body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I just started Developing Web App (Vue.js) for my company for around 1-2 months. Therefore, my knowledge and experience in HTML, CSS and Javascript is kinda shallow.</p>
<p>I've created a custom resizable split DIVs and it working just fine as what I wanted. However, I would like to know if my code is a good code or a bad code.</p>
<p><a href="https://codepen.io/aziziaziz/pen/yLBeRxQ" rel="nofollow noreferrer">Live demo</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var dividerRef = '';
var currentDivider = null;
var leftDivider = null;
var rightDivider = null;
var leftRightDivider = null;
var topLeft = null;
var topRight = null;
var bottomLeft = null;
var bottomRight = null;
var app = new Vue({
el: '#app',
methods:
{
dividerDragStart: function(e) {
e.dataTransfer.setDragImage(new Image, 0, 0);
},
dividerDrag: function(e) {
if (dividerRef == 'lrDivider') {
currentDivider.style.left = e.clientX + 'px';
leftDivider.style.width = (e.clientX + 2) + 'px';
rightDivider.style.left = (e.clientX) + 'px';
rightDivider.style.width = (window.innerWidth - e.clientX + 2) + 'px';
topLeft.style.width = e.clientX + 'px';
bottomLeft.style.width = e.clientX + 'px';
topRight.style.left = e.clientX + 'px';
topRight.style.width = (window.innerWidth - e.clientX + 2) + 'px';
bottomRight.style.left = e.clientX + 'px';
bottomRight.style.width = (window.innerWidth - e.clientX + 2) + 'px';
} else if (dividerRef == 'rtbDivider') {
currentDivider.style.top = (e.clientY) + 'px';
topRight.style.height = (e.clientY) + 'px'
bottomRight.style.height = (window.innerHeight - e.clientY) + 'px';
bottomRight.style.top = (e.clientY) + 'px';
} else if (dividerRef == 'ltbDivider') {
currentDivider.style.top = (e.clientY) + 'px';
topLeft.style.height = (e.clientY) + 'px'
bottomLeft.style.height = (window.innerHeight - e.clientY) + 'px';
bottomLeft.style.top = (e.clientY) + 'px';
}
},
dividerMouseDown: function(name) {
dividerRef = name;
currentDivider = this.$refs[dividerRef];
},
dividerDragEnd: function(e) {
if (dividerRef == 'lrDivider') {
currentDivider.style.left = e.clientX + 'px';
leftDivider.style.width = (e.clientX + 2) + 'px';
rightDivider.style.left = (e.clientX) + 'px';
rightDivider.style.width = (window.innerWidth - e.clientX + 2) + 'px';
topLeft.style.width = e.clientX + 'px';
bottomLeft.style.width = e.clientX + 'px';
topRight.style.left = e.clientX + 'px';
topRight.style.width = (window.innerWidth - e.clientX + 2) + 'px';
bottomRight.style.left = e.clientX + 'px';
bottomRight.style.width = (window.innerWidth - e.clientX + 2) + 'px';
} else if (dividerRef == 'rtbDivider') {
currentDivider.style.top = (e.clientY) + 'px';
topRight.style.height = (e.clientY) + 'px'
bottomRight.style.height = (window.innerHeight - e.clientY) + 'px';
bottomRight.style.top = (e.clientY) + 'px';
} else if (dividerRef == 'ltbDivider') {
currentDivider.style.top = (e.clientY) + 'px';
topLeft.style.height = (e.clientY) + 'px'
bottomLeft.style.height = (window.innerHeight - e.clientY) + 'px';
bottomLeft.style.top = (e.clientY) + 'px';
}
dividerRef = '';
currentDivider = null;
}
},
mounted() {
topLeft = this.$refs.topLeft;
topRight = this.$refs.topRight;
bottomLeft = this.$refs.bottomLeft;
bottomRight = this.$refs.bottomRight;
var heightHalf = (window.innerHeight - 80) / 2;
var widthHalf = window.innerWidth / 2;
leftDivider = this.$refs.ltbDivider;
rightDivider = this.$refs.rtbDivider;
leftRightDivider = this.$refs.lrDivider;
}
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<div class="top-left" ref="topLeft">
<div class="text-area">
<h3>Resize me using the black bars</h3>
</div>
</div>
<div class="top-right" ref="topRight">
<div class="text-area">
<h3>Resize me using the black bars</h3>
</div>
</div>
<div class="bottom-left" ref="bottomLeft">
<div class="text-area">
<h3>Resize me using the black bars</h3>
</div>
</div>
<div class="bottom-right" ref="bottomRight">
<div class="text-area">
<h3>Resize me using the black bars</h3>
</div>
</div>
<div class="left-right divider" ref="lrDivider" @mousedown="dividerMouseDown('lrDivider')" draggable="true"
@drag="dividerDrag" @dragend="dividerDragEnd" @dragstart="dividerDragStart"></div>
<div class="right-top-bottom divider" ref="rtbDivider" @mousedown="dividerMouseDown('rtbDivider')" draggable="true"
@drag="dividerDrag" @dragend="dividerDragEnd" @dragstart="dividerDragStart"></div>
<div class="left-top-bottom divider" ref="ltbDivider" @mousedown="dividerMouseDown('ltbDivider')" draggable="true"
@drag="dividerDrag" @dragend="dividerDragEnd" @dragstart="dividerDragStart"></div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<h2>Manipulating DOM with VueJS</h2>\n\n<p>The biggest comment I have about this code is that it modifies DOM elements using vanillaJS techniques. With VueJS, there are ways of achieving this without needing to reference those elements via properties like <em>id</em> or <em>ref</em>. One way is to use <a href=\"https://vuejs.org/v2/guide/computed.html\" rel=\"nofollow noreferrer\">computed properties</a> and <a href=\"https://vuejs.org/v2/guide/class-and-style.html#Binding-Inline-Styles\" rel=\"nofollow noreferrer\">bound styles</a>. See rewritten code below for examples.</p>\n\n<h2>Other review points</h2>\n\n<h3>Global variables</h3>\n\n<p>This code relies heavily on global variables (e.g. <code>dividerRef</code>, <code>currentDivider</code>, <code>leftDivider</code>, <code>rightDivider</code>, etc.). Unless those variables are needed for other code, the Vue instance's <a href=\"https://vuejs.org/v2/guide/instance.html#Data-and-Methods\" rel=\"nofollow noreferrer\"><code>data</code></a> object can be used to store properties used within the various methods.</p>\n\n<h3>Readability aspect: indentation</h3>\n\n<p>The code is somewhat difficult to read because indentation is inconsistent. Particularly lines like these:</p>\n\n<blockquote>\n<pre><code>var app = new Vue({\n el: '#app',\n methods: \n {\n dividerDragStart: function(e) {\n e.dataTransfer.setDragImage(new Image, 0, 0);\n },\n dividerDrag: function(e) {\n if (dividerRef == 'lrDivider') {\n currentDivider.style.left = e.clientX + 'px';\n</code></pre>\n</blockquote>\n\n<p>It is best to keep indentation consistent - e.g. two or four spaces or single tab per nesting level.</p>\n\n<h3>Repeated code</h3>\n\n<p>There is a lot of duplicated code in methods <code>dividerDrag()</code> and <code>dividerDragEnd()</code> - all lines except the last few of the latter function appear to be repeated, and <code>dividerDragEnd</code> could just call <code>dividerDrag</code> (which could be renamed to avoid confusion) or those duplicate lines could be abstracted out to a separate function that can be called by both. </p>\n\n<h3>Unused variables</h3>\n\n<p>Variables <code>heightHalf</code> and <code>widthHalf</code> appear to be unused after being assigned a value in the <code>mounted</code> method. Those can be removed.</p>\n\n<h3>Styles can be consolidated</h3>\n\n<p>The CSS for the <code><div></code> elements that contain the text-area elements could be consolidated - e.g. give them all a class called <code>container</code>:</p>\n\n<pre><code>.container {\n position: absolute;\n overflow: scroll;\n top: 0;\n left: 0;\n height: 50%;\n width: 50%;\n}\n</code></pre>\n\n<p>Then the existing styles can be simplified to simple colors and position overrides: </p>\n\n<pre><code>top-left {\n background-color: pink;\n}\n\n.top-right {\n background-color: lightgreen;\n left: 50%;\n}\n\n.bottom-left {\n background-color: lightblue;\n top: 50%;\n}\n\n.bottom-right {\n background-color: lightyellow;\n top: 50%;\n left: 50%;\n}\n</code></pre>\n\n<h2>Alternative approach</h2>\n\n<p>As mentioned above, computed properties and bound styles can be used to manipulate the DOM elements instead of referencing the DOM elements by <em>ref</em> attributes.</p>\n\n<p>Notice the <code>data</code> property of the vue instance contains three values, initially set to empty strings, to store the positions of the dividers. When the dividers are dragged, those properties get updated accordingly. Then the computed values for the styles will be changed automatically.</p>\n\n<p>With this approach, there are only four small methods needed to handle the drag events, and there is no need to have methods bound to the <code>dragend</code> or <code>mousedown</code> events on the dividers. All of the style properties are computed after the data values are updated. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var app = new Vue({\n el: '#app',\n data: {\n lrDividerPos: '',\n rtbDividerPos: '',\n ltbDividerPos: '',\n },\n computed: {\n bottomLeftStyle: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.width = this.lrDividerPos + 'px';\n }\n if (this.ltbDividerPos) {\n style.height = (window.innerHeight - this.ltbDividerPos) + 'px';\n style.top = this.ltbDividerPos + 'px';\n }\n return style;\n },\n bottomRightStyle: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.left = this.lrDividerPos + 'px';\n style.width = (window.innerWidth - this.lrDividerPos + 2) + 'px';\n }\n if (this.rtbDividerPos) {\n style.top = this.rtbDividerPos + 'px';\n style.height = (window.innerHeight - this.rtbDividerPos) + 'px';\n }\n return style;\n },\n leftDividerStyles: function() {\n if (this.lrDividerPos) {\n return {\n width: (this.lrDividerPos + 2) + 'px'\n };\n }\n return {};\n },\n ltbDividerStyles: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.width = this.lrDividerPos + 2 + 'px';\n }\n if (this.ltbDividerPos) {\n style.top = this.ltbDividerPos + 'px';\n }\n return style;\n },\n lrDividerStyles: function() {\n if (this.lrDividerPos) {\n return {\n left: this.lrDividerPos + 'px'\n };\n }\n return {};\n },\n rtbDividerStyles: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.left = this.lrDividerPos + 'px';\n style.width = (window.innerWidth - this.lrDividerPos + 2) + 'px';\n }\n if (this.rtbDividerPos) {\n style.top = this.rtbDividerPos + 'px';\n }\n return style;\n },\n topLeftStyle: function() {\n const style = {};\n if (this.ltbDividerPos) {\n style.height = this.ltbDividerPos + 'px';\n }\n if (this.lrDividerPos) {\n style.width = this.lrDividerPos + 'px';\n }\n return style;\n },\n topRightStyle: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.left = this.lrDividerPos + 'px';\n style.width = (window.innerWidth - this.lrDividerPos + 2) + 'px';\n }\n if (this.rtbDividerPos) {\n style.height = this.rtbDividerPos + 'px';\n }\n return style;\n }\n },\n methods: {\n lrDividerDrag: function(e) {\n if (e.clientX) {\n this.lrDividerPos = e.clientX;\n }\n },\n ltbDividerDrag: function(e) {\n if (e.clientY) {\n this.ltbDividerPos = e.clientY;\n }\n },\n rtbDividerDrag: function(e) {\n if (e.clientY) {\n this.rtbDividerPos = e.clientY;\n }\n },\n dividerDragStart: function(e) {\n e.dataTransfer.setDragImage(new Image, 0, 0);\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.text-area {\n margin: 10px;\n}\n\n.top-left {\n position: absolute;\n background-color: pink;\n overflow: scroll;\n top: 0;\n left: 0;\n height: 50%;\n width: 50%;\n}\n\n.top-right {\n position: absolute;\n background-color: lightgreen;\n overflow: scroll;\n top: 0;\n left: 50%;\n height: 50%;\n width: 50%;\n}\n\n.bottom-left {\n position: absolute;\n background-color: lightblue;\n overflow: scroll;\n top: 50%;\n left: 0;\n height: 50%;\n width: 50%;\n}\n\n.bottom-right {\n position: absolute;\n background-color: lightyellow;\n overflow: scroll;\n top: 50%;\n left: 50%;\n height: 50%;\n width: 50%;\n}\n\n.divider {\n position: absolute;\n background-color: black;\n}\n\n.left-right {\n width: 4px;\n height: 100%;\n top: 0;\n left: calc(50% - 4px / 2);\n}\n\n.right-top-bottom {\n width: 50%;\n height: 4px;\n top: calc(50% - 4px / 2);\n left: 50%;\n}\n\n.left-top-bottom {\n width: 50%;\n height: 4px;\n top: calc(50% - 4px / 2);\n left: 0;\n}\n\n.left-right:hover {\n cursor: col-resize;\n}\n\n.left-top-bottom:hover,\n.right-top-bottom:hover {\n cursor: row-resize;\n}\n\n::-webkit-scrollbar {\n height: 0;\n width: 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"></script>\n\n<div id=\"app\">\n <div>\n <div class=\"top-left\" :style=\"topLeftStyle\">\n <div class=\"text-area\">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n <div class=\"top-right\" :style=\"topRightStyle\">\n <div class=\"text-area\">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n <div class=\"bottom-left\" :style=\"bottomLeftStyle\">\n <div class=\"text-area\">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n <div class=\"bottom-right\" :style=\"bottomRightStyle\">\n <div class=\"text-area\">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n\n <div class=\"left-right divider\" draggable=\"true\" @dragstart=\"dividerDragStart\" @drag=\"lrDividerDrag\" :style=\"lrDividerStyles\"></div>\n <div class=\"right-top-bottom divider\" draggable=\"true\" @drag=\"rtbDividerDrag\" @dragstart=\"dividerDragStart\" :style=\"rtbDividerStyles\"></div>\n <div class=\"left-top-bottom divider\" draggable=\"true\" @drag=\"ltbDividerDrag\" @dragstart=\"dividerDragStart\" :style=\"ltbDividerStyles\"></div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The computed properties could be simplified using shorthand notations and ternary operators. For example, instead of conditionally setting properties on each object, always apply it and the browser will accept it if it is a valid rule. For some rules, a ternary operator can be used to either add a value or an empty string - e.g.</p>\n\n<p>instead of </p>\n\n<pre><code>ltbDividerStyles: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.width = this.lrDividerPos + 2 + 'px';\n }\n if (this.ltbDividerPos) {\n style.top = this.ltbDividerPos + 'px';\n }\n return style;\n},\n</code></pre>\n\n<p>it can be simplified to:</p>\n\n<pre><code> ltbDividerStyles: function() {\n return {\n top: this.ltbDividerPos + 'px',\n width: this.lrDividerPos ? this.lrDividerPos + 2 + 'px' : ''\n };\n },\n</code></pre>\n\n<p>Full simplification: </p>\n\n<pre><code>computed: {\n bottomLeftStyle: function() { \n return {\n height: (window.innerHeight - this.ltbDividerPos) + 'px',\n top: this.ltbDividerPos + 'px',\n width: this.lrDividerPos + 'px'\n };\n },\n bottomRightStyle: function() {\n return {\n height: (window.innerHeight - this.rtbDividerPos) + 'px',\n left: this.lrDividerPos + 'px',\n top: this.rtbDividerPos + 'px', \n width: (window.innerWidth - this.lrDividerPos + 2) + 'px'\n };\n }, \n leftDividerStyles: function() {\n return {width: (this.lrDividerPos + 2) + 'px'};\n },\n ltbDividerStyles: function() {\n return {\n top: this.ltbDividerPos + 'px',\n width: this.lrDividerPos ? this.lrDividerPos + 2 + 'px' : ''\n };\n },\n lrDividerStyles: function() {\n return {left: this.lrDividerPos + 'px'};\n },\n rtbDividerStyles: function() {\n return {\n left: this.lrDividerPos + 'px',\n top: this.rtbDividerPos + 'px',\n width: (window.innerWidth - this.lrDividerPos + 2) + 'px'\n };\n },\n topLeftStyle: function() { \n return {\n height: this.ltbDividerPos + 'px',\n width: this.lrDividerPos + 'px'\n };\n },\n topRightStyle: function() {\n return {\n height: this.rtbDividerPos + 'px',\n left: this.lrDividerPos + 'px',\n width: (window.innerWidth - this.lrDividerPos + 2) + 'px'\n };\n }\n },\n</code></pre>\n\n<p>Another option might be to use negative values for the initial divider position values in the <code>data</code> property, and only if those values are non-negative use them in the computed properties.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var app = new Vue({\n el: '#app',\n data: {\n lrDividerPos: -1,\n rtbDividerPos: -1,\n ltbDividerPos: -1,\n },\n computed: {\n bottomLeftStyle: function() {\n return {\n height: this.ltbDividerPos > -1 ? (window.innerHeight - this.ltbDividerPos) + 'px' : '',\n top: this.ltbDividerPos > -1 ? this.ltbDividerPos + 'px' : '',\n width: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : ''\n };\n },\n bottomRightStyle: function() {\n return {\n height: this.rtbDividerPos > -1 ? (window.innerHeight - this.rtbDividerPos) + 'px' : '',\n left: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : '',\n top: this.rtbDividerPos > -1 ? this.rtbDividerPos + 'px' : '',\n width: this.lrDividerPos > -1 ? (window.innerWidth - this.lrDividerPos + 2) + 'px' : ''\n };\n },\n leftDividerStyles: function() {\n return {\n width: this.lrDividerPos > -1 ? (this.lrDividerPos + 2) + 'px' : ''\n };\n },\n ltbDividerStyles: function() {\n return {\n top: this.ltbDividerPos > -1 ? this.ltbDividerPos + 'px' : '',\n width: this.lrDividerPos > -1 ? this.lrDividerPos + 2 + 'px' : ''\n };\n },\n lrDividerStyles: function() {\n return {\n left: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : ''\n };\n },\n rtbDividerStyles: function() {\n return {\n left: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : '',\n top: this.rtbDividerPos > -1 ? this.rtbDividerPos + 'px' : '',\n width: this.lrDividerPos > -1 ? (window.innerWidth - this.lrDividerPos + 2) + 'px' : ''\n };\n },\n topLeftStyle: function() {\n return {\n height: this.ltbDividerPos > -1 ? this.ltbDividerPos + 'px' : '',\n width: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : ''\n };\n },\n topRightStyle: function() {\n return {\n height: this.rtbDividerPos > -1 ? this.rtbDividerPos + 'px' : '',\n left: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : '',\n width: this.lrDividerPos > -1 ? (window.innerWidth - this.lrDividerPos + 2) + 'px' : ''\n };\n }\n },\n methods: {\n lrDividerDrag: function(e) {\n if (e.clientX) {\n this.lrDividerPos = e.clientX;\n }\n },\n ltbDividerDrag: function(e) {\n if (e.clientY) {\n this.ltbDividerPos = e.clientY;\n }\n },\n rtbDividerDrag: function(e) {\n if (e.clientY) {\n this.rtbDividerPos = e.clientY;\n }\n },\n dividerDragStart: function(e) {\n e.dataTransfer.setDragImage(new Image, 0, 0);\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.text-area {\n margin: 10px;\n}\n\n.top-left {\n position: absolute;\n background-color: pink;\n overflow: scroll;\n top: 0;\n left: 0;\n height: 50%;\n width: 50%;\n}\n\n.top-right {\n position: absolute;\n background-color: lightgreen;\n overflow: scroll;\n top: 0;\n left: 50%;\n height: 50%;\n width: 50%;\n}\n\n.bottom-left {\n position: absolute;\n background-color: lightblue;\n overflow: scroll;\n top: 50%;\n left: 0;\n height: 50%;\n width: 50%;\n}\n\n.bottom-right {\n position: absolute;\n background-color: lightyellow;\n overflow: scroll;\n top: 50%;\n left: 50%;\n height: 50%;\n width: 50%;\n}\n\n.divider {\n position: absolute;\n background-color: black;\n}\n\n.left-right {\n width: 4px;\n height: 100%;\n top: 0;\n left: calc(50% - 4px / 2);\n}\n\n.right-top-bottom {\n width: 50%;\n height: 4px;\n top: calc(50% - 4px / 2);\n left: 50%;\n}\n\n.left-top-bottom {\n width: 50%;\n height: 4px;\n top: calc(50% - 4px / 2);\n left: 0;\n}\n\n.left-right:hover {\n cursor: col-resize;\n}\n\n.left-top-bottom:hover,\n.right-top-bottom:hover {\n cursor: row-resize;\n}\n\n::-webkit-scrollbar {\n height: 0;\n width: 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"></script>\n\n<div id=\"app\">\n <div>\n <div class=\"top-left\" :style=\"topLeftStyle\">\n <div class=\"text-area\">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n <div class=\"top-right\" :style=\"topRightStyle\">\n <div class=\"text-area\">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n <div class=\"bottom-left\" :style=\"bottomLeftStyle\">\n <div class=\"text-area\">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n <div class=\"bottom-right\" :style=\"bottomRightStyle\">\n <div class=\"text-area\">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n\n <div class=\"left-right divider\" draggable=\"true\" @dragstart=\"dividerDragStart\" @drag=\"lrDividerDrag\" :style=\"lrDividerStyles\"></div>\n <div class=\"right-top-bottom divider\" draggable=\"true\" @drag=\"rtbDividerDrag\" @dragstart=\"dividerDragStart\" :style=\"rtbDividerStyles\"></div>\n <div class=\"left-top-bottom divider\" draggable=\"true\" @drag=\"ltbDividerDrag\" @dragstart=\"dividerDragStart\" :style=\"ltbDividerStyles\"></div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T17:36:58.920",
"Id": "232396",
"ParentId": "230486",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T10:34:16.950",
"Id": "230486",
"Score": "6",
"Tags": [
"javascript",
"html",
"event-handling",
"sass",
"vue.js"
],
"Title": "Resizable split DIVs Vue.js"
}
|
230486
|
<p>This app will be a FTP desktop application meant to transfer files between a server and a client, pretty much like Filezilla, there is no server code to show as I will not implement Network features until I have reached a comfortable design architecture.</p>
<p>It is a qt Gui program, and I wish to construct it in a way that has a good Mvc design principles, meaning the View class is only responsible for the UI elements, Model class will only be responsible to perform action around Data, and neither class will be aware of one another.</p>
<p>I did not want to construct the Model Class from inside or alongside the UI class as I feel it makes my code too co-dependent, meaning if I would want to update the UI from inside the Data class I would have to pass a pointer to the main View class,but to me that seems like a badly written design, each class should not be aware of other parts of the program and should only be responsible to their own actions, which is why I've decided to go use a single controller class that would combine SIGNALS and SLOTS from the View and Data classes.</p>
<p>If the View class detects a button press, it simply raises a flag (signal), the Model class has its own function responsible for processing that request (slot), and the controller class is the one that connects that signal and slot, without co-dependency of neither the View or the Model, a different example would be the Model class needing to update a UI element by writing to the screen, it would emit a signal, and the View class would catch it with the slot.</p>
<p>I believe this way of working makes this type of a project easier to be re-useable, as these classes are not intrinsically tied to each other, by theory if ever needed, it should be easier to re-write the Model or the View class should the need arise, but I'm curious to get some second opinions going forward.</p>
<p>Is this good Mvc design?
it could be that this way of writing the code is simply not worth the hassle of managing the extra controller class.</p>
<p><strong>Bonus question:</strong>
In clientView.h i'm setting clientController to all the UI elements by setting it as a friend class, I believe this is necessary for ease of use, instead of setting up multiple redundant get pointers functions for the UI class I simply set up the controller as a friend class.
do you believe this is a bad practice in this situation?</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include "stdafx.h"
#include "clientController.h"
int main(int argc, char *argv[])
{
clientController controller(argc, argv);
return controller.init();
}
</code></pre>
<p><strong>clientController.h</strong></p>
<pre><code>#pragma once
#include "stdafx.h"
#include "clientView.h"
#include "clientModel.h"
class clientController : public QObject
{
public:
clientController(int argc, char* argv[], QWidget* parent = Q_NULLPTR);
int init();
private:
Q_OBJECT
QApplication app;
clientView window;
clientModel data;
};
</code></pre>
<p><strong>clientController.cpp</strong></p>
<pre><code> #include "stdafx.h"
#include "clientController.h"
clientController::clientController(int argc, char* argv[], QWidget* parent) : QObject(parent), app(argc, argv) { }
int clientController::init()
{
//**** This is the part responsible for connecting the signals and slots for the View and the Model.
connect(window.ui.connectButton, &QPushButton::clicked, &data, &clientModel::connect);
connect(&data, &clientModel::writeTextSignal, &window, &clientView::writeTextToScreen);
window.show();
return app.exec();
}
</code></pre>
<p><strong>clientView.h</strong></p>
<pre><code> #pragma once
#include "stdafx.h"
#include "ui_clientView.h"
class clientView : public QMainWindow
{
public:
explicit clientView(QWidget* parent = Q_NULLPTR);
public slots:
void writeTextToScreen(QString text);
private:
Q_OBJECT
Ui::clientView ui;
friend class clientController;
//*** Take note that i'm exposing clientController to all the UI elements.
};
</code></pre>
<p><strong>clientView.cpp</strong></p>
<pre><code>#include "stdafx.h"
#include "clientView.h"
clientView::clientView(QWidget *parent) : QMainWindow(parent)
{
ui.setupUi(this);
}
void clientView::writeTextToScreen(QString text)
{
ui.mainTextWindow->append(text);
}
</code></pre>
<p><strong>clientModel.h</strong></p>
<pre><code>#pragma once
#include "stdafx.h"
class clientModel : public QObject
{
Q_OBJECT
public:
signals:
void writeTextSignal(QString text);
public slots:
void connect();
void updateData();
};
</code></pre>
<p><strong>clientModel.cpp</strong></p>
<pre><code>#include "stdafx.h"
#include "clientModel.h"
void clientModel::connect()
{
qDebug() << "void clientModel::connect()";
emit writeTextSignal("Attempting Connection To FTP Server");
}
void clientModel::updateData()
{
emit writeTextSignal("Updating data");
}
</code></pre>
<p><strong>auto generated qt code: ui_clientView.h</strong></p>
<pre><code>#ifndef UI_CLIENTVIEW_H
#define UI_CLIENTVIEW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_clientView
{
public:
QAction *actionExit;
QAction *actionOptions;
QWidget *centralWidget;
QTextEdit *mainTextWindow;
QPushButton *connectButton;
QMenuBar *menuBar;
QMenu *menuFile;
QMenu *menuOptions;
void setupUi(QMainWindow *clientView)
{
if (clientView->objectName().isEmpty())
clientView->setObjectName(QString::fromUtf8("clientView"));
clientView->resize(640, 486);
actionExit = new QAction(clientView);
actionExit->setObjectName(QString::fromUtf8("actionExit"));
actionOptions = new QAction(clientView);
actionOptions->setObjectName(QString::fromUtf8("actionOptions"));
centralWidget = new QWidget(clientView);
centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
mainTextWindow = new QTextEdit(centralWidget);
mainTextWindow->setObjectName(QString::fromUtf8("mainTextWindow"));
mainTextWindow->setGeometry(QRect(60, 30, 511, 241));
mainTextWindow->setReadOnly(true);
mainTextWindow->setTextInteractionFlags(Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse);
connectButton = new QPushButton(centralWidget);
connectButton->setObjectName(QString::fromUtf8("connectButton"));
connectButton->setGeometry(QRect(60, 320, 91, 31));
clientView->setCentralWidget(centralWidget);
menuBar = new QMenuBar(clientView);
menuBar->setObjectName(QString::fromUtf8("menuBar"));
menuBar->setGeometry(QRect(0, 0, 640, 21));
menuFile = new QMenu(menuBar);
menuFile->setObjectName(QString::fromUtf8("menuFile"));
menuOptions = new QMenu(menuBar);
menuOptions->setObjectName(QString::fromUtf8("menuOptions"));
clientView->setMenuBar(menuBar);
menuBar->addAction(menuFile->menuAction());
menuBar->addAction(menuOptions->menuAction());
menuFile->addAction(actionExit);
menuOptions->addAction(actionOptions);
retranslateUi(clientView);
QMetaObject::connectSlotsByName(clientView);
} // setupUi
void retranslateUi(QMainWindow *clientView)
{
clientView->setWindowTitle(QCoreApplication::translate("clientView", "client", nullptr));
actionExit->setText(QCoreApplication::translate("clientView", "Exit", nullptr));
actionOptions->setText(QCoreApplication::translate("clientView", "Options", nullptr));
connectButton->setText(QCoreApplication::translate("clientView", "Connect", nullptr));
menuFile->setTitle(QCoreApplication::translate("clientView", "File", nullptr));
menuOptions->setTitle(QCoreApplication::translate("clientView", "Tools", nullptr));
} // retranslateUi
};
namespace Ui {
class clientView: public Ui_clientView {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_CLIENTVIEW_H
</code></pre>
<p><strong>stdafx.h</strong></p>
<pre><code>#include <QtWidgets>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T14:54:15.213",
"Id": "449054",
"Score": "0",
"body": "Are you using Visual Studio 2017 or 2019?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T15:53:55.060",
"Id": "449096",
"Score": "1",
"body": "Visual studio 2019 Community version, with build Tools MSVC v142, and v141 ( through the visual studio installer). qt version 5.13.1, compiler msvc2017, and qtVS tools 2.4.1."
}
] |
[
{
"body": "<p>There isn't a lot I see that can be improved; nevertheless:</p>\n\n<h2>Initialization vs. execution</h2>\n\n<p>Your <code>clientController::init</code> is misnamed. It does both initialization as well as running the main application loop. It'd probably better if you separated those two functions. This code:</p>\n\n<pre><code>//**** This is the part responsible for connecting the signals and slots for the View and the Model.\n connect(window.ui.connectButton, &QPushButton::clicked, &data, &clientModel::connect);\n connect(&data, &clientModel::writeTextSignal, &window, &clientView::writeTextToScreen);\n</code></pre>\n\n<p>should go in the constructor if possible; then <code>execute</code> would only do:</p>\n\n<pre><code> window.show();\n return app.exec();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:28:13.933",
"Id": "230509",
"ParentId": "230488",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230509",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T10:55:51.360",
"Id": "230488",
"Score": "6",
"Tags": [
"c++",
"mvc",
"gui",
"qt"
],
"Title": "Mvc design for FTP Client"
}
|
230488
|
<p>As of now the below code working As expected. But in future if the <strong>newFilterArr</strong> have new record again I want to reedit this functionality. So how to overcome this?</p>
<pre><code>function Optimiz() {
let courseFilter = this.newFilterArr.find(k => k.key === 'courseId'),
rateTypeFilter = this.newFilterArr.find(k => k.key === 'rateTypeId');
this.rateSetupDataUI = this.originalRateSetupDataUI.filter(x => {
if (courseFilter && rateTypeFilter) {
return x['courseId'] === courseFilter.filtered.id && x['rateTypeId'] === rateTypeFilter.filtered.id;
} else if (courseFilter && !rateTypeFilter) {
return x['courseId'] === courseFilter.filtered.id
} else if (!courseFilter && rateTypeFilter) {
return x['rateTypeId'] === rateTypeFilter.filtered.id;
}
});
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>let courseFilter = this.newFilterArr.find(k => k.key === 'courseId'),\n rateTypeFilter = this.newFilterArr.find(k => k.key === 'rateTypeId');\n</code></pre>\n\n<p>I would consider making your filter an object instead of an array. The keys are probably unique and known ahead of time, thus could be a type.</p>\n\n<pre><code> if (courseFilter && rateTypeFilter) {\n return x['courseId'] === courseFilter.filtered.id && x['rateTypeId'] === rateTypeFilter.filtered.id;\n } else if (courseFilter && !rateTypeFilter) {\n return x['courseId'] === courseFilter.filtered.id\n } else if (!courseFilter && rateTypeFilter) {\n return x['rateTypeId'] === rateTypeFilter.filtered.id;\n }\n</code></pre>\n\n<p>This code is a good example of a function doing too many things. You can just progressively filter, filtering by <code>courseId</code> first, and whatever results from that, you filter with <code>rateTypeId</code>. The condition with the <code>&&</code> is not necessary. </p>\n\n<p>This could be rewritten as:</p>\n\n<pre><code>class Filter {\n courseId:string\n rateTypeId:string\n}\n\nfunction Optimiz() {\n const filter:Filter = this.newFilterObj\n\n // Match only if filter is a truthy value. Otherwise, just add it.\n this.rateSetupDataUi = this.originalRateSetupDataUI\n .filter(x => filter.courseId ? x.courseId === filter.courseId : true)\n .filter(x => filter.rateTypeId ? x.rateTypeId === filter.rateTypeId : true)\n}\n</code></pre>\n\n<h2>Nitpicks</h2>\n\n<ul>\n<li>I advise against a single <code>let</code>/<code>var</code>/<code>const</code> and recommend a <code>let</code>/<code>var</code>/<code>const</code> <em>per</em> variable. Prepending/appending requires needlessly modifying the first and last lines, respectively. And if you move variables around, you will still have to add <code>let</code>/<code>var</code>/<code>const</code>.</li>\n<li><code>x['courseId']</code> and <code>x['rateTypeId']</code> don't need to be in bracket notation, as the property names don't have invalid characters.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T13:18:20.760",
"Id": "230493",
"ParentId": "230490",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:24:32.447",
"Id": "230490",
"Score": "1",
"Tags": [
"javascript",
"angular-2+"
],
"Title": "Compare multiple values of an array in the same time in Javascript"
}
|
230490
|
<p>I designed a (q)spi controller which can be configured over generics in QSYS(Quartus) and acts as an avalon slave.</p>
<p>The documentation started in german, so please bear with the partial translation.</p>
<p>I want to know if I can improve my signal handling or naming of my variables (or lets just say: what can be done better and how).
We are two in our team and there is no code review and most of the time we define signal naming, or how to write vhdl code for ourselves.</p>
<p>The following code is a snipped:</p>
<pre><code> -- altera vhdl_input_version vhdl_2008
-- (Q)SPI Controller for communiction with an Avalon Master
-- Parametizeable over the GUI of QSYS - see *_hw.tcl
-- Calculation of ports is done in the *_hw.tcl file
-- Has to be done manually for simulation
-- Function:
-- zim_qspi_controller :
-- Top level - Communication with AVM and all components
-- flash_comp_cmd_V* :
-- Gets r/w and cmd codes signals from zim_qspi_controller
-- communicates directly with the SPI lines
-- clk_domain_sync and clk_domain_port_sync:
-- DFFs for synchronization between domains
-- dcfifo:
-- Intel IP for a FIFO
-- s1_* signals that the signal is in clk_domain 1 (avalon clock)
-- s2_* signals that the signal is in clk_domain 2 (spi_clock)
-- V01:
/* Basic functions implemented
The AVS_CSR(32 upto 63) = Unique ID and so on
max Burstbytes = Number Bytes from the Fifo
*/
-- CSR can be read back to check if the settings were taken
-- From QSPI_DEF_PACK:
/* CSR Interface - Bit Mapping */
/* Wird hier was geaendert sind in der Architektur die Konstanten anzupassen */
/*constant FR_BIT : natural := 0;
constant PP_BIT : natural := 1;
constant FRQIO_BIT : natural := 2; -- Normalerweise Dummy Cycle
constant PPQ_BIT : natural := 3;
constant FRDIO_BIT : natural := 4; -- Normalerweise Dummy Cycle
constant FRDO_BIT : natural := 5;
constant RD_BIT : natural := 6;
constant FRQO_BIT : natural := 7; --0x80
constant PERRSM_BIT : natural := 8;
constant RDID_BIT : natural := 9;
constant RDUID_BIT : natural := 10;
constant RDJDID_BIT : natural := 11; --x800
constant RDMDID_BIT : natural := 12;
constant RDSFDP_BIT : natural := 13;
constant RSTEN_BIT : natural := 14;
constant RST_BIT : natural := 15; --x8000
constant IRRD_BIT : natural := 16;
constant SER_BIT : natural := 17;
constant BER32K_BIT : natural := 18;
constant BER64K_BIT : natural := 19; --x8 0000
constant CER_BIT : natural := 20;
constant WER_BIT : natural := 21;
constant WRSR_BIT : natural := 22;
constant WRFR_BIT : natural := 23; --x80 0000
constant RDSR_BIT : natural := 24;
constant RDFR_BIT : natural := 25;
*/
library altera_mf;
use altera_mf.all;
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use ieee.math_real.all;
use WORK.avm_behav_pack.all;
use WORK.QSPI_DEF_PACK.all; -- Functions and constants
use IEEE.math_real.all; -- Only for pre synthesis
entity zim_qspi_controller is
generic (
constant FPGA_TYPE : string := "MAX 10";
constant DEVICE_FAMILY : string := "IS25LQ";
constant FIFO_WORDS : natural := 32;
constant DEF_MODE : string := "QUAD MODE";
constant SYNC_STAGES : natural := 2;
constant ENDIAN : string := "BIG";
constant AVALON_BUS_DATA_BYTES : natural := 4;
constant ADDRESS_BITS : natural := 10;
constant SLAVE_LATENCY : natural := 1;
constant PERM_WR_ENA : boolean := TRUE;
constant RESET_CMD_AFTER_EXEC : boolean := TRUE; -- sets the FLASH in R/W condition after each command
constant CHECK_STATUS_REG_BEFORE_WRITE : boolean := TRUE -- checks if the FLASH is in IDLE condition before each write - Important for interrupted burst operations
);
port (
-- Sys
-- clock interface
csi_clock_clk : in std_logic;
csi_clock_reset_n : in std_logic; -- Koennte auch rsi_reset_n sein
csi_pll_locked : in std_logic;
csi_qspi_clk_in : in std_logic;
csi_qspi_inv_clk_in : in std_logic;
--CSR-Interface
avs_csr_write :in std_logic;
avs_csr_read :in std_logic;
avs_csr_address :in std_logic_vector(0 downto 0);
avs_csr_writedata :in std_logic_vector(31 downto 0);
avs_csr_readdata :out std_logic_vector(31 downto 0);
avs_csr_waitrequest :out std_logic;
--Speicher-Interface
avs_mem_write :in std_logic;
avs_mem_waitrequest :out std_logic;
avs_mem_read :in std_logic;
avs_mem_writedata :in std_logic_vector(AVALON_BUS_DATA_BYTES*8-1 downto 0);
avs_mem_readdata :out std_logic_vector(AVALON_BUS_DATA_BYTES*8-1 downto 0);
avs_mem_readdatavalid :out std_logic;
avs_mem_byteenable :in std_logic_vector(AVALON_BUS_DATA_BYTES-1 downto 0);
--avs_mem_irq :out std_logic;
avs_mem_burstcount :in std_logic_vector (4 downto 0);
avs_mem_address :in std_logic_vector (ADDRESS_BITS-1 downto 0);
-- Flash Verbindung - bridged through flash_comp_cmd_v02 component
coe_qspi_clk : out std_logic;
coe_qspi_cs_n : out std_logic;
coe_qspi_data : inout std_logic_vector(3 downto 0);
coe_pll_locked : out std_logic
);
end entity zim_qspi_controller;
architecture rtl of zim_qspi_controller is
-------- Helper constants --------
constant c_LITTLE_ENDIAN : std_logic := '0';
constant c_BIG_ENDIAN : std_logic := '1';
constant c_CSR_BITS : natural := 32;
constant c_NIOS_BYTES_PER_ADDR : natural := 4;
constant c_FLASH_BYTES_PER_ADDR : natural := get_byte_per_addr(DEVICE_FAMILY);
constant c_BURST_BITS : natural := 5;
constant c_ADDR_MULTIPLIER : natural := c_NIOS_BYTES_PER_ADDR / c_FLASH_BYTES_PER_ADDR; -- TODO: Pruefen auf gerade Zahlen und Vielfaches von 2 assert usw.
constant c_EXT_MODE : std_logic_vector (c_CSR_BITS-1 downto 0) := (others => '0');
constant c_FAST_DUAL_MODE : std_logic_vector (c_CSR_BITS-1 downto 0) := (0=>'1', others => '0');
constant c_FAST_QUAD_MODE : std_logic_vector (c_CSR_BITS-1 downto 0) := (1 =>'1', others => '0');
constant c_NORMAL_MODE : std_logic_vector (c_CSR_BITS-1 downto 0) := (2=> '1', others => '0');
/* CMD mapping
* 4-7 => Dummy
* ---- Ab hier sind Kommandos ----
* 8 => Read Status Register
* 9 => Read Function Register
* 10 => Resume Program/Erase
* 11 => read manufactor and product id
* 12 => read unique ID number
* 13 => read manufacturer and product id by jedec id command
* 14 => read manufacturer and device id
* 15 => sfdp read
* 16 => software reset enable
* 17 => reset (only along with x66)
* 18 => read information row
*/
-------------------------- Components ------------------------
-- clk Domain Sync
component clk_domain_sync
generic ( num_stages : natural := 2);
port (
clk_out : in std_logic;
a_reset_n : in std_logic;
signal_in : in std_logic;
signal_out : out std_logic
);
end component clk_domain_sync;
-- clk Domain Port SYNC
component clk_domain_port_sync is
generic ( NUM_STAGES : natural := 2;
BUS_BITS : natural := 8
);
port (
clk_out : in std_logic;
a_reset_n : in std_logic;
signal_in : in std_logic_vector (BUS_BITS-1 downto 0);
signal_out : out std_logic_vector (BUS_BITS-1 downto 0)
);
end component clk_domain_port_sync;
-- FIFO - Intel IP
COMPONENT dcfifo
GENERIC (
intended_DEVICE_FAMILY : STRING;
lpm_numwords : NATURAL;
lpm_showahead : STRING;
lpm_type : STRING;
lpm_width : NATURAL;
lpm_widthu : NATURAL;
overflow_checking : STRING;
rdsync_delaypipe : NATURAL;
read_aclr_synch : STRING;
underflow_checking : STRING;
use_eab : STRING;
write_aclr_synch : STRING;
wrsync_delaypipe : NATURAL
);
PORT (
aclr : IN STD_LOGIC ;
data : IN STD_LOGIC_VECTOR (lpm_width-1 DOWNTO 0);
rdclk : IN STD_LOGIC ;
rdreq : IN STD_LOGIC ;
wrclk : IN STD_LOGIC ;
wrreq : IN STD_LOGIC ;
q : OUT STD_LOGIC_VECTOR (lpm_width-1 DOWNTO 0);
rdempty : OUT STD_LOGIC ;
rdfull : OUT STD_LOGIC ;
rdusedw : OUT STD_LOGIC_VECTOR (lpm_widthu-1 DOWNTO 0);
wrfull : OUT STD_LOGIC ;
wrempty : OUT STD_LOGIC ;
wrusedw : OUT STD_LOGIC_VECTOR (lpm_widthu-1 DOWNTO 0)
);
END COMPONENT;
-- Flash Comp CMD V02
component flash_comp_cmd_v02 is
generic (
constant DEVICE_FAMILY : string := "IS25LQ";
constant ENDIAN : string := "BIG"
);
port (
csi_clk_clk : in std_logic; -- SPI clock
csi_clk_reset_n : in std_logic;
csi_pll_locked : in std_logic;
csi_comp_ready : out std_logic;
coe_cmd : in std_logic_vector(get_CMD_BITS(DEVICE_FAMILY)-1 downto 0);
coe_spi_addr : in std_logic_vector(get_command_length(DEVICE_FAMILY)*get_addr_multi(DEVICE_FAMILY)-1 downto 0);
coe_spi_comp_busy : out std_logic;
coe_cmd_data : in std_logic_vector (23 downto 0);
coe_write : in std_logic; -- as long as write is active, data will be written on the SPI bus
coe_wrfifo_wait : out std_logic; -- Daten is still being processed
coe_wrfifo_empty : in std_logic;
coe_wrfifo_data : in std_logic_vector (get_command_length(DEVICE_FAMILY)-1 downto 0);
coe_read : in std_logic; -- As long as read is active, there is an read operation to the flash
coe_rdfifo_wait : out std_logic;
coe_rdfifo_data : out std_logic_vector (get_command_length(DEVICE_FAMILY)-1 downto 0); -- Shiftregister output
-- Flash connection
coe_qspi_cs_n :out std_logic;
coe_qspi_data :inout std_logic_vector(3 downto 0)
);
end component;
------------------------ TYPES --------------------------
type avs_csr_register is array (1 downto 0) of std_logic_vector (31 downto 0);
-- Quartus unterstuetzt keine unconstrained records ...(Q18)
---------------------- RECORDS --------------------------
---------------------- Functions ------------------------
--- GET DEFAULT MODE
function get_default_mode (constant DEF_MODE : in string) return std_logic_vector is
variable v_return_vector : std_logic_vector (31 downto 0);
begin
v_return_vector := (others => '0');
IF DEF_MODE = "NORMAL MODE" THEN
v_return_vector := c_NORMAL_MODE;
ELSIF DEF_MODE = "EXTENDED MODE" THEN
v_return_vector := c_EXT_MODE;
ELSIF DEF_MODE = "FAST DUAL MODE" THEN
v_return_vector := c_FAST_DUAL_MODE;
ELSIF DEF_MODE = "QUAD MODE" THEN
v_return_vector := c_FAST_QUAD_MODE;
ELSE
assert FALSE REPORT "Unbekannter Modus: " & DEF_MODE severity ERROR;
END IF;
return v_return_vector;
end get_default_mode;
----------------- Constants -----------------
constant c_ENDIAN : std_logic := get_endian (ENDIAN);
constant c_DEF_CSR : std_logic_vector (31 downto 0) := get_default_mode(DEF_MODE);
------------------- Signals -----------------
--SIGNAL s1_avm_mem_byteenable : std_logic_vector(AVALON_BUS_DATA_BYTES downto 0); -- wir nehmen ein Bit mehr fuer den RD_DATA_ALIGN_PROC
--alias a_byteena_zero_bit : std_logic is s1_avm_mem_byteenable(AVALON_BUS_DATA_BYTES);
---------- Process FSM
-- MAIN PROZESS <-> SPI Controller
SIGNAL s1_spi_read, s1_spi_write : std_logic;
SIGNAL s2_spi_read, s2_spi_write : std_logic;
SIGNAL s1_spi_cmd, s2_spi_cmd : std_logic_vector (get_cmd_bits(DEVICE_FAMILY)-1 downto 0);
SIGNAL s1_spi_addr, s2_spi_addr : std_logic_vector (get_command_length(DEVICE_FAMILY)*get_addr_multi(DEVICE_FAMILY)-1 downto 0);
SIGNAl s1_coe_cmd_data,s2_coe_cmd_data : std_logic_vector (23 downto 0);
--- FIFO
SIGNAL s2_wrfifo_out, s2_rdfifo_data : std_logic_vector (get_command_length(DEVICE_FAMILY)-1 downto 0);
SIGNAL s2_wrfifo_wait, s2_rdfifo_wait,s2_rdfifo_wrreq : std_logic; -- Signals from the flash_comp_cmd_v* component
SIGNAL s1_rdfifo_empty : std_logic;
SIGNAL s1_rdfifo_read, s1_rdfifo_read_avm : std_logic; -- For reading from RDfifo for CSR cmds
SIGNAL s1_clear_rdfifo, s1_aclr_rdfifo : std_logic;
alias spi_clk : std_logic is csi_qspi_clk_in;
SIGNAL s1_rd_ready : std_logic; -- Marker if RDfifo is ready for data
SIGNAL s1_wrfifo_write : std_logic;
SIGNAL s1_wr_data_buffer : unsigned (AVALON_BUS_DATA_BYTES*8-1 downto 0 );
SIGNAL s1_wrfifo_usedw : std_logic_vector (integer(ceil(log2(real(fifo_words))))-1 downto 0);
SIGNAl s1_byte_cnt : unsigned(AVALON_BUS_DATA_BYTES-1 downto 0);
-- WAITREQUEST
SIGNAL s1_avs_readdata_valid, s1_avs_writedata_ack : std_logic;
-- CSR Register
SIGNAL s1_avs_csr : avs_csr_register;
alias a_csr : std_logic_vector (31 downto 0) is s1_avs_csr(0);
alias a_addr : std_logic_vector (23 downto 0) is s1_avs_csr(1)(23 downto 0);
alias a_csr_cmd : std_logic_vector (7 downto 0) is s1_avs_csr(1)(7 downto 0);
-- WrFifo
SIGNAL s1_wrfifo_full, s2_wrfifo_rd_empty : std_logic;
SIGNAL s1_wrfifo_wr_requ : std_logic;
SIGNAL s1_wrfifo_data : std_logic_vector(7 downto 0);
SIGNAL s1_wrfifo_empty : std_logic;
------ Sonstiges ----
alias clk : std_logic is csi_clock_clk;
alias reset_n : std_logic is csi_clock_reset_n;
--SIGNAL s1_csr_busy : std_logic; -- Validation ob CSR Prozess beim Arbeiten ist, ACHTUNG! Kombinatorisch
SIGNAL s1_flash_comp_busy, s2_spi_busy : std_logic;
alias qspi_clk_inv : std_logic is csi_qspi_inv_clk_in; -- We are working with the falling edge of the spi_clk
SIGNAL s2_flash_comp_rdy, s1_flash_comp_rdy : std_logic;
-- RD Data Align Proc
SIGNAL s1_rdfifo_ack : std_logic;
SIGNAL s1_rdfifo_data : std_logic_vector (7 downto 0);
SIGNAL s1_rdfifo_read_req : std_logic;
SIGNAL s1_rd_pre_ack : std_logic; -- For burstcount, waitrequest is set one cycle before readdata_valid
---------------------- BEGIN -------------------------
begin
coe_qspi_clk <= csi_qspi_clk_in;
-------------------- MAIN FSM ------------------------
MAIN_FSM : process (ALL)
type fsm_type is (
IDLE , -- Waiting for cmd
SPI_PREP_CMD , -- Commands ned to be synced
MEM_WRITE , -- WRFIFO is being written - flash_comp_cmd_V* has a direct communication with the FIFO
MEM_READ , -- Read RDFIFO and put data on avalon bus
WAIT_FINISH , -- Wait for flash_comp_cmd_V*
READ_CSR ,
WRITE_CSR ,
EXEC_CMD
);
variable fsm_cur : fsm_type;
--variable v_mode_changed : std_logic; -- Zum schauen ob sich Read/Write geloest hat
variable v_csr_read, v_csr_write : std_logic; -- marker
variable v_mem_read, v_mem_write : std_logic; -- marker;
variable v_wait_for_flash_busy : std_logic;
variable v_cmd_running : std_logic; -- Marker
variable v_wr_requ : std_logic;
variable v_mode_changed : std_logic; -- 1 Pulse, checking if the AVM wants to do something new, while an operation is running
variable v_csr_addr : std_logic_vector (0 downto 0);
--variable v_mem_addr : std_logic_vector (ADDRESS_BITS-1 downto 0);
variable v_avs_csr_wr_valid : std_logic;
variable v_avs_csr_rd_valid : std_logic;
variable v_mem_access : std_logic;
variable v_read_csr_ack : std_logic;
variable v_conv_flash_addr : std_logic_vector (get_command_length(DEVICE_FAMILY)*get_addr_multi(DEVICE_FAMILY)-1 downto 0);
variable v_set_write_enable : std_logic; -- Marker, if set we enable Write Enable of the flash
variable v_status_reg_idle : std_logic; -- When CHECK_FOR_BUSY is set, => 1 if status reg is idle
variable v_csr_write_ack : std_logic; -- Waitrequest Ack
begin
coe_pll_locked <= csi_pll_locked;
-- Waitrequest Kombinatorische Zuweisungen
IF reset_n /= '1' or s1_flash_comp_rdy = '0' THEN
fsm_cur := IDLE; -- Vorbereiten mit den Default Werten
s1_spi_read <= '0';
s1_spi_write <= '0';
v_wait_for_flash_busy := '1';
v_wr_requ := '0';
s1_clear_rdfifo <= '1';
v_read_csr_ack := '0';
s1_rdfifo_read <= '0';
s1_rdfifo_read_avm <= '0';
v_mem_access := '0';
avs_csr_waitrequest <= '1';
avs_mem_waitrequest <= '1';
v_cmd_running := '0';
v_csr_read := '0';
v_csr_write := '0';
v_mem_read := '0';
v_mem_write := '0';
s1_wrfifo_write <= '0';
v_set_write_enable := '0';
avs_mem_readdatavalid <= '0';
s1_avs_readdata_valid <= '0';
v_avs_csr_rd_valid := '0';
v_avs_csr_wr_valid := '0';
v_status_reg_idle := '0';
v_csr_write_ack := '0';
v_conv_flash_addr := (others => '0');
s1_coe_cmd_data <= (others => '0');
s1_spi_addr <= (others => '0');
s1_spi_cmd <= (others => '0');
s1_avs_csr <= (others => (others => '0'));
avs_csr_readdata <= (others => '0');
a_csr <= c_DEF_CSR; -- Reset to the pre configured CSR
ELSIF RISING_EDGE(clk) THEN
v_avs_csr_wr_valid := v_csr_write_ack and not (v_mode_changed or v_cmd_running);
v_avs_csr_rd_valid := (avs_csr_read and v_read_csr_ack); -- Read needs one cycle => s1_csr_busy for one cycle to HIGH
avs_csr_waitrequest <= not ((v_avs_csr_wr_valid or v_avs_csr_rd_valid));
avs_mem_waitrequest <= not (((s1_avs_writedata_ack or s1_avs_readdata_valid)) ) ;
avs_mem_readdatavalid <= s1_rdfifo_ack and v_mem_access;
s1_avs_readdata_valid <= s1_rd_pre_ack and s1_flash_comp_busy and avs_mem_read; --avs_mem_read and not s1_rdfifo_empty and not v_mode_changed;
if v_csr_read then
v_mode_changed := avs_mem_read or avs_mem_write or avs_csr_write;
elsif v_csr_write then
v_mode_changed := avs_mem_read or avs_mem_write or avs_csr_read;
elsif v_mem_read then
v_mode_changed := avs_mem_write or avs_csr_read or avs_csr_write;
elsif v_mem_write then
v_mode_changed := avs_mem_read or avs_csr_read or avs_csr_write;
else
v_mode_changed := '0';
end if;
v_wait_for_flash_busy := not s1_flash_comp_busy and v_cmd_running and not avs_csr_read;--'1' WHEN not s1_flash_comp_busy and v_cmd_running ELSE '0'; -- Durchs synchronisieren ist die flash_comp nicht sofort beim Arbeiten
--------------- FSM --------------
CASE fsm_cur is
------------ IDLE
-- Only in the IDLE state are commandos valid
-- Else: Waitrequest until we finished the operation
WHEN IDLE =>
if s1_flash_comp_rdy then
v_csr_addr := avs_csr_address; -- We ack write commands immediately
avs_csr_readdata <= s1_avs_csr(to_integer(UNSIGNED(v_csr_addr)));
v_wr_requ := avs_mem_write;
s1_clear_rdfifo <= '0';
s1_rdfifo_read <= '0';
s1_rdfifo_read_avm <= '0';
v_mem_access := '0';
v_read_csr_ack := '0';
v_cmd_running := '0';
v_csr_read := '0';
v_csr_write := '0';
v_mem_read := '0';
v_mem_write := '0';
s1_wrfifo_write <= '0';
v_csr_write_ack := '0';
-- Mem Read
IF avs_mem_read then
fsm_cur := SPI_PREP_CMD;
v_mem_access := '1';
s1_rdfifo_read_avm <= '1';
v_cmd_running := '1';
v_mem_read := '1';
-- Mem Write
elsif avs_mem_write then
v_mem_write := '1';
if CHECK_STATUS_REG_BEFORE_WRITE then
if not v_status_reg_idle then -- Zuerst Status Pollen
a_csr <= (RDSR_BIT => '1', others => '0');
s1_spi_cmd <= (RDSR_BIT => '1', others => '0');
v_cmd_running := '1';
v_csr_write := '1';
fsm_cur := EXEC_CMD;
else
if PERM_WR_ENA then
if v_set_write_enable then
s1_spi_cmd <= (WER_BIT => '1', others => '0');
s1_spi_write <= '1';
fsm_cur := MEM_WRITE;
v_cmd_running := '1';
else
fsm_cur := SPI_PREP_CMD;
v_mem_access := '1';
v_cmd_running := '1';
s1_wrfifo_write <= '1';
end if;
else -- no PERM_WR_ENA
fsm_cur := SPI_PREP_CMD;
v_mem_access := '1';
v_cmd_running := '1';
v_mem_write := '1';
s1_wrfifo_write <= '1';
end if;
end if;
else
if PERM_WR_ENA then
if v_set_write_enable then
s1_spi_cmd <= (WER_BIT => '1', others => '0');
s1_spi_write <= '1';
fsm_cur := MEM_WRITE;
v_cmd_running := '1';
else
fsm_cur := SPI_PREP_CMD;
v_mem_access := '1';
v_cmd_running := '1';
v_mem_write := '1';
s1_wrfifo_write <= '1';
end if;
else -- kein PERM_WR_ENA
fsm_cur := SPI_PREP_CMD;
v_mem_access := '1';
v_cmd_running := '1';
v_mem_write := '1';
s1_wrfifo_write <= '1';
end if;
end if;
-- CSR read
elsif avs_csr_read then
fsm_cur := READ_CSR;
v_cmd_running := '1';
v_csr_read := '1';
-- CSR write
elsif avs_csr_write then
v_cmd_running := '1';
if PERM_WR_ENA then
if v_set_write_enable and (avs_csr_writedata(WRSR_BIT) or avs_csr_writedata(WRFR_BIT) or avs_csr_writedata(CER_BIT) or avs_csr_writedata(SER_BIT) or avs_csr_writedata(BER32K_BIT) or avs_csr_writedata(BER64K_BIT)) then
s1_spi_cmd <= (WER_BIT => '1', others => '0');
s1_spi_write <= '1';
fsm_cur := MEM_WRITE;
else
fsm_cur := WRITE_CSR;
v_csr_write := '1';
end if;
else
fsm_cur := WRITE_CSR;
v_csr_write := '1';
end if;
-- We do nothing
else
v_set_write_enable := '1';
fsm_cur := IDLE;
end if;
-- End check if command pending --
--v_conv_flash_addr(avs_mem_address'HIGH downto 0) := avs_mem_address; -- Nios kann QUAD Alignt sein, also z.B. Adresse 1 wäre avs_mem => (others=>'0') mit byte_ena b"0010"
-- Check byteenable bits
for I in AVALON_BUS_DATA_BYTES-1 downto 0 loop
if avs_mem_byteenable(I) then
--v_conv_flash_addr := STD_LOGIC_VECTOR(TO_UNSIGNED(TO_INTEGER(UNSIGNED(avs_mem_address)) + I,v_conv_flash_addr'HIGH+1));
v_conv_flash_addr := STD_LOGIC_VECTOR(TO_UNSIGNED(TO_INTEGER(UNSIGNED(avs_mem_address))*c_ADDR_MULTIPLIER-I,v_conv_flash_addr'HIGH+1));
end if;
end loop;
end if;
----------- MEM READ
-- Command is already sent to flash_comp_cmd_V*
-- Signals are routed to the sync components and from there to the flash_comp_cmd_v*
WHEN MEM_READ =>
IF avs_mem_read THEN -- We read as long as the master is asserting read
s1_spi_read <= '1';
ELSE
s1_rdfifo_read_avm <= '0';
fsm_cur := WAIT_FINISH;
END IF;
s1_spi_addr <= v_conv_flash_addr;
--------------- MEM_WRITE
WHEN MEM_WRITE =>
v_wr_requ := '0';
s1_spi_addr <= v_conv_flash_addr;
s1_spi_write <= '1';
IF not v_wait_for_flash_busy THEN
fsm_cur := WAIT_FINISH;
s1_spi_write <= '0';
END IF;
--------------- WAIT_FINISH
WHEN WAIT_FINISH =>
if s1_rd_ready then
s1_spi_read <= '0';
end if;
s1_clear_rdfifo <= '1';
if RESET_CMD_AFTER_EXEC = TRUE then -- Is eavluated at pre synthesis
a_csr <= c_DEF_CSR;
s1_spi_cmd <= c_DEF_CSR(s1_spi_cmd'HIGH downto 0);
end if;
IF s1_rd_ready and s1_wrfifo_empty and not s1_flash_comp_busy THEN -- All data was sent/read and the flash_comp_cmd_V* component is IDLE
if CHECK_STATUS_REG_BEFORE_WRITE then
if not v_status_reg_idle and v_mem_write then
v_status_reg_idle := not s1_avs_csr(1)(24);
fsm_cur := IDLE;
if PERM_WR_ENA then
v_set_write_enable := '1';
end if;
else
v_cmd_running := '0';
fsm_cur := IDLE; -- We go to IDLE in each path
if PERM_WR_ENA then
if v_set_write_enable then -- Write enable was already set
v_set_write_enable := '0';
else
v_status_reg_idle := '0';
end if;
end if;
end if;
-------------------------------
elsif PERM_WR_ENA then
v_set_write_enable := not v_set_write_enable;
fsm_cur := IDLE;
v_cmd_running := '0';
else
fsm_cur := IDLE;
v_cmd_running := '0';
end if;
END IF;
------------- CSR READ
WHEN READ_CSR =>
v_read_csr_ack := '1';
fsm_cur := IDLE;
--v_cmd_running := '0';
----------- CSR Write
WHEN WRITE_CSR => -- Kommen hier nur von IDLE aus her, somit sparen wir uns die state Kontrollen
v_csr_write_ack := '1';
IF UNSIGNED(v_csr_addr) = 0 THEN
a_csr <= avs_csr_writedata;
fsm_cur := SPI_PREP_CMD;
else
a_addr <= avs_csr_writedata(23 downto 0);
fsm_cur := IDLE;
v_cmd_running := '0';
END IF;
---------------------
-- Hier wird der STATUS der CSR in den Kommando code fuer das SPI Interface umgewandelt
WHEN SPI_PREP_CMD =>
--v_csr_write_ack := '0';
s1_wrfifo_write <= '0';
s1_spi_cmd <= (others=>'0');
-- Kommando auswerten
-- Nach Synthese wird nur der Teil verwendet der ausgewaehlt wurde
if v_wr_requ then
fsm_cur := MEM_WRITE;
elsif avs_mem_read then
fsm_cur := MEM_READ;
else
fsm_cur := EXEC_CMD;
end if;
IF DEVICE_FAMILY = "IS25LQ" THEN
CASE a_csr is
-- FAST Mode
WHEN c_EXT_MODE =>
IF v_wr_requ THEN
s1_spi_cmd(PP_BIT) <= '1';
ELSE
s1_spi_cmd(FR_BIT) <= '1';
END IF;
-- FAST_QUAD_MODE
WHEN c_FAST_QUAD_MODE =>
IF v_wr_requ THEN
s1_spi_cmd (PPQ_BIT) <= '1';
else
s1_spi_cmd(FRQIO_BIT) <= '1';
END IF;
--- Others
-- Ein Kommando soll ausgefuehrt werden
WHEN others =>
s1_coe_cmd_data <= a_addr;
s1_spi_cmd <= STD_LOGIC_VECTOR(TO_UNSIGNED((to_integer(UNSIGNED(a_csr))),s1_spi_cmd'HIGH+1));
end CASE;
ELSE -- Nicht unterstuetzer FLASH
assert FALSE report "Flash Type wird nicht unterstuetzt" severity ERROR;
END IF;
---- EXEC_CMD
when EXEC_CMD =>
-- Validiere welches Kommando
if a_csr(RDSR_BIT) or a_csr(RDFR_BIT) then
if s1_rd_ready then
s1_spi_read <= '1';
s1_rdfifo_read <= '1';
else
s1_rdfifo_read <= '0';
end if;
else
s1_spi_write <= '1';
s1_rdfifo_read <= '0';
end if;
IF not v_wait_for_flash_busy and s1_spi_write THEN
fsm_cur := WAIT_FINISH;
s1_spi_write <= '0';
ELSIF not v_wait_for_flash_busy and s1_rdfifo_read_req then
s1_spi_read <= '0';
fsm_cur := WAIT_FINISH;
s1_avs_csr(1)(31 downto 24) <= s1_rdfifo_data;
s1_clear_rdfifo <= '1';
END IF;
----- WHEN OTHERS
WHEN others =>
fsm_cur := IDLE;
v_cmd_running := '0';
end CASE;
END IF;
end process MAIN_FSM;
------------------ ENDE MAIN FSM --------------------
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-05T14:05:34.330",
"Id": "452502",
"Score": "1",
"body": "To prevent opinionated answers: what do you want to achieve? I mean, I think this is very hard to read as it is so large. So I would split it up over some hierarchy, with fsms in multiple processes. But that's a personal preference."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:36:44.903",
"Id": "230492",
"Score": "2",
"Tags": [
"vhdl"
],
"Title": "SPI controller in VHDL"
}
|
230492
|
<p>I work with electronics test equipment. I like to be able to automate tests using their remote control interfaces. I have built a pattern, a few base classes, that I can apply to all devices that follow the <a href="https://en.wikipedia.org/wiki/Standard_Commands_for_Programmable_Instruments" rel="nofollow noreferrer">SCPI protocol</a>. I would like to avoid half-assing the implementation like every time before. I wan't to bite the bullet and do this the right way once and for all. I do not use LabView so I can't just download their drivers.</p>
<p>I pounded out something that got me close, but it's not all the way there. If it looks like mad ramblings just ignore it. Any pointers on the right design pattern will really help!</p>
<p>I have designed it the way you see it because I want the usability to be nice and clean like:</p>
<pre><code>double instantaneousCurrent = instrument.Measurement.Current.Instantaneous.Get();
</code></pre>
<p>or</p>
<pre><code>double powerSetPoint = double.Parse(Console.ReadLine());
instrument.Load.ConstantPower.Set(powerSetPoint);
</code></pre>
<p>Each node in the would ideally put your statement another "." deeper down the instrument object.</p>
<p><em>Code:</em></p>
<p>SCPI Baseclass, Subsystem BaseClass, and SystemProperty BaseClass:</p>
<pre><code>/// <summary>
/// Provides serial object creation services and ensures the correct device is on the other end.
/// </summary>
public abstract class ScpiDeviceBaseClass : IDisposable
{
private List<int> PossibleBaudRates = new List<int>() { 115200, 57600, 38400, 19200, 9600, 4800};
protected SerialPort serialPort;
protected string DeviceName;
#region Constructors
/// <summary>
/// Takes the device name and provided serial port and ensures the port is open and the device on the other end responds with the correct identifier.
/// </summary>
/// <param name="deviceName">A string that can be used to verify the connected device is the expected one by checking if <paramref name="deviceName"/> is contained in the response to an *IDN? request.</param>
/// <param name="port">A preconfigured <see cref="SerialPort"/>.</param>
public ScpiDeviceBaseClass(string deviceName, SerialPort port)
{
this.DeviceName = deviceName;
serialPort = port;
if (!serialPort.IsOpen)
{
try
{
serialPort.Open();
}
catch (UnauthorizedAccessException)
{
throw new Exception($"Failed to open {serialPort.PortName} because it was already open elsewhere.");
}
catch (Exception ex)
{
throw new Exception($"Failed to open {serialPort.PortName}. Reason: \r\n{ex.Message}");
}
}
serialPort.ReadTimeout = 2000;
CheckIdn();
}
/// <summary>
/// Takes the device name and provided serial port name (COM Port), creates a <see cref="SerialPort"/> using all possible baud rates until the device responds with a correct identifier.
/// </summary>
/// <param name="deviceName">A string that can be used to verify the connected device is the expected one by checking if <paramref name="deviceName"/> is contained in the response to an *IDN? request.</param>
/// <param name="portName">A string with the name of the COM port to be used i.e. "COM12".</param>
public ScpiDeviceBaseClass(string deviceName, string portName)
{
this.DeviceName = deviceName;
// Make sure the port name given looks valid.
if (portName == null || portName == "" || !portName.StartsWith("COM"))
{
if (portName == null)
{
portName = "null";
}
else if (portName == "")
{
portName = "blank";
}
throw new Exception($"Unable to connect to {DeviceName}. Bad port provided. Port provided was {portName}.");
}
ScanSelectedPortWithAllBaudRates(portName);
}
/// <summary>
/// Takes the device name and checks all available COM ports with all possible baud rates until the device responds with the correct identifier.
/// </summary>
/// <param name="deviceName">A string that can be used to verify the connected device is the expected one by checking if <paramref name="deviceName"/> is contained in the response to an *IDN? request.</param>
/// <param name="baudRate">An optional parameter that can be used to shorten the list of possible combinations to check.</param>
public ScpiDeviceBaseClass(string deviceName, int baudRate = -1)
{
this.DeviceName = deviceName;
if (baudRate != -1)
{
ScanPortsWithSelectedBaudRate(baudRate);
}
else
{
ScanAllPortsWithAllBaudRates();
}
}
/// <summary>
/// Ensures the device can respond with the current serial port configuration and that the response contains the expected response.
/// </summary>
private void CheckIdn()
{
int tries = 0;
// Try to read the identification of the device connected and ensure it is the device expected.
try
{
while (true)
{
try
{
ReadUntilInBufferEmpty();
serialPort.WriteLine("*IDN?");
string idn = serialPort.ReadLine();
if (!idn.Contains(DeviceName))
{
throw new Exception($"Identification request returned \"{idn}\". Are you connected to the correct com port?");
}
return;
}
catch (Exception)
{
if (tries > 3)
{
throw;
}
}
tries++;
}
}
catch (Exception ex)
{
if (ex is TimeoutException)
{
throw new Exception($"Connection to {DeviceName} failed due to read timeout.");
}
else if (ex is InvalidOperationException)
{
throw new Exception($"Error connecting to {DeviceName}. Error: " + ex.Message);
}
else
{
throw;
}
}
}
/// <summary>
/// Loops through all available COM ports and tries to connect using the specified baud rate.
/// </summary>
/// <param name="baudRate">The baud rate to check each COM port with.</param>
private void ScanPortsWithSelectedBaudRate(int baudRate)
{
string[] ports = SerialPort.GetPortNames();
if (ports.Count() == 0)
{
throw new Exception($"No com ports found to connect to {DeviceName}.");
}
// Try all ports using the specified baud rate.
for (int i = 0; i < ports.Count(); i++)
{
try
{
serialPort = new SerialPort(ports[0], baudRate);
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
serialPort.Open();
serialPort.ReadTimeout = 2000;
CheckIdn();
return ;
}
catch (Exception)
{
if (i == ports.Count() - 1)
{
throw;
}
}
}
}
/// <summary>
/// Loops through all available COM ports and tries to connect with all possible baud rates.
/// </summary>
private void ScanAllPortsWithAllBaudRates()
{
string[] ports = SerialPort.GetPortNames();
if (ports.Count() == 0)
{
throw new Exception($"No com ports found to connect to {DeviceName}.");
}
// Try all ports with any baud rate.
for (int i = 0; i < ports.Count(); i++)
{
try
{
// Try all possible baud rates on this port.
for (int j = 0; j < PossibleBaudRates.Count; j++)
{
try
{
int baud = PossibleBaudRates[j];
serialPort = new SerialPort(ports[0], baud);
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
serialPort.Open();
serialPort.ReadTimeout = 2000;
CheckIdn();
break;
}
catch (Exception)
{
serialPort.Dispose();
serialPort = null;
}
}
if (serialPort == null)
{
throw new Exception("Failed to connect to device.");
}
break;
}
catch (Exception)
{
if (i == ports.Count() - 1)
{
throw;
}
}
}
}
/// <summary>
/// Loops through all possible baud rates and tries to connect on the specified COM port.
/// </summary>
/// <param name="portName"></param>
private void ScanSelectedPortWithAllBaudRates(string portName)
{
// Try all possible baud rates on this port.
for (int j = 0; j < PossibleBaudRates.Count; j++)
{
try
{
int baud = PossibleBaudRates[j];
serialPort = new SerialPort(portName, baud);
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
serialPort.Open();
serialPort.ReadTimeout = 2000;
CheckIdn();
break;
}
catch (Exception)
{
serialPort.Dispose();
serialPort = null;
}
}
if (serialPort == null)
{
throw new Exception("Failed to connect to device.");
}
}
#endregion Constructors
/// <summary>
/// Read the comport until we are sure it is empty.
/// By reading the com port until we get a read timeout three times in a row we can feel confident there is no more data left to be read.
/// </summary>
private void ReadUntilInBufferEmpty()
{
int previousReadTimeout = serialPort.ReadTimeout;
serialPort.ReadTimeout = 100;
int timeoutExceptions = 0;
while (timeoutExceptions < 3)
{
try
{
serialPort.ReadLine();
// If the read does not fail we reset the counter.
timeoutExceptions = 0;
}
catch (TimeoutException)
{
// If the exception thrown is a timeout exception we increment the exception counter and then read again if we are not over the try limit of 3.
timeoutExceptions++;
}
catch (Exception)
{
serialPort.ReadTimeout = previousReadTimeout;
// If the exception thrown is not a read timeout exception we want to throw it up.
throw;
}
}
serialPort.ReadTimeout = previousReadTimeout;
}
public void Dispose()
{
if (this.serialPort != null)
{
this.serialPort.Dispose();
this.serialPort = null;
}
}
/// <summary>
/// Used to represent all nodes in an SCPI command tree that are not leafs.
/// This makes the case where a non-leaf node is a request clunky. How can I fix this?
/// </summary>
public abstract class DeviceSubsystem
{
// Used to quickly identify a root node.
protected bool IsRoot
{
get
{
if (this.Parent == null)
{
return true;
}
else
{
return false;
}
}
}
// The parent of this node.
protected DeviceSubsystem Parent;
// This nodes children.
protected List<DeviceSubsystem> Children;
// This node's name.
protected string NodeName;
// The serial port to use.
protected SerialPort ComPort;
public DeviceSubsystem(string nodeName, DeviceSubsystem parent, SerialPort comPort)
{
NodeName = nodeName;
Parent = parent;
ComPort = comPort;
Children = new List<DeviceSubsystem>();
}
/// <summary>
/// Used to represent all nodes in the SCPI command tree that are leafs.
/// This leaf can be written to and read from.
/// </summary>
/// <typeparam name="PropertyType">The <see cref="Type"/> of this leaf.</typeparam>
public abstract class SubSystemProperty<PropertyType> : SubSystemPropertyBase<PropertyType>, SubSystemReader<PropertyType>, SubSystemWritter<PropertyType>
{
/// <summary>
/// Creates a leaf node that can read and write.
/// </summary>
/// <param name="name">The name of the node. This is used to create commands so it must match the exact text the device expects at this node.</param>
/// <param name="parent">This nodes <see cref="DeviceSubsystem"/> parent.</param>
/// <param name="isRootResquest"><para>Indicates that this is not really a leaf, but rather the request implementation of a <see cref="DeviceSubsystem"/>. Some non-leaf nodes are also requests. The current implementation does not handle this case gracefully. This is a hack.</para></param>
public SubSystemProperty(string name, DeviceSubsystem parent, bool isRootResquest = false) : base(name, parent, isRootResquest)
{
}
public PropertyType Get()
{
string response = GetString(Name);
return ConvertToType(response);
}
public void Set(PropertyType value)
{
string valueString = value.ToString();
// If the value is a bool we need to represent it differently.
if (value.GetType() == typeof(bool))
{
bool boolValue = bool.Parse(valueString);
if (boolValue == true)
{
valueString = "1";
}
else
{
valueString = "0";
}
}
SetString(this.Name, valueString);
}
}
/// <summary>
/// Used to represent all nodes in the SCPI command tree that are leafs.
/// This leaf can only be read from.
/// </summary>
/// <typeparam name="PropertyType">The <see cref="Type"/> of this leaf.</typeparam>
public abstract class SubsytemPropertyReadonly<PropertyType> : SubSystemPropertyBase<PropertyType>, SubSystemReader<PropertyType>
{
/// <summary>
/// Creates a leaf node that can read.
/// </summary>
/// <param name="name">The name of the node. This is used to create commands so it must match the exact text the device expects at this node.</param>
/// <param name="parent">This nodes <see cref="DeviceSubsystem"/> parent.</param>
/// <param name="isRootResquest"><para>Indicates that this is not really a leaf, but rather the request implementation of a <see cref="DeviceSubsystem"/>. Some non-leaf nodes are also requests. The current implementation does not handle this case gracefully. This is a hack.</para></param>
public SubsytemPropertyReadonly(string name, DeviceSubsystem parent, bool isRootResquest = false) : base(name, parent, isRootResquest)
{
}
public PropertyType Get()
{
string response = GetString(Name);
return ConvertToType(response);
}
}
/// <summary>
/// Used to represent all nodes in the SCPI command tree that are leafs.
/// This leaf can only be written to.
/// </summary>
/// <typeparam name="PropertyType">The <see cref="Type"/> of this leaf.</typeparam>
public abstract class SubSystemPropertyWriteOnly<PropertyType> : SubSystemPropertyBase<PropertyType>, SubSystemWritter<PropertyType>
{
/// <summary>
/// Creates a leaf node that can write.
/// </summary>
/// <param name="name">The name of the node.</param>
/// <param name="parent">This nodes <see cref="DeviceSubsystem"/> parent.</param>
/// <param name="isRootResquest"><para>Indicates that this is not really a leaf, but rather the request implementation of a <see cref="DeviceSubsystem"/>. Some non-leaf nodes are also requests. The current implementation does not handle this case gracefully. This is a hack.</para></param>
public SubSystemPropertyWriteOnly(string name, DeviceSubsystem parent, bool isRootResquest = false) : base(name, parent, isRootResquest)
{
}
public void Set(PropertyType value)
{
string valueString = value.ToString();
if (value.GetType() == typeof(bool))
{
bool boolValue = bool.Parse(valueString);
if (boolValue == true)
{
valueString = "1";
}
else
{
valueString = "0";
}
}
SetString(this.Name, valueString);
}
}
/// <summary>
/// Provides the ability to write to leafs.
/// </summary>
/// <typeparam name="PropertyType">The <see cref="Type"/> of this leaf.</typeparam>
public interface SubSystemWritter<PropertyType>
{
void Set(PropertyType value);
}
/// <summary>
/// Provides the ability to read from leafs.
/// </summary>
/// <typeparam name="PropertyType">The <see cref="Type"/> of this leaf.</typeparam>
public interface SubSystemReader<PropertyType>
{
PropertyType Get();
}
/// <summary>
/// Provides the basic leaf functionality.
/// </summary>
/// <typeparam name="PropertyType">The <see cref="Type"/> of this leaf.</typeparam>
public abstract class SubSystemPropertyBase<PropertyType>
{
protected string Name;
protected DeviceSubsystem Parent;
/// <summary>
/// Creates the base leaf node. It can neither read nor write.
/// </summary>
/// <param name="name">The name of the node. This is used to create commands so it must match the exact text the device expects at this node.</param>
/// <param name="parent">This nodes <see cref="DeviceSubsystem"/> parent.</param>
/// <param name="isRootResquest"><para>Indicates that this is not really a leaf, but rather the request implementation of a <see cref="DeviceSubsystem"/>. Some non-leaf nodes are also requests. The current implementation does not handle this case gracefully. This is a hack.</para></param>
public SubSystemPropertyBase(string name, DeviceSubsystem parent, bool isRootResquest = false)
{
Parent = parent;
if (!isRootResquest)
{
// If isRootRequest is false, we just use the provided name.
Name = name;
}
else
{
// If isRootRequest is true, we use an empty name. This fixes the case where a non-leaf node can make requests. This is a hack.
Name = "";
}
}
#region ResponseConversions
protected PropertyType ConvertToType(string response)
{
switch (Type.GetTypeCode(typeof(PropertyType)))
{
case TypeCode.Boolean:
{
return (PropertyType)Convert.ChangeType(ToBool(response), typeof(PropertyType));
}
case TypeCode.Int16:
{
return (PropertyType)Convert.ChangeType(ToInt(response), typeof(PropertyType));
}
case TypeCode.UInt16:
{
return (PropertyType)Convert.ChangeType(ToUint(response), typeof(PropertyType));
}
case TypeCode.Int32:
{
return (PropertyType)Convert.ChangeType(ToInt(response), typeof(PropertyType));
}
case TypeCode.UInt32:
{
return (PropertyType)Convert.ChangeType(ToUint(response), typeof(PropertyType));
}
case TypeCode.Double:
{
return (PropertyType)Convert.ChangeType(ToDouble(response), typeof(PropertyType));
}
case TypeCode.String:
{
return (PropertyType)Convert.ChangeType(response, typeof(PropertyType));
}
default:
throw new Exception($"Invalid type of '{typeof(PropertyType).Name}' specified in SubsytemProperty.");
}
}
private bool ToBool(string response)
{
if (response == null || response == "")
{
MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
throw new ArgumentException($"Null or empty value passed to {method.Name}.");
}
if (response == "0")
{
return false;
}
else if (response == "1")
{
return true;
}
else
{
MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
throw new ArgumentException($"Invalid value of '{response}' passed to {method.Name}.");
}
}
private double ToDouble(string response)
{
if (response == null || response == "")
{
MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
throw new ArgumentException($"Null or empty value passed to {method.Name}.");
}
if (double.TryParse(response, out double value))
{
return value;
}
else
{
MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
throw new ArgumentException($"Invalid value of '{response}' passed to {method.Name}.");
}
}
private int ToInt(string response)
{
if (response == null || response == "")
{
MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
throw new ArgumentException($"Null or empty value passed to {method.Name}.");
}
if (int.TryParse(response, out int value))
{
return value;
}
else
{
MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
throw new ArgumentException($"Invalid value of '{response}' passed to {method.Name}.");
}
}
private uint ToUint(string response)
{
if (response == null || response == "")
{
MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
throw new ArgumentException($"Null or empty value passed to {method.Name}.");
}
if (uint.TryParse(response, out uint value))
{
return value;
}
else
{
MethodBase method = System.Reflection.MethodBase.GetCurrentMethod();
throw new ArgumentException($"Invalid value of '{response}' passed to {method.Name}.");
}
}
#endregion ResponseConversions
#region Messaging
protected string GetString(string command)
{
string fullCommand = CreateFullCommand(command);
Write(fullCommand);
string response = Read();
return response;
}
protected void SetString(string command, string value)
{
string fullCommand = CreateFullCommand(command, value);
Write(fullCommand);
}
private string ConvertBoolToValue(bool boolValue)
{
if (boolValue == true)
{
return "1";
}
else
{
return "0";
}
}
private string CreateFullCommand(string command, string value = null)
{
StringBuilder sb = new StringBuilder();
// Get the path from this subsystem to the root. This is used to create the full command string.
List<DeviceSubsystem> pathToRoot = new List<DeviceSubsystem>();
DeviceSubsystem currentSubSystem = this.Parent;
// starting from the subsystem we are in check to see if we are at the root, if no look at our parent.
while (true)
{
pathToRoot.Add(currentSubSystem);
if (currentSubSystem.IsRoot)
{
break;
}
else
{
currentSubSystem = currentSubSystem.Parent;
}
}
// Reverse the list so we go from root to the node of interest.
pathToRoot.Reverse();
foreach (DeviceSubsystem subsystem in pathToRoot)
{
sb.Append($":{subsystem.NodeName}");
}
// Add our command to the end of our request.
if (value == null)
{
// if the value param is null this is a request for data
sb.Append($":{command}?");
}
else
{
// if the value param is not null we are sending information to be set
sb.Append($":{command} {value}");
}
return sb.ToString();
}
private void Write(string message)
{
int tries = 0;
while (true)
{
try
{
this.Parent.ComPort.WriteLine(message);
break;
}
catch (Exception)
{
tries++;
if (tries > 3)
{
throw;
}
}
}
}
private string Read()
{
int tries = 0;
while (true)
{
try
{
string response = this.Parent.ComPort.ReadLine();
return response;
}
catch (Exception)
{
tries++;
if (tries > 3)
{
throw;
}
}
}
}
#endregion Messaging
}
}
}
</code></pre>
<p>Implementation:</p>
<pre><code>public class TestInstrument : ScpiDeviceBaseClass
{
#region Constructors
public MeasurmentsSubSystem Measurement;
public LoadSubSystem Load;
public TestInstrument(SerialPort port) : base("TestInstrumentIdentifier", port)
{
ConstructSystemRootNodes();
}
public TestInstrument(string portName) : base("TestInstrumentIdentifier", portName)
{
ConstructSystemRootNodes();
}
public TestInstrument() : base("TestInstrumentIdentifier", 57600)
{
ConstructSystemRootNodes();
}
/// <summary>
/// Handles the construction of all root subsystem nodes.
/// </summary>
private void ConstructSystemRootNodes()
{
Measurement = new MeasurmentsSubSystem("Measure", null, this.serialPort);
Load = new LoadSubSystem("Load", null, this.serialPort);
}
#endregion Constructors
/// <summary>
/// Represents the measurements subsystem.
/// </summary>
public class MeasurmentsSubSystem : DeviceSubsystem
{
#region Nodes
/// <summary>
/// The sub-subsystem of measurements, the current measurement subsystem.
/// </summary>
public CurrentMeasurements Current;
#endregion Nodes
#region Constructors
/// <summary>
/// Constructs this subsystem.
/// </summary>
/// <param name="nodeName">The node name is used to construct commands sent to the device.</param>
/// <param name="parent">This subsystem's parent subsystem. Null if this is a root node.</param>
/// <param name="serialPort">The serial port used to communicate with the device.</param>
public MeasurmentsSubSystem(string nodeName, DeviceSubsystem parent, SerialPort serialPort) : base(nodeName, parent, serialPort)
{
ConstructChildren();
ConstructLeafs();
}
/// <summary>
/// Used to construct all non-leaf nodes below this subsystem.
/// </summary>
protected override void ConstructChildren()
{
this.Children.Add(Current = new CurrentMeasurements("Current", this, this.serialPort));
}
/// <summary>
/// Used to construct all leaf nodes directly below this subsystem.
/// </summary>
protected override void ConstructLeafs()
{
}
#endregion Constructors
#region DeviceSubsystem Node Definitions
/// <summary>
/// Represents the subsystem responsible for current measurement.
/// </summary>
public class CurrentMeasurements : DeviceSubsystem
{
#region Nodes
/// <summary>
/// The Amplitude measurement subsystem.
/// </summary>
public AmplitudeMeasurements Amplitude;
/// <summary>
/// Used to access the instantaneous current measurement.
/// </summary>
public Instantaneous instantaneous;
#endregion Nodes
#region Constructors
/// <summary>
/// Constructs this subsystem.
/// </summary>
/// <param name="nodeName">The node name is used to construct commands sent to the device.</param>
/// <param name="parent">This subsystem's parent subsystem. Null if this is a root node.</param>
/// <param name="serialPort">The serial port used to communicate with the device.</param>
public CurrentMeasurements(string nodeName, DeviceSubsystem parent, SerialPort serialPort) : base(nodeName, parent, serialPort)
{
ConstructChildren();
ConstructLeafs();
}
/// <summary>
/// Used to construct all non-leaf nodes below this subsystem.
/// </summary>
protected override void ConstructChildren()
{
this.Children.Add(Amplitude = new AmplitudeMeasurements("Amplitude", this, this.serialPort));
}
/// <summary>
/// Used to construct all leaf nodes directly below this subsystem.
/// </summary>
protected override void ConstructLeafs()
{
instantaneous = new Instantaneous(this);
}
#endregion Constructors
#region DeviceSubsystem Node Definitions
public class AmplitudeMeasurements : DeviceSubsystem
{
#region Nodes
public Hold hold;
public Max max;
#endregion Nodes
#region Constructors
public AmplitudeMeasurements(string nodeName, DeviceSubsystem parent, SerialPort comPort) : base(nodeName, parent, comPort)
{
ConstructChildren();
ConstructLeafs();
}
/// <summary>
/// Used to construct all non-leaf nodes below this subsystem.
/// </summary>
protected override void ConstructChildren()
{
}
/// <summary>
/// Used to construct all leaf nodes directly below this subsystem.
/// </summary>
protected override void ConstructLeafs()
{
hold = new Hold(this);
max = new Max(this);
}
#endregion Constructors
#region SubSystemProperty Node Definitions
public class Hold : SubSystemProperty<bool>
{
public Hold(DeviceSubsystem parent) : base(typeof(Hold).Name, parent) { }
}
public class Max : SubSystemProperty<double>
{
public Max(DeviceSubsystem parent) : base(typeof(Max).Name, parent) { }
}
#endregion SubSystemProperty Node Definitions
}
#endregion DeviceSubsystem Node Definitions
#region SubsytemProperty Node Definitions
public class Instantaneous : SubsytemPropertyReadonly<double>
{
public Instantaneous(DeviceSubsystem parent) : base(typeof(Instantaneous).Name, parent, true) { }
}
#endregion SubsytemProperty Node Definitions
}
#endregion DeviceSubsystem Node Definitions
}
public class LoadSubSystem : DeviceSubsystem
{
#region Nodes
public Status status;
#endregion Nodes
#region Constructors
public LoadSubSystem(string nodeName, DeviceSubsystem parent, SerialPort comPort) : base(nodeName, parent, comPort)
{
ConstructChildren();
ConstructLeafs();
}
/// <summary>
/// Used to construct all non-leaf nodes below this subsystem.
/// </summary>
protected override void ConstructChildren()
{
}
/// <summary>
/// Used to construct all leaf nodes directly below this subsystem.
/// </summary>
protected override void ConstructLeafs()
{
status = new Status(this);
}
#endregion Constructors
#region SubSystemProperty Node Definitions
public class Status : SubSystemProperty<bool>
{
public Status(DeviceSubsystem parent) : base(typeof(Status).Name, parent) { }
}
#endregion SubSystemProperty Node Definitions
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T14:12:41.877",
"Id": "230495",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"error-handling",
"io"
],
"Title": "Implementation of SCPI for control of test instruments"
}
|
230495
|
<p>I'm writing a program to calculate the longest collatz sequence for positive integers below some N. I have optimized it as far as I can - is there anything more I could do to optimize it? Any constructive criticism is welcome :) </p>
<p>A few interesting notes: It is easy to prove (by contradiction or otherwise) that the number that produces the longest chain exists in the second half of the numbers from 1-N (that is, it must be greater than N/2). If we try to run the loop from N/2 to N, the running time becomes substantially slower. Interesting... Also, the lower while loop is an interesting idea, but provides no tangible performance benefits (or losses, for that matter - which is why I kept it. It's an interesting idea).</p>
<p>Thank you!</p>
<pre><code>#include <iostream>
#include <chrono>
using namespace std::chrono;
const int N = 1000000;
long long iCpy;
short ct;
short maxLength = 0;
short vals[N] = {0};
int main() {
// Time the program:
auto startTime = steady_clock::now();
int i, maxIndex = 0;
// calculate collatz lengths for all indices.
// keep track of max value:
for (i = 2; i < N; i++) {
iCpy = i;
ct = 0;
while (iCpy != 1) {
if (iCpy < N && vals[iCpy]) {
ct += vals[iCpy];
break;
}
if (iCpy & 1) {
iCpy *= 3;
iCpy++;
} else {
iCpy >>= 1; // Equivalent to iCpy /= 2
}
ct++;
}
iCpy = i;
vals[iCpy] = ct;
while (iCpy < N/2) {
iCpy <<= 1; // Equivalent to iCpy *= 2
vals[iCpy] = ++ct;
}
if (ct > maxLength) {
maxLength = ct;
maxIndex = iCpy;
}
}
// output the max index and length:
std::cout << "Max number: " << maxIndex << ", with length " << maxLength << std::endl;
auto elapsed = duration_cast<milliseconds>(steady_clock::now() - startTime);
std::cout << "Program execution took " << elapsed.count() << "ms\n";
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T05:28:35.597",
"Id": "449167",
"Score": "0",
"body": "using unsigned types should speed it up a bit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T08:27:53.830",
"Id": "449742",
"Score": "0",
"body": "It's interesting that you report that the lower loop has no effect on your timings. I measured about 20× difference with it (more visible when I set N to 100'000'000, as the result was too small at just 1'000'000)."
}
] |
[
{
"body": "<p>Here are some suggestions:</p>\n\n<ul>\n<li><p>Don't use global variables.</p></li>\n<li><p>Instead of using a single big function, break it down to logical parts.</p></li>\n<li><p><code>const int N = 1000000;</code> should be <code>constexpr</code> instead of <code>const</code>.</p></li>\n<li><p>Instead of <code>= {0}</code>, use <code>{}</code>. The latter makes it clear that you are\nvalue initializing all elements.</p></li>\n<li><p><code>i</code> should be declared in the loop.</p></li>\n<li><p>Post-increment operators <code>i++</code> should be changed to pre-increment\n<code>++i</code> in a discarded-value expression.</p></li>\n<li><p><code>iCpy & 1</code> should be <code>iCpy % 2 == 0</code>. <code>iCpy <<= 1; // Equivalent to iCpy *= 2</code> should be <code>iCpy *= 2</code>. Optimization doesn't happen in this way — the compiler knows such things much better.</p></li>\n<li><p>Use <code><< '\\n'</code> instead of <code><< std::endl</code> when you don't need the flushing behavior.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:22:44.323",
"Id": "449213",
"Score": "0",
"body": "The compiler will optimize i++ to ++i in discarded-value expressions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:57:24.873",
"Id": "449217",
"Score": "1",
"body": "@Kyy13, that's true for integers, but with preincrement, then readers don't need to double-check what type `i` is. (i.e. `++i` is *always* right, and `i++` is *sometimes* right, depending on the type of `i`. So let's consistently use the one that's always right.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T13:19:38.447",
"Id": "449221",
"Score": "1",
"body": "@Kyy13 In addition to what Toby Speight said, ++i just means “increment i” whereas i++ means “copy the value, increment, and then give me the original value” (just like std::exchange). In the same way you don’t want to write `int a = static_cast<int>('\\008') * 42LL / 21.0 - true;` in place of `int a = 15;` even though compiler optimizations should compile them the same way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T13:59:12.350",
"Id": "449227",
"Score": "0",
"body": "@TobySpeight I get the same disassembly with i++ and ++i regardless of using floating or integral types when the return value is not needed. Can you explain what you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:02:24.280",
"Id": "449229",
"Score": "1",
"body": "@Kyy13, I'm thinking of class types with overloaded `++` operators. When the operator isn't inlineable, your compiler has much less ability to optimise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:06:01.570",
"Id": "449230",
"Score": "0",
"body": "@L.F. I understand what you mean, but the intention of both i++ and ++i is clear. Some find post increment easier to read according to the Google C++ Style Guide. https://google.github.io/styleguide/cppguide.html#Preincrement_and_Predecrement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:12:16.327",
"Id": "449231",
"Score": "0",
"body": "@TobySpeight Okay, that's true. I just wanted to make it clear to OP, because the answer already mentions compiler optimization."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:58:53.897",
"Id": "230542",
"ParentId": "230501",
"Score": "2"
}
},
{
"body": "<p>The lower loop (which fills all power-of-two multiples of the outer index) is doing unnecessary work when <code>i</code> is even. If we find that <code>vals[i]</code> was already filled in by a previous iteration, then so was <code>vals[2*i]</code> and so on.</p>\n<p>I improved run-time by about 5% simply by adding at the start of the outer loop:</p>\n<pre><code> if (vals[i]) {\n continue;\n }\n</code></pre>\n<hr />\n<p>It's usual to report the lowest starting value of those that give rise to the same length chain. The current code doesn't do that, because of the second loop. To give the same results as seen on OEIS, then we need to change the logic to update <code>maxIndex</code> and <code>maxLength</code> only after computing Collatz(i), and before the <code>*=2</code> loop.</p>\n<hr />\n<p>Finally, we don't want to be measuring printing time as well as computation, so move the setting of <code>elapsed</code> before the printing of max number.</p>\n<hr />\n<h1>Improved version</h1>\n<p>I upped the range to 100 million so that I could get meaningful numbers of milliseconds on my machine. This consistently gives under 1750 ms, compared to slightly over 2000 ms with the original. It also gives the lowest index for a given count, consistent with the results shown on the <a href=\"https://en.wikipedia.org/wiki/Collatz_conjecture#Examples\" rel=\"nofollow noreferrer\">Collatz entry in Wikipedia</a>.</p>\n<p>I've also applied changes suggested in other reviews</p>\n<pre><code>#include <chrono>\n#include <iostream>\n\nconst unsigned int N = 100'000'000;\nunsigned short vals[N] = {};\n\nint main() {\n using namespace std::chrono;\n // Time the program:\n auto const startTime = steady_clock::now();\n\n unsigned int maxIndex = 0;\n unsigned int maxLength = 0;\n\n // calculate Collatz length for each index, and memoize\n for (unsigned int i = 2; i < N; ++i) {\n unsigned long iCpy = i;\n unsigned int ct = 0;\n\n while (iCpy > 1) {\n if (iCpy < N && vals[iCpy]) {\n ct += vals[iCpy];\n break;\n }\n\n iCpy = iCpy % 2\n ? 3 * iCpy + 1\n : iCpy / 2;\n ++ct;\n }\n if (ct > maxLength) {\n maxLength = ct;\n maxIndex = i;\n }\n\n // Pre-fill power-of-two multiples of this result\n for (iCpy = i; iCpy < N && !vals[i]; iCpy *= 2) {\n vals[iCpy] = ct++;\n }\n }\n\n auto elapsed = duration_cast<milliseconds>(steady_clock::now() - startTime);\n\n // output the max index and length:\n std::cout << "Max number: " << maxIndex << ", with length " << maxLength << '\\n';\n std::cout << "Program execution took " << elapsed.count() << "ms\\n";\n return 0;\n}\n</code></pre>\n<p>In case you wonder what happened to the <code>continue</code> mentioned in my first paragraph, it has to move to after the <code>maxLength</code> check, and it seems to optimise better when incorporated into the existing <code>for</code> loop condition, perhaps due to branch prediction.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T08:58:51.680",
"Id": "230739",
"ParentId": "230501",
"Score": "2"
}
},
{
"body": "<p>You are more interested in the performance, and on style there are sufficient mentions.</p>\n\n<p>The Collatz sequence can be reduced:</p>\n\n<pre><code> if (iCpy & 1) {\n iCpy *= 3;\n ++iCpy;\n ++ct;\n }\n iCpy >>= 1;\n ++ct;\n\nwhile (iCpy != 1) {\n if (iCpy & 1) {\n iCpy *= 3;\n ++iCpy;\n ++ct;\n }\n iCpy >>= 1;\n ++ct;\n}\n</code></pre>\n\n<p>As a loop's intermediate step is not cached, instead first using a recursive function and on coming back update the result cache could be faster. Especially when the compiler eliminates the recursion.</p>\n\n<pre><code>int collatz(int n) {\n if (n <= 1) {\n return 0;\n }\n int st = n & 1;\n if (st) {\n n = 3*n + 1;\n }\n n /= 2;\n return 1 + st + collatz(n);\n}\n\nint collatz(int n) {\n if (n <= 1) {\n return 0;\n }\n int res = from_cache(n);\n if (res) {\n return res;\n }\n int n0 = n;\n\n int st = n & 1;\n if (st) {\n n = 3*n + 1;\n }\n n /= 2;\n res = collatz(n);\n res += 1 + st;\n to_cache(n0, res);\n return res;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T10:28:05.953",
"Id": "230744",
"ParentId": "230501",
"Score": "2"
}
},
{
"body": "<p>I reduced the time of the algorithm by ~36% by reducing the algorithm and improving the Cache. Tested for <code>N=500,000,000</code>.</p>\n\n<p><strong>First lets look at the properties of the Collatz sequence</strong></p>\n\n<p>1) If the number is even, then we will perform a right-shift until the value is odd.</p>\n\n<p>2) If the number is odd, then it will take one iteration of <code>n=3*n+1</code> to become even.</p>\n\n<blockquote>\n <p>Proof</p>\n \n <p>Let's rewrite our equation <code>n = 3*n + 1</code> = <code>(2*n) + (n+1)</code> = <code>(n<<1) + (n+1)</code>.</p>\n \n <p>The first term <code>(n<<1)</code> is guaranteed to be even, because a left shift will pad a 0 to the lsb.</p>\n \n <p>The second term <code>(n+1)</code> is guaranteed to be even, because an odd number plus one is even.</p>\n \n <p>The sum of two even terms is even.</p>\n \n <p>As a result, <code>n = 3*n + 1</code> is guaranteed to create an even n (when n is odd).</p>\n</blockquote>\n\n<p>3) <code>n = 3*n+1</code> for odd n will never be <code>1</code>.</p>\n\n<blockquote>\n <p>Proof</p>\n \n <p>See #2. Result must be even.</p>\n</blockquote>\n\n<p><strong>Now let's rewrite our Collatz sequence</strong></p>\n\n<pre><code>// if even, right shift until odd\nwhile ((n & 1) == 0) {\n n >>= 1;\n ++len;\n}\nwhile ( n != 1 ) {\n // odd (guaranteed)\n n = 3*n + 1;\n // even (guaranteed)\n n >>= 1;\n // if even, right shift until odd\n while ((n & 1) == 0) {\n n >>= 1;\n ++len;\n }\n // account for 2 guaranteed steps (see above)\n len += 2;\n}\n</code></pre>\n\n<p><strong>Now let's improve the Cache</strong></p>\n\n<p>From our properties (see above), we notice that the Collatz sequence will frequently alternate between positive and negative numbers. The maximum number of odd numbers that can be seen before seeing an even number is one. The maximum number of even numbers that can be seen before seeing an odd number depends on N, but it is relatively small due to right shifting (max 31 for an unsigned int). For this reason, I have decided to only store odd numbers in the Cache, which will reduce our Cache to half the size.</p>\n\n<p>Additionally, I have decided to store values in the cache as I encounter them--rather than set only the initial values at the end of each sequence. In order to achieve this, we will need to store the values in a preliminary buffer, and then, at the end of the Collatz sequence, add them to the cache and calculate the length by taking the difference between the length that we first encountered the number, and the final length of the sequence.</p>\n\n<p>Since we are storing the values we encounter rather than the initial values. We can now improve our algorithm by starting at N/2 as you mentioned, because we will still cache values for the range [2, N/2).</p>\n\n<p><strong>Here is the resulting function</strong></p>\n\n<pre><code>void collatz(unsigned N, unsigned& r_index, unsigned& r_length) {\n unsigned *cache, n0, len, i=0, lenMax=0;\n unsigned long long n;\n\n // cache size\n const unsigned cacheMaxN = N;\n const unsigned cacheSize = (cacheMaxN/2) + 1; // store all odd from (1,cacheMaxN) exclusive\n\n // cache\n cache = new unsigned[cacheSize];\n memset(cache, 0, cacheSize*sizeof(unsigned));\n\n // cache buffer (for temporarily holding cache values)\n struct CacheObject {\n unsigned n;\n unsigned n0_to_n_len;\n };\n std::vector<CacheObject> buffer;\n buffer.reserve(128);\n CacheObject cObj;\n\n for (n0 = N/2; n0 < N; ++n0 ) {\n // initial\n n = n0;\n len = 0;\n // collatz\n // if even, right shift until odd\n while ((n & 1) == 0) {\n n >>= 1;\n ++len;\n }\n while ( n != 1 ) {\n // odd (guaranteed), check cache\n if ( n < cacheMaxN ) {\n if ( cache[ n>>1 ] ) {\n // use cache value\n len += cache[ n>>1 ];\n break;\n } else {\n // store cache value\n // store to cache as difference between current length and final length\n // needs to resolve final length first, so store in queue\n cObj.n = n;\n cObj.n0_to_n_len = len;\n buffer.push_back( cObj );\n }\n }\n // odd (guaranteed)\n n = 3*n + 1;\n // even (guaranteed)\n n >>= 1;\n // if even, right shift until odd\n while ((n & 1) == 0) {\n n >>= 1;\n ++len;\n }\n // account for 2 guaranteed steps (see above)\n len += 2;\n }\n // buffer to cache\n if ( buffer.size() != 0 ) {\n for (CacheObject o : buffer) {\n cache[ o.n>>1 ] = len - o.n0_to_n_len;\n }\n buffer.clear();\n }\n // set max len\n if ( len > lenMax ) {\n lenMax = len;\n i = n0;\n }\n }\n\n r_index = i;\n r_length = lenMax;\n\n delete [] cache;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T20:53:12.630",
"Id": "230787",
"ParentId": "230501",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T18:43:39.693",
"Id": "230501",
"Score": "4",
"Tags": [
"c++",
"performance",
"collatz-sequence"
],
"Title": "Optimized Longest Collatz Sequence"
}
|
230501
|
<p>We have an upcoming project at work which is going to require working with express.js. I have no prior experience with node.js, so I thought I'd try and do something aside from some courses. Are there any anti-patterns and what can be improved?</p>
<p><strong>Objective</strong></p>
<p>I have a text file that is retrieved from an external source and looks like this (It has a lot more lines than this)</p>
<p>I do not need the first 3 lines, but I do need the data separated by a "|". Wherever there is a "||" it adds an undefined value to the array so I just remove it. I also do not need any text which has a "/" in it.</p>
<pre><code>2019-10-09 11:03:33 : ============================= ATTACK LOG ==============================
2019-10-09 11:03:33 : | ------- LOOT ------ ------ BONUS ------
2019-10-09 11:03:33 : |AC|TIME.|TROP.|SRC|DS| GOLD| ELIXIR| DE|TR.|S| %| GOLD|ELIXIR| DE|L.
2019-10-09 11:15:44 : 1|11:15| 1761| 17| 4| 450447| 546344|1704|-17|0| 47| 0| 0| 0|--||211/220|
2019-10-09 11:20:49 : 1|11:20| 1744| 14| 4| 307817| 279805| 643| 10|1| 62| 15640| 15640| 0|G1||209/220|
</code></pre>
<p>I am using a library called line-reader to read the text file and my Mongoose schema is defined as Results </p>
<pre><code> router.get('/retrieve-logs', (req,res,next)=>{
var headers = ['accountNumber','timeOfAttack',
'trophies','searches','ds',
'gold','elixir','darkElixir',
'trophyChange','victory','damagePercentage',
'bonusGold','bonusElixir','bonusDarkElixir'];
const filePath = 'AttackLog-2019-10.log'
//Read from each line
lineReader.eachLine(filePath, (line)=> {
//Do nothing if 'ATTACK LOG' in line
if (line.includes('ATTACK LOG')) {
} else {
//Remove appended date and time
removedDateTime = line.substring(22);
if (removedDateTime.includes('GOLD')) {
} else {
//Grab lines after headers removed
attackData = removedDateTime.split("|");
tempAttackData = [];
//Remove undefined from array of data and remove last value from array
for(let i of attackData)
i && tempAttackData.push(i);
attackData = tempAttackData;
//Remove last item from array which we don't need
attackData.pop();
// Remove excess whitespace
cleanedAttackData= [];
attackData.forEach((data, index) => {
cleaned = data.trim();
cleanedAttackData.push(cleaned)
});
//Create object for DB {headers: attackData}
var result = {};
headers.forEach((headers, i) => result[headers] = cleanedAttackData[i]);
//Save the created object
finalResults = new Results(result)
finalResults.save();
}
}
})
Results.find({},(err, docs) => {
res.status(200).send({
message: "Results successfully loaded",
success: docs
})
})
})
</code></pre>
|
[] |
[
{
"body": "<h2>Style</h2>\n<ul>\n<li><p>Comments are just noise and thus reduce readability if they state what is obvious in the code. EG the comment <code>//Read from each line</code> is followed by the line\n<code>lineReader.eachLine(filePath, (line)=> {</code></p>\n</li>\n<li><p>Do not mix styles. You use semicolons randomly in the code. Use them or not, do not mix them</p>\n</li>\n<li><p>Do not add empty blocks or as your comment describes "do nothing" . Example <code>if (line.includes('ATTACK LOG')) { } else </code> should be <code>if (!line.includes('ATTACK LOG')) {</code></p>\n</li>\n<li><p>Do not add magic numbers or string in the code. Define them as constants in one place</p>\n</li>\n<li><p>Always delimite statement blocks with <code>{}</code>. EG <code>for(let i of attackData) i && tempAttackData.push(i);</code> should be <code>for(const i of attackData) { i && tempAttackData.push(i) }</code></p>\n</li>\n<li><p>Use constants for variables that do not change</p>\n</li>\n<li><p>Single argument arrow functions do not need the <code>()</code> around the argument. EG <code>(line)=> {</code> can be <code>line => {</code></p>\n</li>\n<li><p>Spaces between commas</p>\n</li>\n<li><p>Undeclared variable are dangerouse. The variables <code>finalResults</code>, <code>attackData</code>, <code>tempAttackData</code>, <code>cleanedAttackData</code> and <code>removedDateTime</code> are all undecalared and thus are part of the top level scope and may clash creating very hard to debug problems</p>\n</li>\n<li><p>Avoid single use variables. EG <code>finalResults = new Results(result); finalResults.save();</code> can be <code>new Results(result).save();</code></p>\n</li>\n<li><p><code>i</code> is used as a loop counter and should not be used to represent a value or item of an array. The loop <code>for (let i of ...</code> should be <code>for (const item of...</code></p>\n</li>\n<li><p>Do not add arguments to a function if that argument is not used. EG <code>tempAttackData.forEach((data, index) =></code> You do not use <code>index</code> so there is no need to define it</p>\n</li>\n</ul>\n<h2>Logic</h2>\n<p>The whole thing feels clumsy as you move data from array to array, variable to variable, and step over and into nested and superfluous statements blocks.</p>\n<p>It can be greatly simplified by creating a few helper functions to separate the various tasks. See example.</p>\n<p>There also seams to be a bug as you do not check if the line is the second header line (contains <code>"---- LOOT -----"</code>).</p>\n<h2>Example</h2>\n<p>The example breaks the task into smaller functions reducing the overall source code (and executional) complexity.</p>\n<p>The additional item at the end of the data line is just ignored (rather than popped from the array) by the function <code>Attack</code> which creates the attack object you save.</p>\n<pre><code>const LOGS = "/retrieve-logs";\nconst message = "Results successfully loaded";\nconst FILE_PATH = "AttackLog-2019-10.log"; \nconst FIELDS = "accountNumber,timeOfAttack,trophies,searches,ds,gold,elixir,darkElixir,trophyChange,victory,damagePercentage,bonusGold,bonusElixir,bonusDarkElixir";\nconst Attack = new Function(...FIELDS.split(","), "return {" + FIELDS + "};");\n\nconst valid = line => ! ["ATTACK LOG", "GOLD", "LOOT"].some(mark => line.includes(mark));\nconst clean = line => line.slice(22).replace("||", "|");\nconst parse = line => Attack(...clean(line).split("|").map(item => item.trim())); \n\nrouter.get(LOGS, (req, res) => { \n lineReader.eachLine(FILE_PATH, line => { valid(line) && new Results(parse(line)).save() });\n Results.find({}, (err, success) => { res.status(200).send({message, success}) });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T05:07:42.300",
"Id": "449166",
"Score": "0",
"body": "Thanks for the help. I'll keep all of this in mind."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T23:15:55.937",
"Id": "230512",
"ParentId": "230505",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230512",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T21:15:49.173",
"Id": "230505",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"node.js",
"express.js"
],
"Title": "Reading a text file, manipulating it and saving it to a mongo database"
}
|
230505
|
<p>I tried to implement KMP algorithm on my own and found it kind of hard to follow.
Can you please comment how would you make this code easier to read / understand.</p>
<pre><code>using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StringQuestions
{
[TestClass]
public class KMPAlgorithmTest
{
[TestMethod]
public void TestMethod1()
{
string input = "abcdefgh";
string pattern = "def";
Assert.AreEqual(3, KMP.FindSubString(input, pattern)[0]);
}
[TestMethod]
public void TestMethod2()
{
string input = "abcdabcabcdf";
string pattern = "abcdf";
Assert.AreEqual(7, KMP.FindSubString(input, pattern)[0]);
}
//naive algo O(n*m)
[TestMethod]
public void WorstCaseTest()
{
string input = "aaaaaaab";
string pattern = "aaab";
Assert.AreEqual(4, KMP.FindSubString(input, pattern)[0]);
}
[TestMethod]
public void FailTest()
{
string input = "aaaaaaab";
string pattern = "ggg";
Assert.AreEqual(0,KMP.FindSubString(input, pattern).Count);
}
}
public class KMP
{
public static List<int> FindSubString(string str, string pattern)
{
List<int> result = new List<int>();
int strLength = str.Length;
int pLength = pattern.Length;
if (strLength < pLength)
{
return result;
}
//the longest prefix suffix
// we allocate a memory with Pattern size
int[] lps = new int[pLength];
ComputeLps(lps, pLength, pattern);
int j = 0; // index for pattern
int i = 0; // index for str
while (i < strLength)
{
if (pattern[j] == str[i])
{
j++;
i++;
}
if (j == pLength)
{
//pattern is found at index i-j
result.Add(i - j);
j = lps[j - 1];
}
else if (i < strLength && pattern[j] != str[i])
{
if (j != 0)
{
j = lps[j - 1];
}
else
{
i = i + 1;
}
}
}
return result;
}
private static void ComputeLps(int[] lps, int pLength, string pattern)
{
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0
while (i < pLength)
{
if (pattern[i] == pattern[len])
{
len++;
lps[i] = len;
i++;
}
//(pattern[i] != pattern[len])
else
{
if (len != 0)
{
len = lps[len - 1];
}
else
{
lps[i] = len;
i++;
}
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T22:06:32.670",
"Id": "449419",
"Score": "0",
"body": "This is [Knuth-Morris-Pratt](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) string searching algorithm, for those who don't know what KMP means off the top of their head. A bit more context and exposition of how it works on the part of OP would be helpful."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T21:43:35.157",
"Id": "230506",
"Score": "1",
"Tags": [
"c#",
"algorithm",
"strings"
],
"Title": "C# KMP algorithm"
}
|
230506
|
<p>I wrote this code for a simple app that gives us random images. The code works, but I feel like I'm doing something wrong. And one thing I would love to know is instead of grabbing from a folder called "resources", we would actually grab from a custom folder inside my exe. So there's no need to add any folder to a different computer, all works inside the exe. </p>
<ul>
<li>Is that possible to do ? </li>
</ul>
<p>I'm slowly learning C#. Thank you for your time in reading my post.</p>
<p><sup>P.S I'm very new in using the Lambda expression.</sup></p>
<pre><code> public partial class Menu : Form
{
private string[] files;
private string[] files2;
private string[] files3;
private string[] files4;
private int currentIndex = 0;
private int currentIndex2 = 0;
private int currentIndex3 = 0;
private int currentIndex4 = 0;
Random rnd = new Random();
public Menu()
{
InitializeComponent();
}
private void initializeImages()
{
string appRoot = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
files = System.IO.Directory.GetFiles(appRoot + @"\Resources");
files2 = System.IO.Directory.GetFiles(appRoot + @"\Resources");
files3 = System.IO.Directory.GetFiles(appRoot + @"\Resources");
files4 = System.IO.Directory.GetFiles(appRoot + @"\Resources");
files = files.OrderBy(x => rnd.Next()).ToArray();
files2 = files.OrderBy(x => rnd.Next()).ToArray();
files3 = files.OrderBy(x => rnd.Next()).ToArray();
files4 = files.OrderBy(x => rnd.Next()).ToArray();
}
private void setImage()
{
pictureBox1.ImageLocation = files[currentIndex];
pictureBox2.ImageLocation = files2[currentIndex2];
pictureBox3.ImageLocation = files3[currentIndex3];
pictureBox4.ImageLocation = files4[currentIndex4];
}
private void nextImage()
{
currentIndex = currentIndex < files.Length - 1 ? currentIndex + 1 : files.Length - 1;
setImage();
}
private void button1_Click(object sender, EventArgs e)
{
initializeImages();
nextImage();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T23:42:27.083",
"Id": "449157",
"Score": "1",
"body": "Welcome to CR! Sounds like the code you're putting up for peer review isn't working as intended, which is drawing close votes (see [help/on-topic] for what's expected of code posted here). If you removed the part about changing what it does (and added more context about what's what.. it's not as clear as you might think), you would be getting extremely valuable feedback on any/all aspects of it; feel free to [edit] anytime! PS - it's \"lambda\" ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T04:36:10.897",
"Id": "449165",
"Score": "0",
"body": "This is lambada: https://en.wikipedia.org/wiki/Lambada"
}
] |
[
{
"body": "<blockquote>\n<pre><code> private void initializeImages()\n {\n string appRoot = System.IO.Path.GetDirectoryName(Application.ExecutablePath);\n files = System.IO.Directory.GetFiles(appRoot + @\"\\Resources\");\n files2 = System.IO.Directory.GetFiles(appRoot + @\"\\Resources\");\n files3 = System.IO.Directory.GetFiles(appRoot + @\"\\Resources\");\n files4 = System.IO.Directory.GetFiles(appRoot + @\"\\Resources\");\n files = files.OrderBy(x => rnd.Next()).ToArray();\n files2 = files.OrderBy(x => rnd.Next()).ToArray();\n files3 = files.OrderBy(x => rnd.Next()).ToArray();\n files4 = files.OrderBy(x => rnd.Next()).ToArray();\n }\n</code></pre>\n</blockquote>\n\n<p>Here you load the same file names into four different arrays of strings. This is very memory inefficient and unnecessary. Instead only load them once into a single array and shuffle that when you want to change the images in the picture boxes.</p>\n\n<p>In general: when you feel the need to add indices to the names of a set of variables like you do, you should reconsider your design - and you'll probably realize that an array or list or other kind of collection is the solution.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>Random rnd = new Random();\n</code></pre>\n</blockquote>\n\n<p>In general: avoid abbreviated names of properties, fields, methods, object/classes etc. Provide descriptive names and let intellisense in the IDE do the work for you. Here <code>random</code> or <code>randomGenerator</code> would be descriptive names.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>private void button1_Click(object sender, EventArgs e)\n {\n initializeImages();\n nextImage();\n }\n</code></pre>\n</blockquote>\n\n<p>Here you repeatedly reload the image file names. This makes sense if the number of images in the location changes - but you look in a sub folder to the installation folder which indicates that they are rather constant, so no need to do it other than when the form loads.</p>\n\n<hr>\n\n<p>Below I've tried to refactor your code while implementing the above suggestions:</p>\n\n<pre><code>private string[] imageFileNames;\nRandom random = new Random();\n\npublic Menu()\n{\n InitializeComponent();\n\n InitializeImages();\n}\n\nprivate void InitializeImages()\n{\n imageFileNames = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), \"Resources\"));\n}\n\nprivate void ShuffleImages()\n{\n Array.Sort(imageFileNames, (a, b) => random.Next(0, 3) - 1);\n}\n\nprivate void SetImages()\n{\n var picturBoxes = new[] { pictureBox1, pictureBox2, pictureBox3, pictureBox4 };\n\n for (int i = 0; i < picturBoxes.Length; i++)\n {\n picturBoxes[i].ImageLocation = imageFileNames[i % imageFileNames.Length];\n }\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n ShuffleImages();\n SetImages();\n}\n</code></pre>\n\n<hr>\n\n<p>If the number of images is limited you can consider to load them all once into an list of <code>Image</code> objects and then shuffle these instead of the file names.</p>\n\n<pre><code>private void InitializeImages()\n{\n images = Directory\n .GetFiles(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), \"Resources\"))\n .Select(fn => Image.FromFile(fn)).ToArray();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T03:46:56.963",
"Id": "449443",
"Score": "0",
"body": "Thank you for your time and kindness to explain me all of this, i learned a lot ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T04:27:30.090",
"Id": "449444",
"Score": "0",
"body": "I only have one question, when i use bitmaps, normally i have to dispose them, so this method dons't increase the memory usage if we keep clicking the random option?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T05:46:29.303",
"Id": "449449",
"Score": "0",
"body": "@Sinesters: You have a good point there. In `SetImage()`, you should check for existing images and call `Dispose()` on them if present."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:33:32.447",
"Id": "230539",
"ParentId": "230507",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230539",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T21:45:03.640",
"Id": "230507",
"Score": "4",
"Tags": [
"c#",
"beginner",
"array",
"random",
"winforms"
],
"Title": "Simple winform that randomizes images in a picturebox"
}
|
230507
|
<p>I wrote a function that partitions an image into multiple patches. Here is the function, are there any suggestions to make it better or more production ready in terms of the best software practice?</p>
<pre><code>def cal_patches(img,num_colums):
patch_list = []
num_rows = num_colums
x,y,w,h = 0,0, int(img.shape[1]/num_colums), int(img.shape[0]/ num_rows)
ind = 0
for i in range(num_colums):
x= 0
for j in range(num_rows):
ind += 1
y_end = min(y+h, img.shape[0])
x_end = min(x+w, img.shape[1])
patch = img[y: y_end, x: x_end]
patch_list.append(patch)
x += w
y += h
return patch_list
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:22:34.863",
"Id": "449148",
"Score": "1",
"body": "Welcome to CodeReview! Is there any other surrounding code you can show us - particularly what `img` is, and how it's loaded?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T23:09:04.677",
"Id": "449155",
"Score": "0",
"body": "My bets are on [tag:numpy] being involved here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T02:10:40.887",
"Id": "449160",
"Score": "0",
"body": "What is the point of this code? What makes it useful?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:12:34.077",
"Id": "449232",
"Score": "1",
"body": "I dont think \"what makes this code useful\" is a *useful* remark here. I would very much appreciate verification of `img` being a numpy array though, that's extremely relevant to possible solutions that avoid double looping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T15:02:07.813",
"Id": "449241",
"Score": "1",
"body": "Apart from the nice feedback you got already, perhaps check out numpy's [array_split](https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html#numpy.array_split) method. Not so much to their code or how it's inmpemented there, but just so you can use that method for this use case and don't need to reinvent the wheel"
}
] |
[
{
"body": "<h2>PEP-8 Guidelines</h2>\n\n<p>Your code violates the PEP-8 standard in several area, including (but not limited to):</p>\n\n<ul>\n<li>Operators should have 1 space before and after the operator (<code>y + h</code> instead of <code>y+h</code>)</li>\n<li>One space after commas (<code>x, y, w, h</code> not <code>x,y,w,h</code>)</li>\n<li>Slices should not have any spaces around the colon (<code>y:y_end</code> not <code>y: y_end</code>)</li>\n</ul>\n\n<h2>Spelling</h2>\n\n<p>Columns is spelt with an <code>n</code>.</p>\n\n<h2>Meaningful names</h2>\n\n<p>I don't know what <code>cal_patches</code> means. Is <code>cal</code> short for \"calculate\"? Your question title says \"partition\"; perhaps that should be part of the function name.</p>\n\n<h2><code>docstring</code></h2>\n\n<p>Add a doc-string to <code>help()</code> the user understand what the function does, and what the function returns ... without having to consult the source code.</p>\n\n<h2>Type Hints</h2>\n\n<p>With Python 3.6+, you can add type hints to the function to further improve understanding about what the function requires and what it returns:</p>\n\n<pre><code>def cal_patches(img: Image, num_colums: int) -> List[Image]:\n</code></pre>\n\n<h2>Useful arguments</h2>\n\n<p>The function can partition the image into a number of vertical columns. What if I wanted a number of rows as well? I can't request that.</p>\n\n<p>Oh wait! It does do rows too. But always the same number of rows and columns. Perhaps add <code>num_rows</code> to the argument list too?</p>\n\n<h2>Integer division</h2>\n\n<p><code>int(n / d)</code> is verbose and unnecessary. Use the integer division operator <code>n // d</code>.</p>\n\n<h2>Unused variables</h2>\n\n<p><code>ind</code> is never used anywhere, and could be removed.</p>\n\n<p><code>i</code> and <code>j</code> are never used anywhere, so could be replaced by the \"throwaway\" variable <code>_</code>. Even better, you could use the <code>w</code> and <code>h</code> values as the step size for the <code>range()</code>, and get rid of the <code>x += w</code> and <code>y += h</code> statements:</p>\n\n<h2>Avoid calculating unchanging values</h2>\n\n<p>In the inner loop, <code>y</code> is not changing, so <code>y_end</code> results in the same value each iteration of the inner loop. It can be moved out of the inner loop.</p>\n\n<h2>Bug?</h2>\n\n<p>The inner loop goes over the number rows, but is increase <code>x</code> by <code>w</code>, which is a column increment. Did you accidentally swap the rows and columns? It works as long as <code>num_rows == num_columns</code>, but it will cause grief when that is relaxed.</p>\n\n<hr>\n\n<h2>Updated code</h2>\n\n<pre><code>def create_image_patches(img, num_rows, num_columns):\n \"\"\"\n Partition an image into multiple patches of approximately equal size.\n The patch size is based on the desired number of rows and columns.\n Returns a list of image patches, in row-major order.\n \"\"\"\n\n patch_list = []\n width, height = img.shape[1], img.shape[0]\n w, h = width // num_columns, height // num_rows\n\n for y in range(0, height, h): \n y_end = min(y + h, width)\n for x in range(0, width, w):\n x_end = min(x + w, height)\n patch = img[y:y_end, x:x_end]\n patch_list.append(patch)\n\n return patch_list\n</code></pre>\n\n<p>Add type hints using the <code>typing</code> module.</p>\n\n<hr>\n\n<h2>Generator</h2>\n\n<p>As suggested by <a href=\"https://codereview.stackexchange.com/users/98493/graipher\">@Graipher</a>, this function could be turned into a generator, which may be useful depending on how the patches are processed downstream:</p>\n\n<pre><code>def generate_image_patches(img, num_rows, num_columns):\n \"\"\"\n Generate image patches of approximately equal size from a source image.\n The patch size is based on the desired number of rows and columns.\n Patches are generated in row-major order.\n \"\"\"\n\n width, height = img.shape[1], img.shape[0]\n w, h = width // num_columns, height // num_rows\n\n for y in range(0, height, h): \n y_end = min(y + h, width)\n for x in range(0, width, w):\n x_end = min(x + w, height)\n yield img[y:y_end, x:x_end]\n</code></pre>\n\n<p>A \"helper\" function could be used to turn the generator back into a <code>list</code>, if required for existing callers of the function:</p>\n\n<pre><code>def create_image_patches(img, num_rows, num_columns):\n \"\"\"\n Partition an image into multiple patches of approximately equal size.\n The patch size is based on the desired number of rows and columns.\n Returns a list of image patches, in row-major order.\n \"\"\"\n\n return list(generate_image_patches(img, num_rows, num_columns))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T08:06:03.153",
"Id": "449178",
"Score": "2",
"body": "You don't need to initialize `x` and `y` to zero, the `for` loop will already do that. I would also consider making this a generator, depending on how the resulting patches are processed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T13:53:49.643",
"Id": "449225",
"Score": "1",
"body": "@Graipher Re: x & y, good point! I reviewed pretty much from top down, and applied my comments to create the “Updated code” ... I clearly needed to do a two-pass review to catch the new redundancies. Re: generator. Fair point. I hesitate to introduce too many new concepts into one review, but there is no “beginner” tag, so unless someone beats me to it, I’ll update my answer to include generation ... in a little while when I have time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T03:55:04.033",
"Id": "230518",
"ParentId": "230508",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "230518",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:07:15.570",
"Id": "230508",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "a function to partition images into patches"
}
|
230508
|
<p>So in learning c++ I have to make a little program that makes a game list that can add games to the list, remove games, and display the list, and it has to use vectors and iterators, so I made the program and need feedback on how to improve it and make it cleaner/better</p>
<pre><code>// Favourite Game list
// Program using vectors and iterators
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<ctime>
#include<cctype>
#include<cstdlib>
using namespace std;
int main()
{
bool quit = false;
string game_name;
vector<string> gameList;
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
int choice;
while (!quit)
{
cout << "1: Add a Game to List" << endl;
cout << "2: Remove a Game from the List" << endl;
cout << "3: List all the Games on the List" << endl;
cout << "4: Exit the Program" << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the Game Name to add" << endl;
cin >> game_name;
gameList.push_back(game_name);
break;
case 2:
for (iter = gameList.begin(); iter != gameList.end(); ++iter)
cout << *iter << endl;
cout << "Here is the list of games enter the one to remove" << endl;
cin >> game_name;
iter = find(gameList.begin(), gameList.end(), game_name);
cout << *iter << "This is the game we will remove" << endl;
gameList.erase(iter);
break;
case 3:
cout << "Your Games" << endl;
for (iter = gameList.begin(); iter != gameList.end(); ++iter)
cout << *iter << endl;
break;
case 4:
quit = true;
cout << "You chose quit! The Program Will Close Now" << endl;
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:42:27.093",
"Id": "449149",
"Score": "1",
"body": "First of all: Ditch this `using namespace std;` please!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:44:42.963",
"Id": "449150",
"Score": "0",
"body": "Does not a lot of the code rely on that though, or would i do like std::cout, etc for everything, im new to c++ so any tips help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:46:56.113",
"Id": "449151",
"Score": "0",
"body": "Use explicit namespace scopes when needed, either like `using std::cout;` etc., or just prepend it when used like `std::cout`. See here: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:52:40.280",
"Id": "449153",
"Score": "0",
"body": "What version of C++ are you using? C++89? C++11 (or newer)? (And do you want to learn about the new stuff?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:54:50.967",
"Id": "449154",
"Score": "1",
"body": "I believe i am using c++17, using the 2019 community version of visual studio, and yes I want to learn a lot about new c++ stuff, just started learning c++ today"
}
] |
[
{
"body": "<h1>Unused headers</h1>\n<p>As far as I can tell, nothing from the following headers is actively being used, so they shouldn't be included.</p>\n<ul>\n<li><code><ctime></code></li>\n<li><code><cctype></code></li>\n<li><code><cstdlib></code></li>\n</ul>\n<h1><code>using namespace std</code></h1>\n<p>While it's probably not quite as bad using it inside a .cpp file instead of a header, it's generally seen as a <a href=\"https://stackoverflow.com/q/1452721/6467688\">code smell</a>.</p>\n<h1>Variable usage</h1>\n<p>There are some variables that are declared at the begin of <code>main</code>, but only used further down (if at all, <code>myIterator</code> appears to not be used at all). This makes it harder to keep track of variables.</p>\n<h1>Magic numbers/literals</h1>\n<p>There are a lot of numbers/string literals, whose intention is not obvious in all cases. Examples include values <code>1</code> to <code>4</code> for input choices, or strings like <code>"Your Games"</code>.</p>\n<p>One way of dealing with these so called magic numbers is to put them into adequately named enums, constants or variables.</p>\n<h1>Container choice</h1>\n<p>There doesn't seem to be any dependency on actually keeping the order of the games intact. In addition, a small oversight (it is possible to add the same game twice) leads me to suggest that maybe a different container would be a better fit: <code>std::unordered_set</code>.</p>\n<p><code>std::unordered_set</code> allows us to insert and remove items with amortized <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> runtime complexity, as well as to ignore duplicates.</p>\n<h1>Iterators or ranged <code>for</code> loops?</h1>\n<p>Generally, I prefer ranged <code>for</code> loops over "manual" iterator loops if the code isn't requiring some specific iterator behavior. Since this isn't the case here, I would suggest using ranged <code>for</code> loops for ease of reading.</p>\n<h1>Prefer smaller functions</h1>\n<p>Generally, it is easier to work with smaller functions: There is less mental overhead due to shorter code, fewer variables and narrower scope. Additionally, it allows for code reuse, which might reduce code duplication.</p>\n<p>While the given code is small enough that these concerns might not matter right now, it will become a lot more obvious once additional logic like formatting, input handling or similar gets added.</p>\n<h1>Error checking</h1>\n<p>Neither user inputs nor results of calls to <code>std::find</code> are being checked for invalid values. This means I can easily cause errors inside the program (or crash it) by just entering weird stuff, or trying to remove non-existing entries.</p>\n<h1>Summary</h1>\n<p>Using all these suggestions, a cleaned up version could look like this:</p>\n<pre><code>#include <iostream>\n#include <string>\n#include <unordered_set>\n\nenum class input_choices : int {\n add = 1,\n remove,\n list,\n exit\n};\n\nstd::ostream& operator<<(std::ostream& output, input_choices choice) {\n output << static_cast<int>(choice);\n return output;\n}\n\nstd::istream& operator>>(std::istream& input, input_choices& choice) {\n int temp = 0;\n input >> temp;\n choice = static_cast<input_choices>(temp);\n \n return input;\n}\n\nnamespace messages {\n static const auto menu_header = "Menu";\n static const auto option_add = "Add a game to the list";\n static const auto option_remove = "Remove a game from the list";\n static const auto option_list = "Show all games on the list";\n static const auto option_exit = "Exit the program";\n static const auto enter_menu_choice = "Your choice: ";\n\n static const auto enter_game_to_add = "Enter the Game Name to add";\n static const auto enter_game_to_remove = "Here is the list of games enter the one to remove";\n static const auto list_header = "Your games";\n static const auto quitting = "Exiting program...";\n static const auto invalid_choice = "Unknown menu option";\n}\n\nclass game_list_menu {\n std::unordered_set<std::string> games;\n\npublic:\n void add_game() {\n const auto game = enter_game(messages::enter_game_to_add);\n games.insert(game);\n }\n\n void remove_game() {\n print_games();\n\n const auto game = enter_game(messages::enter_game_to_remove);\n games.erase(game);\n }\n \n std::string enter_game(std::string_view prompt) const {\n std::cout << prompt << ": ";\n \n auto game = std::string{};\n std::cin >> game;\n \n return game;\n }\n\n\n void print_games() const {\n std::cout << "\\n" << messages::list_header << ":\\n\\n";\n \n for(auto& game : games) {\n std::cout << "\\t" << game << "\\n";\n }\n }\n\n void print_menu() const {\n std::cout << "\\n" << messages::menu_header << "\\n\\n";\n \n print_choice(input_choices::add, messages::option_add);\n print_choice(input_choices::remove, messages::option_remove);\n print_choice(input_choices::list, messages::option_list);\n print_choice(input_choices::exit, messages::option_exit);\n \n std::cout << "\\n" << messages::enter_menu_choice;\n }\n\n void print_choice(input_choices choice, std::string_view description) const {\n std::cout << "\\t" << choice << ": " << description << "\\n";\n }\n\n void main_loop() {\n auto choice = input_choices::exit;\n\n do {\n print_menu();\n \n std::cin >> choice;\n\n switch(choice) {\n case input_choices::add:\n add_game();\n break;\n case input_choices::remove:\n remove_game();\n break;\n case input_choices::list:\n print_games();\n break;\n case input_choices::exit:\n std::cout << messages::quitting << "\\n";\n break;\n default:\n std::cout << messages::invalid_choice << "\\n";\n break;\n }\n } while(choice != input_choices::exit);\n }\n};\n\nint main() {\n auto menu = game_list_menu{};\n menu.main_loop();\n}\n</code></pre>\n<blockquote>\n<p>Can you see how you can easily tell what each function does or what the meaning of each number/literal is?</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T06:57:24.650",
"Id": "449174",
"Score": "3",
"body": "The code might look a little overwhelming for beginners at first. But this is a really nice display of good practices!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T16:03:12.217",
"Id": "449247",
"Score": "0",
"body": "@sbecker: Thanks! I tried to keep it very simple (and beginner-friendly), i.e. no templates, no `noexcept`, no `constexpr`, and so on. I also wanted to show some of the more modern c++ features in an easy-to-grasp way, as the code in question looked like it time-traveled around 30 years into the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T06:40:13.167",
"Id": "449565",
"Score": "0",
"body": "Your code reading the `input_choices` runs into UB if the users enters a value outside the range. Please do range checking there! Note that the OPs code handled the invalid value by simply falling through the loop as ints were used. Here it works in practice but it is still UB. And a missing const on the range-based-for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T08:14:41.320",
"Id": "449570",
"Score": "0",
"body": "@Flamefire: Please clarify where I run into UB. Casting a value to an enum where the value is of the same type as the enums underlying type is well defined. As for error handling, I included a `default` case with a nice error message."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T08:36:51.687",
"Id": "449572",
"Score": "0",
"body": "You are correct. I haven't seen you use a fixed type for the enum, so it is all good. Then just 2 nits: The const in the loop and `enter_game` can be static or a free function."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T00:17:02.810",
"Id": "230513",
"ParentId": "230510",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "230513",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:40:23.527",
"Id": "230510",
"Score": "9",
"Tags": [
"c++",
"beginner"
],
"Title": "Favorite Game List utilizing vectors and iterators"
}
|
230510
|
<p>I am working on an e-commerce website. I have a <code>CarMake</code> dropdown which contains car make names and their corresponding Id, for example: { 1:Alfa romeo}, { 2:Audi }, { 3:BMW }, etc</p>
<p>I want to keep this lookup in cache, so I won't have to make a trip to DB every time I want to get the corresponding Name or Id...</p>
<p>So in my infrastructure layer, I read the data from DB and keep it in cache, I am using a static <code>CarMakeLookup</code> class:</p>
<pre><code>public static class CarMakeLookup
{
private static readonly Dictionary<short, string> _carMakeIdLookup;
private static readonly Dictionary<string, short> _carMakeNameLookup;
static CarMakeLookup()
{
_carMakeIdLookup = new Dictionary<short, string>();
_carMakeNameLookup = new Dictionary<string, short>();
using (var context = ApplicationDbContext.Create())
{
DropdownRepository dropdownRepository = new DropdownRepository(context);
var carMakes = dropdownRepository.GetCarMakes();
foreach (var carMake in carMakes)
{
_carMakeIdLookup[carMake.CarMakeId] = carMake.CarMakeName;
_carMakeNameLookup[carMake.CarMakeName.ToLower()] = carMake.CarMakeId;
}
}
}
public static string GetCarMakeName(short carMakeId)
{
if (carMakeId <= 0)
{
return string.Empty;
}
if (_carMakeIdLookup.ContainsKey(carMakeId))
{
return _carMakeIdLookup[carMakeId];
}
return string.Empty;
}
public static short GetCarMakeId(string carMakeName)
{
if (!string.IsNullOrEmpty(carMakeName))
{
string lowerCaseCarMakeName = carMakeName.ToLower();
if (_carMakeNameLookup.ContainsKey(lowerCaseCarMakeName))
{
return _carMakeNameLookup[lowerCaseCarMakeName];
}
}
return -1;
}
public static Dictionary<short, string> GetCarMakeLookup()
{
return _carMakeIdLookup;
}
}
</code></pre>
<p>I also need to display car make in a dropdown in my View... so I need a <code>List<SelectListItem></code> to be displayed as a dropdown. So in my Application layer I have another static class which holds this list:</p>
<pre><code>public static class CarCache
{
static CarCache()
{
var selectCarMake = new SelectListItem { Value = "-1", Text = "Select a car", Disabled = true, Selected = true };
CarMakeItemsIncludingSelect = new List<SelectListItem>(); // Dropdown's first option should be "select a car"
CarMakeItemsIncludingSelect.Insert(0, selectCarMake);
foreach (KeyValuePair<short, string> carMakeKeyPair in CarMakeLookup.GetCarMakeLookup())
{
var selectListItem = new SelectListItem { Value = carMakeKeyPair.Key.ToString(), Text = carMakeKeyPair.Value };
CarMakeItemsIncludingSelect.Add(selectListItem);
}
}
public static List<SelectListItem> CarMakeItemsIncludingSelect { get; private set; }
public static string GetCarMakeName(short carMakeId)
{
return CarMakeLookup.GetCarMakeName(carMakeId);
}
public static short GetCarMakeId(string carMakeName)
{
return CarMakeLookup.GetCarMakeId(carMakeName);
}
}
</code></pre>
<p>I have a few more dropdowns like this in my application, for example <code>HouseType</code>, <code>JobType</code>, etc</p>
<p>Everything works fine, the only problem is that my application startup time is slow... I assume one problem is that when I start debugging the application, the application starts building all these static cache classes, and since these classes are static I cannot inject the <code>DbContext</code> into them... so each dropdown should build its own <code>DdContext</code> instance, get corresponding data from DB and Dispose of <code>DbContext</code>. There is no performance problem with the production server... </p>
<p>Any recommendation on how to improve this cache?</p>
|
[] |
[
{
"body": "<p>Global static state makes your code untestable...</p>\n\n<p>I would define your car make lookup as:</p>\n\n<pre><code>public class CarMakeLookup\n{\n public CarMakeLookup(IEnumerable<(short Id, string Make)> data)\n {\n Makes = data.ToDictionary(d => d.Id, d => d.Make);\n Ids = data.ToDictionary(d => d.Make, d => d.Id);\n }\n\n public IReadOnlyDictionary<short, string> Makes { get; }\n public IReadOnlyDictionary<string, short> Ids { get; }\n}\n</code></pre>\n\n<p>And read it with:</p>\n\n<pre><code>public class CarMakeReader : IReader<CarMakeLookup>\n{\n public CarMakeReader(Func<ApplicationDbContext> context) => \n Context = context;\n\n Func<DbContext> Context { get; }\n\n public Task<CarMakeLookup> ReadAsync()\n {\n using (var context = Context())\n return new CarMakeLookup(\n from cm in context.CarMakes\n select (cm.CarMakeId, cm.CarMakeName)); \n }\n}\n</code></pre>\n\n<p>Where <code>IReader<></code> is simply:</p>\n\n<pre><code>public interface IReader<TSet>\n{\n Task<TSet> ReadAsync();\n}\n</code></pre>\n\n<p>There should be also an extension method <code>Cache</code> defined nearby:</p>\n\n<pre><code>public static class Reader\n{\n public static IReader<TSet> Cache<TSet>(this IReader<TSet> source) =>\n new CachingReader<TSet>(source);\n}\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>class CachingReader<TSet> : IReader<TSet>\n{\n public CachingReader(IReader<TSet> source) => \n Lookup = new Lazy<Task<TSet>>(() => source.ReadAsync());\n\n Lazy<Task<TSet>> Lookup { get; }\n public Task<TSet> ReadAsync() => Lookup.Value;\n}\n</code></pre>\n\n<p>Now register you reader in the IoC container as a decorated singleton:</p>\n\n<pre><code>containerBuilder.RegisterInstance(ctx => new CarMakeLookup(\n ctx.Resolve<Func<ApplicationDbContext>>())\n .Cache()).AsImplementedInterfaces();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:51:24.530",
"Id": "449321",
"Score": "0",
"body": "Thanks for your answer, I am not able to fully understand your answer... where are you caching the data? are they cached in DbContext?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:53:52.020",
"Id": "449322",
"Score": "1",
"body": "@HoomanBahreini I register a singleton. Will share a link to a demo repository a little bit latter today."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T05:30:59.983",
"Id": "449338",
"Score": "1",
"body": "@HoomanBahreini Here is the [Demo](https://github.com/dmitrynogin/cachingreader)..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T16:34:23.750",
"Id": "230555",
"ParentId": "230511",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230555",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:41:45.090",
"Id": "230511",
"Score": "3",
"Tags": [
"c#",
"cache",
"static",
"asp.net-mvc-5"
],
"Title": "Caching lookup values in an e-commerce website"
}
|
230511
|
<p>I've been learning C# during my free time in the past months; before that, I was mostly writing Java, so the transition hasn't been too hard, but I've never had my code reviewed or read by someone else. </p>
<ul>
<li>Is there anything that could be improved, or maybe simplified?</li>
<li>Am I doing anything that would be considered bad practice or 'smelly' ? If so, what should I be doing instead?</li>
<li>I very rarely write comments; should I use them more, and specifically here, are there any methods or sections that could use some comments?</li>
</ul>
<p>The class <code>DMatrix</code> (D for double, as I intend to make one that uses floats instead, and another one for complex numbers), as you can guess, represents a matrix, or an m by n array of numbers. It started earlier today as rewrite of another implementation I had made in Java months ago; once I had finished translated that old Java code, I tried to include all the commonly used operations I could think of. I also tried to make the class easier and more intuitive to use, while keeping the code simple and -hopefully- readable, and trying to make use of all the C#-specific features I've learned about.</p>
<p>I've also included the <code>Misc.Utils</code> class, which mostly contains some static methods for generating random numbers in different ranges or types. I spend most of my coding time reinventing (or re-implementing) the wheel, or writing things from scratch, as I find it to be a good way to learn and understand most concepts, while also allowing me to implement and play with some interesting math or math-related topics.</p>
<p>DMatrix.cs</p>
<pre><code>using System;
using Mathlib.Misc;
namespace Mathlib.Matrix {
public class DMatrix {
private double[,] data;
public int NbRows {
get;
private set;
}
public int NbCols {
get;
private set;
}
public double this[int i, int j] {
get {
return data[i, j];
}
private set {
data[i, j] = value;
}
}
public static int Precision {
get;
set;
}
static DMatrix() {
Precision = 2;
}
public DMatrix(int n) {
if (n < 1) {
throw new Exception($"Cannot create matrix," +
$" N should be greater or equal to 1.\n\tN = {n}");
}
NbRows = NbCols = n;
Fill(0);
}
public DMatrix(int m, int n) {
if (m < 1) {
throw new Exception($"Cannot create matrix," +
$" M should be greater or equal to 1.\n\tM = {m}");
}
if (n < 1) {
throw new Exception($"Cannot create matrix," +
$" N should be greater or equal to 1.\n\tN = {n}");
}
NbRows = m;
NbCols = n;
data = new double[m, n];
Fill(0);
}
public DMatrix(int m, int n, double x) {
if (m < 1) {
throw new Exception($"Cannot create matrix," +
$" M should be greater or equal to 1.\n\tM = {m}");
}
if (n < 1) {
throw new Exception($"Cannot create matrix," +
$" N should be greater or equal to 1.\n\tN = {n}");
}
NbRows = m;
NbCols = n;
data = new double[m, n];
Fill(x);
}
public DMatrix(double[,] data) {
NbRows = data.GetLength(0);
NbCols = data.GetLength(1);
this.data = new double[NbRows, NbCols];
for (int i = 0; i < NbRows; i++) {
for (int j = 0; j < NbCols; j++) {
this.data[i, j] = data[i, j];
}
}
}
public DMatrix(DMatrix A) : this(A.data) { }
public void Fill(double x) {
for (int i = 0; i < NbRows; i++) {
for (int j = 0; j < NbCols; j++) {
data[i, j] = x;
}
}
}
public void Rand() {
for (int i = 0; i < NbRows; i++) {
for (int j = 0; j < NbCols; j++) {
data[i, j] = Utils.Rand();
}
}
}
public void Rand(double max) {
for (int i = 0; i < NbRows; i++) {
for (int j = 0; j < NbCols; j++) {
data[i, j] = Utils.Rand(max);
}
}
}
public void Rand(double min, double max) {
for (int i = 0; i < NbRows; i++) {
for (int j = 0; j < NbCols; j++) {
data[i, j] = Utils.Rand(min, max);
}
}
}
public void SwapRows(int row1, int row2) {
for (int i = 0; i < NbCols; i++) {
double temp = data[row1, i];
data[row1, i] = data[row2, i];
data[row2, i] = temp;
}
}
public static DMatrix operator -(DMatrix A) {
DMatrix res = new DMatrix(A.NbRows, A.NbCols);
for (int i = 0; i < A.NbRows; i++) {
for (int j = 0; j < A.NbCols; j++) {
res.data[i, j] = -A.data[i, j];
}
}
return res;
}
public static DMatrix operator ~(DMatrix A) {
return A.Transpose();
}
public static DMatrix operator +(DMatrix A, DMatrix B) {
if (A.NbRows != B.NbRows || A.NbCols != B.NbCols) {
throw new Exception($"Cannot compute sum, matrix dimensions do not match:\n\t" +
$"A : {A.NbRows}x{A.NbCols}\n\tB : {B.NbRows}x{B.NbCols}");
}
DMatrix res = new DMatrix(A.NbRows, A.NbCols);
for (int i = 0; i < A.NbRows; i++) {
for (int j = 0; j < A.NbCols; j++) {
res.data[i, j] = A.data[i, j] + B.data[i, j];
}
}
return res;
}
public static DMatrix operator -(DMatrix A, DMatrix B) {
return A + (-B);
}
public static DMatrix operator *(DMatrix A, DMatrix B) {
if (A.NbCols != B.NbRows) {
throw new Exception($"Cannot compute product, matrix dimensions do not match:\n\t" +
$"A : {A.NbRows}x{A.NbCols}\n\tB : {B.NbRows}x{B.NbCols}");
}
DMatrix res = new DMatrix(A.NbRows, B.NbCols);
for (int i = 0; i < res.NbRows; i++) {
for (int j = 0; j < res.NbCols; j++) {
for (int k = 0; k < A.NbCols; k++) {
res.data[i, j] += A.data[i, k] * B.data[k, j];
}
}
}
return res;
}
public DMatrix HadamardProduct(DMatrix A) {
if (NbCols != A.NbCols || NbRows != A.NbRows) {
throw new Exception($"Cannot compute Hadamard product," +
$" dimensions do not match:\n\tA : {NbRows}x{NbCols}\n\t" +
$"B : {A.NbRows}x{A.NbCols}");
}
DMatrix res = new DMatrix(NbRows, NbCols);
for (int i = 0; i < res.NbRows; i++) {
for (int j = 0; j < res.NbCols; j++) {
res.data[i, j] = data[i, j] * A.data[i, j];
}
}
return res;
}
public static DMatrix operator +(DMatrix A, double x) {
DMatrix res = new DMatrix(A.NbRows, A.NbCols);
for (int i = 0; i < A.NbRows; i++) {
for (int j = 0; j < A.NbCols; j++) {
res.data[i, j] = A.data[i, j] + x;
}
}
return res;
}
public static DMatrix operator -(DMatrix A, double x) {
return A + (-x);
}
public static DMatrix operator *(DMatrix A, double x) {
DMatrix res = new DMatrix(A.NbRows, A.NbCols);
for (int i = 0; i < A.NbRows; i++) {
for (int j = 0; j < A.NbCols; j++) {
res.data[i, j] = A.data[i, j] * x;
}
}
return res;
}
public double Trace() {
if (NbCols != NbRows) {
throw new Exception($"Cannot compute trace, matrix is not square:\n\t" +
$"A : {NbRows}x{NbCols}");
}
double res = 0;
for (int i = 0; i < NbRows; i++) {
res += data[i, i];
}
return res;
}
public double Det_recursive() {
if (NbCols != NbRows) {
throw new Exception($"Cannot compute determinant, matrix isn't square:\n\t" +
$"A : {NbRows}x{NbCols}");
}
double sum = 0;
if (NbRows == 1) {
return data[0, 0];
}
else if (NbRows == 2) {
return data[0, 0] * data[1, 1] - data[0, 1] * data[1, 0];
}
for (int N = 0; N < NbRows; N++) {
DMatrix minor = new DMatrix(NbRows - 1, NbRows - 1);
for (int i = 0; i < NbRows - 1; i++) {
for (int j = 0; j < NbRows; j++) {
if (j < N) {
minor.data[i, j] = data[i + 1, j];
}
else if (j > N) {
minor.data[i, j - 1] = data[i + 1, j];
}
}
}
int sgn = (N % 2 == 0) ? 1 : -1;
sum += sgn * data[0, N] * minor.Det_recursive();
}
return sum;
}
public double Norm_frobenius() {
double res = 0;
if (NbRows == 1 || NbCols == 1) {
for (int i = 0; i < NbRows; i++) {
for (int j = 0; j < NbCols; j++) {
res += data[i, j] * data[i, j];
}
}
}
else {
res = (~this * this).Trace();
}
return Math.Sqrt(res);
}
public static DMatrix Id(int n) {
DMatrix res = new DMatrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
res.data[i, j] = 1;
}
else {
res.data[i, j] = 0;
}
}
}
return res;
}
public DMatrix Transpose() {
DMatrix res = new DMatrix(NbRows, NbCols);
for (int i = 0; i < NbRows; i++) {
for (int j = 0; j < NbCols; j++) {
data[i, j] = data[j, i];
}
}
return res;
}
public DMatrix Row(int row) {
DMatrix A = new DMatrix(1, NbCols);
for (int i = 0; i < NbCols; i++) {
A.data[0, i] = data[row, i];
}
return A;
}
public DMatrix Col(int col) {
DMatrix A = new DMatrix(NbRows, 1);
for (int i = 0; i < NbRows; i++) {
A.data[i, 0] = data[i, col];
}
return A;
}
public DMatrix Diag() {
if (NbRows != NbCols) {
throw new Exception($"Cannot compute diagonal, matrix isn't square:\n\t" +
$"A : {NbRows}x{NbCols}");
}
DMatrix res = new DMatrix(NbRows, NbCols);
for (int i = 0; i < NbRows; i++) {
res.data[i, i] = data[i, i];
}
return res;
}
public DMatrix Map(OneVarFunction func) {
DMatrix res = new DMatrix(NbRows, NbCols);
for (int i = 0; i < res.NbRows; i++) {
for (int j = 0; j < res.NbCols; j++) {
res.data[i, j] = func(data[i, j]);
}
}
return res;
}
public double[,] ToArray() {
double[,] arr = new double[NbRows, NbCols];
for (int i = 0; i < NbRows; i++) {
for (int j = 0; j < NbCols; j++) {
arr[i, j] = data[i, j];
}
}
return arr;
}
public string ToCsv() {
string str = "";
for (int i = 0; i < NbRows; i++) {
for (int j = 0; j < NbCols; j++) {
if (j != NbCols - 1) {
str += $"{data[i, j]},";
}
else {
str += $"{data[i, j]}\n";
}
}
}
return $"{str}\n";
}
public override string ToString() {
string str = "";
for (int i = 0; i < NbRows; i++) {
str += "[ ";
for (int j = 0; j < NbCols; j++) {
string decimals = new string('0', Precision);
string nb = data[i, j].ToString($"+0.{decimals};-0.{decimals};0")
.Replace('+', ' ');
if (j != NbCols - 1) {
str += nb + " ";
}
else {
str += nb + " ]\n";
}
}
}
return str + '\n';
}
}
}
</code></pre>
<p>Utils.cs</p>
<pre><code>using System;
namespace Mathlib.Misc {
public static class Utils {
private static int seed;
private static Random rng;
public static void Seed(int s) {
seed = s;
rng = new Random(s);
}
public static int Seed() {
return seed;
}
static Utils() {
Seed((int) DateTime.Now.Ticks);
rng = new Random(seed);
}
public static double Rand() {
return rng.NextDouble();
}
public static int Rand(int max) {
return (int) (rng.NextDouble() * max);
}
public static float Rand(float max) {
return (float) (rng.NextDouble() * max);
}
public static double Rand(double max) {
return rng.NextDouble() * max;
}
public static int Rand(int min, int max) {
return (int) (rng.NextDouble() * (max - min) + min);
}
public static float Rand(float min, float max) {
return (float) (rng.NextDouble() * (max - min) + min);
}
public static double Rand(double min, double max) {
return rng.NextDouble() * (max - min) + min;
}
public static float Lerp(float val, float x1, float x2, float y1, float y2) {
if (val == x1) {
return y1;
}
if (val == x2) {
return y2;
}
return (y2 - y1) / (x2 - x1) * (val - x1) + y1;
}
public static double Lerp(double val, double x1, double x2, double y1, double y2) {
if (val == x1) {
return y1;
}
if (val == x2) {
return y2;
}
return (y2 - y1) / (x2 - x1) * (val - x1) + y1;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T02:04:16.703",
"Id": "449158",
"Score": "5",
"body": "Welcome to CR, the braces are all wrong! ;-p ..I'd be curious to see what's in this `Utils` static (?) class, feel free to [edit] your post to add more details and context (e.g. expand a bit on the functionality, the *purpose* of the code you present to the reviewers).. don't worry about making a long post, there's no need to be concise on CR (character limit is double that of SO for a reason!) - a small paragraph with a code block for `Mathlib.Misc.Utils` could turn out pretty interesting... alas, only the code that's *in the post* is reviewable ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T02:07:30.617",
"Id": "449159",
"Score": "0",
"body": "Ah, and +1 anyway... buckle up, and keep your head, hands, and feet inside the vehicle - enjoy the ride!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T02:42:21.280",
"Id": "449162",
"Score": "3",
"body": "Thanks for the welcoming... welcome and advice! I've added a bit more information and included the Utils class. Let me know if there's anything more I can/should add. And my braces shall stay where they are!... unless you can convince me to change my mind!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:48:19.283",
"Id": "449215",
"Score": "0",
"body": "Long term, generics!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T13:11:44.690",
"Id": "449220",
"Score": "1",
"body": "@D.BenKnoble you can't do math with generics though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:57:32.787",
"Id": "449279",
"Score": "1",
"body": "@cliesens write for your audience :). C# is going to be read by C# devs. C# devs are used to next-line braces. Conventions make colaboration easier."
}
] |
[
{
"body": "<p>I like that your braces and indentation is beautifully consistent. But, this is C#, and your Java is showing ;-) - Kudos for the mostly-consistent <code>PascalCase</code> type and member names, but it's the K&R same-line <code>{</code> opening brace that clashes with the typical Allman next-line <code>{</code> opening brace standard most people would <em>expect</em> of C# code:</p>\n\n<blockquote>\n<pre><code>public DMatrix(int n)\n{\n if (n < 1)\n {\n throw new Exception($\"Cannot create matrix,\" +\n $\" N should be greater or equal to 1.\\n\\tN = {n}\");\n }\n\n NbRows = NbCols = n;\n Fill(0);\n}\n</code></pre>\n</blockquote>\n\n<p>I would write auto-properties on a single line:</p>\n\n<pre><code>public int NbRows { get; private set; }\n\npublic int NbCols { get; private set; }\n</code></pre>\n\n<p>Or rather, I'd make these <code>get</code>-only:</p>\n\n<pre><code>public int Rows => _rows;\n\npublic int Columns => _columns;\n</code></pre>\n\n<p>..and have the corresponding private fields. Now maybe I'm old-school, but I like that underscore for private fields: it removes the need to qualify private fields with <code>this</code> when you'd like a local variable by that name. But, something feels wrong about needing to store this kind of metadata in private fields... let's keep reading..</p>\n\n<blockquote>\n<pre><code>public static int Precision {\n get;\n set;\n}\n</code></pre>\n</blockquote>\n\n<p>Uh-oh. Assuming it's used elsewhere and not just in the <code>ToString</code> implementation (why then?), it's almost guaranteed you don't want a <code>static</code> modifier here: a <code>static</code> property belongs to the <em>type</em>, not the <em>object/instance</em> - if I have two <code>DMatrix</code> objects and I say <code>matrix1.Precision = 4</code> and then two lines later I say <code>matrix2.Precision = 1</code>, it's perfectly reasonable to expect <code>matrix1.Precision</code> to not start claiming its value is now <code>1</code>... right?</p>\n\n<blockquote>\n<pre><code>public DMatrix(DMatrix A) : this(A.data) { }\n</code></pre>\n</blockquote>\n\n<p>Hm, I was about to write something about <em>constructor chaining</em>.. there's not enough of that:</p>\n\n<pre><code>public DMatrix() : this(1) { }\n\npublic DMatrix(int size) : this(size, size)\n\npublic DMatrix(int width, int height) : this(width, height, default) { }\n\npublic DMatrix(int width, int height, int fillValue) : this(new double[width, height](), fillValue) { }\n\npublic DMatrix(double[,] matrix, int fillValue = default)\n{\n /* one place */\n}\n</code></pre>\n\n<p>I'd make the encapsulated <code>data</code> array <code>readonly</code> (that makes <em>the array reference</em> read-only, not the array elements; the compiler will prevent assigning to the array outside a constructor).</p>\n\n<pre><code> private readonly double[,] _data;\n</code></pre>\n\n<p>And then, the <code>Rows</code> and <code>Cols</code> don't need a setter anymore:</p>\n\n<pre><code>public int Rows { get; }\npublic int Columns { get; }\n</code></pre>\n\n<p>They can only be assigned in a constructor.</p>\n\n<p>Careful with operator overloads - it's not clear how the rather obscure <a href=\"https://stackoverflow.com/a/387429/1188513\">unary one's complement operator</a> turns into an implicit shorthand for <s>applying the <code>~</code> operator to each element</s> ...transposing:</p>\n\n<blockquote>\n<pre><code>public static DMatrix operator ~(DMatrix A) {\n return A.Transpose();\n}\n</code></pre>\n</blockquote>\n\n<p>There's already a <code>Transpose</code> method for that.</p>\n\n<p>I see you <code>throw Exception</code> - avoid that: you want to throw a meaningful exception type, such that you know what the problem is just with the type name. When throwing in a guard clause that's validating the given arguments, you want to throw an <code>ArgumentException</code> for example.</p>\n\n<blockquote>\n<pre><code>if (NbCols != NbRows) {\n throw new Exception($\"Cannot compute trace, matrix is not square:\\n\\t\" +\n $\"A : {NbRows}x{NbCols}\");\n}\n</code></pre>\n</blockquote>\n\n<p>This particular condition should be handled in the constructor IMO (where <code>NbCols/Columns</code> and <code>NbRows/Rows</code> are assigned), and then here a <code>System.Diagnostics.Debug.Assert</code> call should suffice to cover this rather unlikely scenario - it's the job of the constructor(s) to ensure the object is in a valid state.</p>\n\n<p>This one however:</p>\n\n<blockquote>\n<pre><code>if (m < 1) {\n throw new Exception($\"Cannot create matrix,\" +\n $\" M should be greater or equal to 1.\\n\\tM = {m}\");\n}\n</code></pre>\n</blockquote>\n\n<p>...worries me. If <code>NbRows = NbCols = n</code>, and then <code>data = new double[m, n];</code>, it means our parameterization is 1-based, but the matrix itself is 0-based... so we ask for 1x1 and actually get a 2x2 where <code>[0,0]</code> is shoved under the proverbial carpet! </p>\n\n<p>A note here:</p>\n\n<blockquote>\n<pre><code>public double Det_recursive() {\n</code></pre>\n</blockquote>\n\n<p>The common guidelines would scream for <code>PascalCase</code> here, and I would suggest that the recursive nature of the implementation is ..an implementation detail, and so I would have gone with <code>Determinant</code> for a name.</p>\n\n<p>I like how you antagonized <code>+</code> and <code>-</code> operators, and I know you really like the K&R braces, but this:</p>\n\n<blockquote>\n<pre><code>public static DMatrix operator -(DMatrix A, double x) {\n return A + (-x);\n}\n</code></pre>\n</blockquote>\n\n<p>could be:</p>\n\n<pre><code>public static DMatrix operator -(DMatrix A, double x) => A + (-x);\n</code></pre>\n\n<p>Look ma, no <s>hands</s> braces!</p>\n\n<hr>\n\n<p>There's definitely other things to say, notably about <code>Utils</code>, its name and <code>static</code> nature, and how this impacts coupling, and how this coupling impacts testability... but I'll let other reviewers cover other aspects of this code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:01:37.950",
"Id": "449228",
"Score": "0",
"body": "Thank you very much! A quick note about your note on the ```Det_recursive``` and ```Norm_frobenius``` methods; I intend to add more methods for calculation norms and determinants, and I like having them all listed as, for example, ```Norm_aaa```, ```Norm_bbb```, ```Norm_ccc```,... I know I _shouldn't_ name them that way, but it's so tempting! That's why the strange and seemingly out of place ```Det_recursive`` is there. And that last line with the lambda and the method definition, I had no idea I could do that! Thanks again {\n}"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:58:23.973",
"Id": "449239",
"Score": "4",
"body": "@cliesens consider extracting an interface and implementing a strategy pattern then - `INormCalculator` can be implemented by `FrobeniusNormCalculator`, `AaaNormCalculator`, `BbbNormCalculator`, and each can have its own distinct `Calculate` method implementation, and you can test them independently, and inject the calculator as a dependency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:23:37.953",
"Id": "449252",
"Score": "1",
"body": "For what it’s worth my background is .NET. Yet C# is objectively wrong about the bracing style. It wastes tons of vertical space, thus drastically decreasing readability due to reduced context, for no demonstrated trade-off — these are all facts, not opinions. This is (one of the many) hills I’m willing to die on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:59:20.160",
"Id": "449292",
"Score": "5",
"body": "@KonradRudolph I'm not going to engage in holy wars! Wrong or not, it's the standard, and it had to be said in an answer =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T12:43:14.440",
"Id": "449363",
"Score": "0",
"body": "@MathieuGuindon “Holy war” implies subjectiveness and my entire point is that there’s nothing subjective about what I’ve said. I’ve pointed out *facts*, corroborated by usability evidence, which is why it’s so maddening that the prevailing .NET style just ignores this. You can certainly point out the prevailing style, but advocating for it in the face of opposing evidence is simply bad advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T14:59:46.447",
"Id": "449374",
"Score": "2",
"body": "@KonradRudolph If you ever see me writing and advocating K&R braces in C#, my account would have been hijacked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T08:24:59.650",
"Id": "449462",
"Score": "1",
"body": "@KonradRudolph - \"these are all facts, not opinions\" - care to link to some papers (specifically, that show that wasting vertical space is generally undesirable and that the reduction in context is important/relevant)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T08:52:26.567",
"Id": "449471",
"Score": "2",
"body": "@KonradRudolph I use both bracing styles on a daily basis. Allman on C#, K&R on Typescript. I see no discernible differences in readability either way. I find consistency within the code base much more important. So apparently, your \"facts\" are not my \"facts\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T13:05:26.657",
"Id": "449485",
"Score": "1",
"body": "@FilipMilovanović Sure. Gorla, Benander & Benander (1990) shows that too many blank lines (> 16% SLOC) decrease debuggability (~ readability); this is also a generally known fact in typography. Allman style may put this over the limit but this wasn’t specifically tested. There’s also Hansen & Yim (1989), which specifically tested bracing style. However, I misremembered the result: although K&R style was judged easier to understand twice as frequently as Allman style, the study shows no significant difference between the two, potentially because it was underpowered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:16:33.800",
"Id": "449511",
"Score": "0",
"body": "@KonradRudolph Just went through Gorla et al. (1990). Sure, their results suggest that too many blank lines impact debuggability, but they also suggest the same for too few; according to the study, there's a sweet spot percentage (the language used was COBOL: 8-16% for procedure division, 14-20% for data division). They also remark that it was a controlled experiment that \"cannot necessarily be generalized to large programming projects common in industry.\" In any case, not sure if using one or the other bracing style moves you out of that sweet spot, whatever that might be for C#."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:19:59.090",
"Id": "449514",
"Score": "0",
"body": "@FilipMilovanović that does explain how I see K&R braces as turning code into compact blocks wanting some breathing space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:44:12.160",
"Id": "449516",
"Score": "1",
"body": "Really, this style of braces is a non-issue. Pick what you want / what your project uses / what your superior wants and stick with it. Having endless discussions about which one is better and more efficient is pointless. That study proves nothing. Good answer though, concise review."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T03:48:50.187",
"Id": "230517",
"ParentId": "230515",
"Score": "18"
}
},
{
"body": "<p><strong>A bug:</strong> <code>Transpose</code> does <code>data[i, j] = data[j, i];</code>, but it returns a new matrix, it's not supposed to change the matrix in-place, and that doesn't actually work (going out of range for a non-square matrix and losing data for a square one).</p>\n\n<p><strong>Manual loops to copy between arrays:</strong> did you know you can use <code>Array.Copy</code> on multi-dimensional arrays? The indexes work as if the rows are laid end-to-end.</p>\n\n<p><strong><code>Det_recursive</code>:</strong> cofactor expansion is a well known example of an algorithm with O(n!) time complexity. It's fine for a tiny matrix yes, but a factorial quickly gets out of hand. Naming it <code>Determinant</code> is more dangrous if you leave it like this, offering no warning that it's going to be done with the slow algorithm, but fixing the efficiency is much nicer than putting a warning in the name. It can be done in O(n³) time via LU decomposition, which is something that's also useful for various other purposes.</p>\n\n<p><strong>Unnecessary zero filling:</strong> the constructors and the <code>Id</code> function wastes a bunch of time and code writing zeroes into a new array full of zeroes. <code>Id</code> can be simplified by just writing the ones to the diagonal, and the constructor without fill parameter could simply not fill.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:35:24.080",
"Id": "449198",
"Score": "0",
"body": "Or just not fill if the fill value is the default, and keep everything in the ctor with the most parameters? Great review btw!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:16:33.333",
"Id": "449233",
"Score": "0",
"body": "I didn't know about ```Array.Copy```, thanks! And, as I've said in another comment, the reason I named ```Det_recursive``` this way is because I intend to implement other algorithms (because why not?) for determinant calculation. I am aware that the name is ugly and I should probably change it, but I like having all my determinant methods named the same way, e.g. ```Det_someAlgorithm```, ```Det_someOtherAlgorithm```, ..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T08:01:58.043",
"Id": "230526",
"ParentId": "230515",
"Score": "11"
}
},
{
"body": "<p><strong>New line character</strong> <a href=\"https://stackoverflow.com/a/1761086/3668251\">differs depending on system</a>. Can't rely on <code>\\n</code>. Let me introduce you to your new friend, <a href=\"https://docs.microsoft.com/es-es/dotnet/api/system.environment.newline?view=netframework-4.8\" rel=\"nofollow noreferrer\">Environment.NewLine</a></p>\n\n<p><strong>Concatenating strings in a loop</strong> is very inefficient. It's recommended to use <a href=\"https://docs.microsoft.com/es-es/dotnet/api/system.text.stringbuilder?view=netframework-4.8\" rel=\"nofollow noreferrer\">StringBuilder</a> instead</p>\n\n<p><strong>Code reuse.</strong> There are a couple of spots where duplicated code can be extracted away.</p>\n\n<ul>\n<li>Iterating an array and setting values. This can be extracted into a method than accepts a function <code>(T currentValue, int x, int y) -> T newValue</code> and sets each cell to the value returned by the function. Please see <code>SetValues</code> and its usages in the code below.</li>\n<li>Creating a new matrix. This has been abstracted into several methods in my code (<code>Clone()</code>, <code>CreateNewMatrixWithSameSize()</code> and <code>CreateNewMatrix()</code>). </li>\n</ul>\n\n<p><strong>Generics.</strong> You mention that you want to later implement matrixes for different kind of numbers. A good idea would be to use a generic abstract class <code>Matrix<T></code>. I've done some of the work in the code below, but let me summarize some of the changes I needed to make:</p>\n\n<ul>\n<li>Change all mentions of <code>double</code> to <code>T</code></li>\n<li>Extract all code that operates with doubles or instantiates matrixes to it's own abstract methods.</li>\n<li>Create <code>DoubleMatrix</code> class inheriting from <code>Matrix<T></code> and implement the abstract methods we created in the previous step.</li>\n<li><p>Move other type specific logic (Like <code>Rand()</code> and <code>Id()</code>) to <code>DoubleMatrix</code> class</p>\n\n<p>Matrix.cs</p></li>\n</ul>\n\n<pre><code>public abstract class Matrix<T>\n{\n protected Matrix(int n) : this(n, n)\n {\n }\n\n protected Matrix(int m, int n) : this(m, n, default(T))\n {\n }\n\n protected Matrix(int m, int n, T x)\n {\n if (m < 1)\n {\n throw new Exception($\"Cannot create matrix,\" +\n $\" M should be greater or equal to 1.\\n\\tM = {m}\");\n }\n\n if (n < 1)\n {\n throw new Exception($\"Cannot create matrix,\" +\n $\" N should be greater or equal to 1.\\n\\tN = {n}\");\n }\n\n NbRows = m;\n NbCols = n;\n\n data = new T[m, n];\n Fill(x);\n }\n\n protected Matrix(Matrix<T> A) : this(A.data)\n {\n }\n\n protected Matrix(T[,] source)\n {\n NbRows = source.GetLength(0);\n NbCols = source.GetLength(1);\n\n this.data = new T[NbRows, NbCols];\n\n this.SetValues((i, j) => source[i, j]);\n }\n\n private readonly T[,] data;\n\n public int NbRows { get; }\n public int NbCols { get; }\n\n public T this[int i, int j]\n {\n get => data[i, j];\n private set => data[i, j] = value;\n }\n\n public static Matrix<T> operator -(Matrix<T> a) => a.Negative();\n public static Matrix<T> operator ~(Matrix<T> a) => a.Transpose();\n public static Matrix<T> operator +(Matrix<T> a, Matrix<T> B) => a.Add(B);\n public static Matrix<T> operator -(Matrix<T> a, Matrix<T> B) => a + (-B);\n public static Matrix<T> operator *(Matrix<T> a, Matrix<T> B) => a.Multiply(B);\n public static Matrix<T> operator +(Matrix<T> a, T x) => a.Add(x);\n public static Matrix<T> operator -(Matrix<T> a, T x) => a.Subtract(x);\n public static Matrix<T> operator *(Matrix<T> a, T x) => a.MultiplyBy(x);\n\n public void Fill(T x) => SetValues(x);\n\n public void SwapRows(int row1, int row2)\n {\n for (int i = 0; i < NbCols; i++)\n {\n T temp = this[row1, i];\n this[row1, i] = this[row2, i];\n this[row2, i] = temp;\n }\n }\n\n public Matrix<T> HadamardProduct(Matrix<T> A)\n {\n if (NbCols != A.NbCols || NbRows != A.NbRows)\n {\n throw new Exception($\"Cannot compute Hadamard product,\" +\n $\" dimensions do not match:\\n\\tA : {NbRows}x{NbCols}\\n\\t\" +\n $\"B : {A.NbRows}x{A.NbCols}\");\n }\n\n return CreateSameSizeMatrix()\n .SetValues((i, j) => Multiply(this[i, j], A[i, j]));\n }\n\n public T Trace()\n {\n if (NbCols != NbRows)\n {\n throw new Exception($\"Cannot compute trace, matrix is not square:\\n\\t\" +\n $\"A : {NbRows}x{NbCols}\");\n }\n\n T res = default(T);\n\n for (int i = 0; i < NbRows; i++)\n {\n res = Add(res, this[i, i]);\n }\n\n return res;\n }\n\n public T Determinant()\n {\n if (NbCols != NbRows)\n {\n throw new Exception($\"Cannot compute determinant, matrix isn't square:\\n\\t\" +\n $\"A : {NbRows}x{NbCols}\");\n }\n\n T sum = default(T);\n\n if (NbRows == 1)\n {\n return this[0, 0];\n }\n else if (NbRows == 2)\n {\n T member1 = Multiply(this[0, 0], this[1, 1]);\n T member2 = Multiply(this[0, 1], this[1, 0]);\n\n return Subtract(member1, member2);\n }\n\n for (int N = 0; N < NbRows; N++)\n {\n Matrix<T> minor = CreateMatrix(NbRows - 1, NbRows - 1);\n\n for (int i = 0; i < NbRows - 1; i++)\n {\n for (int j = 0; j < NbRows; j++)\n {\n if (j < N)\n {\n minor[i, j] = this[i + 1, j];\n }\n else if (j > N)\n {\n minor[i, j - 1] = this[i + 1, j];\n }\n }\n }\n\n T quotient = (N % 2 == 0) ? this[0, N] : Negative(this[0, N]);\n T product = Multiply(minor.Determinant(), quotient);\n sum = Add(sum, product);\n }\n\n return sum;\n }\n\n public T Norm_frobenius()\n {\n T res = default(T);\n\n if (NbRows == 1 || NbCols == 1)\n {\n for (int i = 0; i < NbRows; i++)\n {\n for (int j = 0; j < NbCols; j++)\n {\n T product = Multiply(this[i, j], this[i, j]);\n res = Add(res, product);\n }\n }\n }\n else\n {\n res = (~this * this).Trace();\n }\n\n return Sqrt(res);\n }\n\n public Matrix<T> Transpose() => Clone().SetValues((_, i, j) => this[j, i]);\n\n public Matrix<T> Row(int row)\n {\n Matrix<T> A = CreateMatrix(1, NbCols);\n\n for (int i = 0; i < NbCols; i++)\n {\n A[0, i] = this[row, i];\n }\n\n return A;\n }\n\n public Matrix<T> Column(int col)\n {\n Matrix<T> A = CreateMatrix(NbRows, 1);\n\n for (int i = 0; i < NbRows; i++)\n {\n A[i, 0] = data[i, col];\n }\n\n return A;\n }\n\n public Matrix<T> Diagonal()\n {\n if (NbRows != NbCols)\n {\n throw new Exception($\"Cannot compute diagonal, matrix isn't square:\\n\\t\" +\n $\"A : {NbRows}x{NbCols}\");\n }\n\n Matrix<T> res = CreateMatrix(NbRows, NbCols);\n\n for (int i = 0; i < NbRows; i++)\n {\n res[i, i] = this[i, i];\n }\n\n return res;\n }\n\n public Matrix<T> Map(Func<T, T> func) =>\n CreateMatrix(NbRows, NbCols)\n .SetValues(func);\n\n public T[,] ToArray()\n {\n T[,] arr = new T[NbRows, NbCols];\n\n for (int i = 0; i < NbRows; i++)\n {\n for (int j = 0; j < NbCols; j++)\n {\n arr[i, j] = this[i, j];\n }\n }\n\n return arr;\n }\n\n public string ToCsv()\n {\n var sb = new StringBuilder();\n\n for (int i = 0; i < NbRows; i++)\n {\n for (int j = 0; j < NbCols; j++)\n {\n if (j != NbCols - 1)\n {\n sb.Append($\"{this[i, j]},\");\n }\n else\n {\n sb.Append($\"{this[i, j]}{Environment.NewLine}\");\n }\n }\n }\n\n return sb.ToString();\n }\n\n public override string ToString()\n {\n var sb = new StringBuilder();\n\n for (int i = 0; i < NbRows; i++)\n {\n sb.Append(\"[ \");\n for (int j = 0; j < NbCols; j++)\n {\n\n string nb = AsString(this[i, j]);\n\n if (j != NbCols - 1)\n {\n sb.Append($\"{nb} \");\n }\n else\n {\n sb.Append($\"{nb} ]{Environment.NewLine}\");\n }\n }\n }\n\n return sb.ToString();\n }\n\n protected abstract Matrix<T> Clone();\n protected abstract Matrix<T> CreateMatrix(int m, int n);\n private Matrix<T> CreateSameSizeMatrix() => CreateMatrix(NbRows, NbCols);\n protected abstract T Negative(T x);\n protected abstract T Add(T x, T y);\n protected abstract T Multiply(T x, T y);\n protected abstract T Sqrt(T x);\n protected virtual string AsString(T x) => x.ToString();\n private T Subtract(T x, T y) => Add(x, Negative(y));\n\n private Matrix<T> Multiply(Matrix<T> B)\n {\n if (NbCols != B.NbRows)\n {\n throw new Exception($\"Cannot compute product, matrix dimensions do not match:\\n\\t\" +\n $\"A : {NbRows}x{NbCols}\\n\\tB : {B.NbRows}x{B.NbCols}\");\n }\n\n Matrix<T> res = CreateMatrix(NbRows, B.NbCols);\n\n res.SetValues((current, i, j) =>\n {\n var sum = default(T);\n for (int k = 0; k < NbCols; k++)\n {\n sum = Add(sum, Multiply(this[i, k], B[k, j]));\n }\n\n return sum;\n });\n\n return res;\n }\n\n private Matrix<T> Negative() => Clone().SetValues(Negative);\n\n private Matrix<T> Add(Matrix<T> B)\n {\n if (NbRows != B.NbRows || NbCols != B.NbCols)\n {\n throw new Exception($\"Cannot compute sum, matrix dimensions do not match:\\n\\t\" +\n $\"A : {NbRows}x{NbCols}\\n\\tB : {B.NbRows}x{B.NbCols}\");\n }\n\n return Clone()\n .SetValues((current, i, j) => Add(current, B[i, j]));\n }\n\n private Matrix<T> Add(T x) =>\n CreateSameSizeMatrix()\n .SetValues((i, j) => Add(this[i, j], x));\n\n private Matrix<T> Subtract(T x) => Add(Negative(x));\n\n private Matrix<T> MultiplyBy(T x) =>\n CreateSameSizeMatrix()\n .SetValues((i, j) => Multiply(this[i, j], x));\n\n protected Matrix<T> SetValues(Func<T, int, int, T> newValueSelector)\n {\n for (int i = 0; i < NbRows; i++)\n {\n for (int j = 0; j < NbCols; j++)\n {\n this[i, j] = newValueSelector(this[i, j], i, j);\n }\n }\n\n return this;\n }\n\n protected Matrix<T> SetValues(T newValue) =>\n SetValues((_, __, ___) => newValue);\n\n protected Matrix<T> SetValues(Func<T, T> newValueSelector) =>\n SetValues((current, _, __) => newValueSelector(current));\n\n protected Matrix<T> SetValues(Func<int, int, T> newValueSelector) =>\n SetValues((_, i, j) => newValueSelector(i, j));\n}\n</code></pre>\n\n<p>DoubleMatrix.cs</p>\n\n<pre><code>public class DoubleMatrix : Matrix<double>\n{\n public DoubleMatrix(int n) : base(n) {}\n public DoubleMatrix(int m, int n) : base(m, n) {}\n public DoubleMatrix(int m, int n, double x) : base(m, n, x) {}\n public DoubleMatrix(double[,] source) : base(source) {}\n public DoubleMatrix(Matrix<double> A) : base(A) {}\n\n public static DoubleMatrix Identity(int n) => \n (DoubleMatrix) new DoubleMatrix(n).SetValues((i, j) => i == j ? 1 : 0);\n\n protected override Matrix<double> Clone() => new DoubleMatrix(this);\n protected override Matrix<double> CreateMatrix(int m, int n) => new DoubleMatrix(m, n);\n protected override double Negative(double x) => -x;\n protected override double Add(double x, double y) => x + y;\n protected override double Multiply(double x, double y) => x * y;\n protected override double Sqrt(double x) => Math.Sqrt(x);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:33:46.570",
"Id": "230551",
"ParentId": "230515",
"Score": "7"
}
},
{
"body": "<h1>Next step: Make it <code>Expression<></code>-oriented.</h1>\n\n<p>Making your own math tools is tons of fun and practical! </p>\n\n<p>Since you're asking about potential improvements, my suggestion is to move toward <code>Expression<></code>-oriented coding next.</p>\n\n<p>First, you define:</p>\n\n<pre><code>public abstract partial class Expression<T>\n{\n public T Evaluate()\n {\n return this.Internal_Evaluate();\n }\n protected abstract T Internal_Evaluate();\n}\n</code></pre>\n\n<p>You can ignore the <code>.Evaluate()</code>/<code>.Internal_Evaluate()</code> distinction for now, though I'd suggest that you include it as it may make your life easier later.</p>\n\n<p>Anyway, then you can define stuff like constants</p>\n\n<pre><code>public partial class ConstantExpression<T>\n : Expression<T>\n{\n protected T ConstantValue { get; private set; }\n\n // Empty constructor that no external code should ever use:\n protected ConstantExpression() { }\n\n // Primary factory-style constructor.\n // If you add overloads, try to make them call this one,\n // such that this is the only method that ever includes\n // \"new ConstantExpression<>()\" anywhere in your code.\n public static ConstantExpression<T> New(\n T constantValue\n )\n {\n var toReturn = new ConstantExpression<T>();\n\n toReturn.ConstantValue = constantValue;\n\n System.Threading.Thread.MemmoryBarrier(); // Just always include this until you have a reason not to.\n\n return toReturn;\n }\n\n protected override T Internal_Evaluate()\n {\n return this.ConstantValue;\n }\n}\n</code></pre>\n\n<p>and addition</p>\n\n<pre><code>public partial class AdditionExpression\n : Expression<double>\n{\n protected Expression<double> Argument0Expression { get; private set; }\n protected Expression<double> Argument1Expression { get; private set; }\n\n // Empty constructor that no external code should ever use:\n protected AdditionExpression() { }\n\n // Primary factory-style constructor.\n // If you add overloads, try to make them call this one,\n // such that this is the only method that ever includes\n // \"new AdditionExpression()\" anywhere in your code.\n public static AdditionExpression New(\n Expression<double> argument0Expression\n , Expression<double> argument1Expression\n )\n {\n if (argument0Expression == null || argument1Expression == null)\n {\n throw new Exception(); // replace with your preferred debug-tracing style\n }\n\n var toReturn = new AdditionExpression();\n\n toReturn.Argument0Expression = argument0Expression;\n toReturn.Argument1Expression = argument1Expression;\n\n System.Threading.Thread.MemmoryBarrier(); // Just always include this until you have a reason not to.\n\n return toReturn;\n }\n\n protected override double Internal_Evaluate()\n {\n var argument0 = this.Argument0Expression.Evaluate();\n var argument1 = this.Argument1Expression.Evaluate();\n\n return argument0 + argument1;\n }\n}\n</code></pre>\n\n<p>with usability helpers like</p>\n\n<pre><code>partial class Expression<T>\n{\n public static implicit operator Expression<T>(\n T constantValue\n )\n {\n return ConstantExpression<T>.New(constantValue);\n }\n\n public static Expression<double> operator +(\n Expression<double> addend0Expression\n , Expression<double> addend1Expression\n )\n {\n return AdditionExpression.New(\n addend0Expression\n , addend1Expression\n );\n }\n}\n</code></pre>\n\n<p>Then now that you've got the basic outline for <code>Expression<></code>'s, you can rewrite your matrix code:</p>\n\n<pre><code>public partial class MatrixExpression\n : Expression<double[,]>\n{\n protected Expression<double>[,] MatrixElementsExpressions { get; private set; }\n\n protected MatrixExpression() { }\n public static MatrixExpression New(\n Expression<double[,]> matrixElementsExpressions\n )\n {\n var toReturn = new MatrixExpression();\n\n toReturn.MatrixElementsExpressions = matrixElementsExpressions;\n\n System.Threading.Thread.MemoryBarrier();\n\n return toReturn;\n }\n\n protected override double[,] Internal_Evaluate()\n {\n var matrixElementsExpressions = this.MatrixElementsExpressions;\n\n var length_0 = matrixElementsExpressions.GetLength(0);\n var length_1 = matrixElementsExpressions.GetLength(1);\n\n var toReturn = new double[length_0, length_1];\n\n for (long i_0 = 0; i_0 < length_0; ++i_0)\n {\n for (long i_1 = 0; i_1 < length_1; ++i_1)\n {\n toReturn[i_0, i_1] = matrixElementsExpressions[i_0, i_1].Evaluate();\n }\n }\n\n return toReturn;\n }\n}\n</code></pre>\n\n<p>Then, it might be tempting to add, say, a <code>.Transpose()</code> method to <code>MatrixExpresion</code> – but <strong><em>don't</em>!</strong></p>\n\n<p>Instead:</p>\n\n<pre><code>public static Expression<double[,]> Transpose(\n this Expression<double[,]> matrixExpression\n )\n{\n if (matrixExpression == null)\n {\n throw new Exception(); // Replace with your preferred error-handling system.\n }\n\n var toReturn = TransposedMatrixExpression.New(\n matrixExpression\n );\n\n return toReturn;\n}\n\npublic partial class TransposedMatrixExpression\n : Expression<double[,]>\n{\n protected Expression<double[,]> MatrixExpression { get; private set; }\n\n protected TransposedMatrixExpression() { }\n public static TransposedMatrixExpression New(\n Expression<double[,]> matrixExpression\n )\n {\n var toReturn = new TransposedMatrixExpression();\n\n toReturn.MatrixExpression = matrixExpression;\n\n System.Threading.Thread.MemoryBarrier();\n\n return toReturn;\n }\n\n protected override double[,] Internal_Evaluate()\n {\n var matrixExpression = this.MatrixExpression;\n\n var matrix = matrixExpression.Evaluate();\n\n var length_0 = matrix.GetLength(0);\n var length_1 = matrix.GetLength(1);\n\n var toReturn = new double[length_1, length_0];\n\n for (long i_0 = 0; i_0 < length_0; ++i_0)\n {\n for (long i_1 = 0; i_1 < length_1; ++i_1)\n {\n toReturn[i_1, i_0] = matrix[i_0, i_1];\n }\n }\n\n return toReturn;\n }\n}\n</code></pre>\n\n<p>In general, keep <code>Expression<></code>-definitions slim. New operations shouldn't be additional methods within other classes, but rather each get its own <code>Expression<></code>, e.g. as we effectively added a <code>.Transpose()</code> method via the <code>class TransposedMatrixExpression</code> above.</p>\n\n<blockquote>\n <h3>Note: Classes and methods are the same thing.</h3>\n \n <p><em>This may be confusing, so I'm quote-boxing it out: you can ignore this point if it doesn't make sense.</em></p>\n \n <p>C# methods and C# classes are logically equivalent, if we ignore some variation in presentation and implied implementation details. To better understand this, you might look into how anonymous C# methods get their own C# class in the runtime.</p>\n \n <p>Once you understand their equivalence, it'll help frame why we define methods as classes, e.g. as with <code>.Transpose()</code> above.</p>\n</blockquote>\n\n<hr>\n\n<h3>Tips</h3>\n\n<ol>\n<li><p>Put operator definitions, e.g. <code>+</code>, into a <code>partial class Expression<>{ }</code> block, as we did for <code>+(Expression<double>, Expression<double>)</code> above.</p></li>\n<li><p>My coding style may look verbose. I've left a lot of room for things that I suspect most people will want to add as they develop a project like this. I'd advise against trying to make it shorter for a long time, until you get several steps beyond this.</p></li>\n<li><p>It may feel weird to have <code>ConstantExpression<T></code>'s getting trivially <code>.Evaluate()</code>'d to the <code>T .ConstantValue</code> that they wrap. You may feel inclined to try to reduce overhead by, for example, defining a variant of <code>AdditionExpression</code> that works on a <code>T</code> and an <code>Expression<T></code>, rather than two <code>Expression<T></code>'s, to help reduce unnecessary method calls. If you feel strongly about trying this, then it can be a good learning experience – but, it's a mistake.</p></li>\n</ol>\n\n<hr>\n\n<h3>Next steps.</h3>\n\n<p>Obviously, there's a lot to play with here. That's a lot of fun!</p>\n\n<p>Then you can also do stuff like:</p>\n\n<ol>\n<li><p>Creating graphical interfaces for <code>Expression<></code>'s.</p>\n\n<ul>\n<li>I originally did this with WPF. I'd suggest coding it purely in C#; ignore the XML interface.</li>\n</ul></li>\n<li><p>Add in symbolic logic.</p></li>\n<li><p>Extend the logic beyond math into general programming structures.</p></li>\n<li><p>Add in calculus, differential equations, etc..</p></li>\n<li><p>Hoist the whole thing onto a custom evaluation engine.</p>\n\n<ul>\n<li>At first, stick with just having an <code>Expression<></code>-tree doing depth-first <code>.Evaluate()</code>-ing, as above.</li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T09:41:31.013",
"Id": "449351",
"Score": "1",
"body": "Just a head's up: I tapped this out quickly on mobile, so the code might have some bugs. But it should give the gist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T12:22:40.663",
"Id": "449359",
"Score": "3",
"body": "Care to explain the _MemoryBarrier_ usage?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T12:29:57.750",
"Id": "449361",
"Score": "1",
"body": "@dfhwze It ensures that the fields are set before another thread might try to access them. Excluding them can create weird race conditions that're really hard to reproduce/debug. I've come to see the inclusion of the `.MemoryBarrier()`'s to be a standard coding practice, with their exclusion being a microopitmization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T04:25:24.907",
"Id": "449543",
"Score": "1",
"body": "Tried typing an edit on mobile, but that kinda backfired. **_tl;dr_-** For randoms, you should make a `RandomDoubleExpression : Expression<double>` that creates a \\$\\texttt{double} \\in \\left[0, 1\\right) ,\\$ then use it as the only source of randomness for all `Expression<>`'s. For example, don't make a variant that generates \\$\\texttt{double}\\text{'s} \\in \\left[x_\\text{min}, x_\\text{max}\\right) ,\\$ nor an `Expression<double[,]>` that creates a randomized-`double[,]`, but instead construct those things more systematically."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T09:40:31.920",
"Id": "230590",
"ParentId": "230515",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230517",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T00:57:00.083",
"Id": "230515",
"Score": "20",
"Tags": [
"c#",
"beginner",
".net",
"matrix"
],
"Title": "Matrix class in C#"
}
|
230515
|
<p>I did this coding exercise for a potential employer who failed it on the basis of unspecified style and structure issues and would appreciate any thoughts on what flaws this contains, in particular in relation to style, structure or any other important software design principles.</p>
<p>Program.cs</p>
<pre><code>namespace ToyRobotSimulator
{
using System;
public static class Program
{
//Reads console input and executes command
public static void Main()
{
bool run = true;
var handler = new CommandHandler(new Robot());
while (run)
{
try
{
handler.HandleCommand(Helpers.GetArrayFromSplitInput(Console.ReadLine()));
}
catch (Exception e)
{
Console.WriteLine("Invalid Input: " + e.Message);
}
}
}
}
}
</code></pre>
<p>CommandHandler.cs</p>
<pre><code>namespace ToyRobotSimulator
{
using System;
public class CommandHandler : ICommandHandler
{
private IRobot _rob;
private bool _placeHasBeenExecuted = false;
public CommandHandler(IRobot rob)
{
_rob = rob;
}
//Handles command. Requires valid placement to occur before executing any other command
public bool HandleCommand(string[] command)
{
if (command == null) { throw new ArgumentNullException("command is null"); }
switch (command[0])
{
case DataConstants.PlaceName:
var placed = command.Length == 4 && _rob.Place(new PlacementRequest
{
X = Helpers.GetNumberFromString(command[1]),
Y = Helpers.GetNumberFromString(command[2]),
F = Helpers.GetDirectionFromString(command[3])
});
Helpers.RunCommandIfTrue(() => _placeHasBeenExecuted = placed, _placeHasBeenExecuted == false);
break;
case DataConstants.MoveName:
Helpers.RunCommandIfTrue(() => _rob.Move(), _placeHasBeenExecuted);
break;
case DataConstants.LeftName:
Helpers.RunCommandIfTrue(() => _rob.Left(), _placeHasBeenExecuted);
break;
case DataConstants.RightName:
Helpers.RunCommandIfTrue(() => _rob.Right(), _placeHasBeenExecuted);
break;
case DataConstants.ReportName:
Helpers.RunCommandIfTrue(() => _rob.Report(), _placeHasBeenExecuted);
break;
default:
break;
}
return _placeHasBeenExecuted;
}
}
}
</code></pre>
<p>Robot.cs</p>
<pre><code>namespace ToyRobotSimulator
{
using System;
public class Robot : IRobot
{
private int? _x;
private int? _y;
private Direction? _f;
//Sets _x, _y and _f values if request contains valid data and returns a bool to indicate success or failure
public bool Place(PlacementRequest req)
{
var placed = false;
if (req != null && Helpers.IsValidPlacement(req.X) && Helpers.IsValidPlacement(req.Y) && req.F != null)
{
_x = req.X;
_y = req.Y;
_f = req.F;
placed = true;
}
return placed;
}
//Moves robot one unit in direction faced
public void Move()
{
switch (_f)
{
case Direction.NORTH:
Helpers.RunCommandIfTrue(() => _y++, Helpers.IsValidPlacement(_y + 1));
break;
case Direction.SOUTH:
Helpers.RunCommandIfTrue(() => _y--, Helpers.IsValidPlacement(_y - 1));
break;
case Direction.EAST:
Helpers.RunCommandIfTrue(() => _x++, Helpers.IsValidPlacement(_x + 1));
break;
case Direction.WEST:
Helpers.RunCommandIfTrue(() => _x--, Helpers.IsValidPlacement(_x - 1));
break;
default:
break;
}
}
//Calls turn with direction as increment of _f
public void Left()
{
Turn(() => (int)_f + 1);
}
//Calls turn with direction as decrement of _f
public void Right()
{
Turn(() => (int)_f - 1);
}
//If value less than zero default, otherwise calculate direction based on modulo
private void Turn(Func<int> newDirection)
{
_f = (newDirection() < 0) ? Direction.EAST : (Direction)(newDirection() % 4);
}
//Outputs comma-separated string with _x,_y and _f values
public void Report()
{
Console.WriteLine($"Output: {_x},{_y},{_f}");
}
}
}
</code></pre>
<p>Helpers.cs</p>
<pre><code>
namespace ToyRobotSimulator
{
using System;
public static class Helpers
{
public static int? GetNumberFromString(string input)
{
int? result = null;
int res;
var success = int.TryParse(input, out res);
return success ? res : result;
}
public static Direction GetDirectionFromString(string input)
{
Object direction;
Enum.TryParse(typeof(Direction), input, out direction);
return (Direction)direction;
}
public static bool IsValidPlacement(int? a)
{
var startIndex = 0;
var endIndex = 4;
return a >= startIndex && a <= endIndex;
}
public static string[] GetArrayFromSplitInput(string input)
{
return input?.Split(new string[] { " ", "," }, StringSplitOptions.None);
}
public static void RunCommandIfTrue(Action action, bool condition)
{
if (condition && action != null)
{
action.Invoke();
}
}
}
}
</code></pre>
<p>Adding the repo for the full project for context, but most of the logic is in the code above: <a href="https://github.com/dennis87532/ToyRobotSimulator" rel="noreferrer">https://github.com/dennis87532/ToyRobotSimulator</a>.</p>
<p>Edit: These are the requirements for the app:</p>
<pre>
Description
• The application is a simulation of a toy robot moving on a square tabletop, of dimensions 5 units x 5 units.
• There are no other obstructions on the table surface.
• The robot is free to roam around the surface of the table, but must be prevented from falling to destruction. Any movement that would result in the robot falling from the table must be prevented, however further valid movement commands must still be allowed.
Create an application that can read in commands of the following form:
PLACE X,Y,F
MOVE
LEFT
RIGHT
REPORT
• PLACE will put the toy robot on the table in position X,Y and facing NORTH, SOUTH, EAST or WEST.
• The origin (0,0) can be considered to be the SOUTH WEST most corner.
• The first valid command to the robot is a PLACE command, after that, any sequence of commands may be issued, in any order, including another PLACE command. The application should discard all commands in the sequence until a valid PLACE command has been executed.
• MOVE will move the toy robot one unit forward in the direction it is currently facing.
• LEFT and RIGHT will rotate the robot 90 degrees in the specified direction without changing the position of the robot.
• REPORT will announce the X,Y and F of the robot. This can be in any form, but standard output is sufficient.
• A robot that is not on the table can choose the ignore the MOVE, LEFT, RIGHT and REPORT commands.
• Input can be from a file, or from standard input, as the developer chooses.
• Provide test data to exercise the application.
Constraints
• The toy robot must not fall off the table during movement. This also includes the initial placement of the toy robot.
• Any move that would cause the robot to fall must be ignored.
</pre>
|
[] |
[
{
"body": "<p><strong>Your commenting style needs improvement</strong></p>\n\n<ul>\n<li>Either you comment all methods or none\n\n<ul>\n<li>This is generally not a good rule of thumb, but for coding tasks in a job interview setting can show consistency</li>\n</ul></li>\n<li>If you comment a method use \"DocComment\" style, i.e.</li>\n</ul>\n\n<pre><code>///<summary>\n/// Moves robot one unit in direction faced\n///</summary> \npublic void Move()\n{\n ...\n}\n</code></pre>\n\n<ul>\n<li>If you comment on specific lines don't say what the line does (this should be obvious from the code) but why you implemented it the way you did</li>\n</ul>\n\n<pre><code>//Calls turn with direction as increment of _f <- useless comment\npublic void Left()\n{\n Turn(() => (int)_f + 1);\n}\n</code></pre>\n\n<ul>\n<li>Only use comments if there is <strong>absolutely no other way</strong> to express it in code</li>\n</ul>\n\n<p><strong>You use code constructs that are not fit for the purpose</strong></p>\n\n<ul>\n<li>The <code>CommandHandler.cs</code> contains a <code>switch</code> with a single <code>case</code> and the code in there is not even poperly indented. Also a <code>case</code> should IMHO not contain more than two or three lines. If you need to handle more, extract a method</li>\n</ul>\n\n<p><strong>Naming is hard</strong></p>\n\n<p>You should double check your naming.</p>\n\n<pre><code>public static bool IsValidPlacement(int? a)\n{\n var startIndex = 0;\n var endIndex = 4;\n\n return a >= startIndex && a <= endIndex;\n}\n</code></pre>\n\n<p>doesn't look bad, but consider the following changes</p>\n\n<pre><code>public static bool IsValidPlacement(int placementIndex)\n{\n const int minPlacementIndex = 0;\n const int maxPlacementIndex = 4;\n\n return placementIndex >= minPlacementIndex \n && placementIndex <= maxPlacementIndex;\n}\n</code></pre>\n\n<ul>\n<li>Even if you don't touch the vars make it explicitly clear to others that these values cannot be changed. </li>\n<li>Keep the wording, don't use start and end when they refer to a min and max</li>\n<li>Do not accept <code>int?</code> when you know that you absolutely must have a value here.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:03:47.800",
"Id": "449193",
"Score": "0",
"body": "Thank you for your comments, i will definitely reconsider naming, when to use nullable variables and commenting in the future. One thing though, the CommandHandler contains 6 cases including default, not 1, (the lack of indentation probably makes it hard to notice) and they all have 1-2 lines except the top one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:24:10.647",
"Id": "449197",
"Score": "0",
"body": "I really missed the cases due to non-existant spacing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T20:07:22.937",
"Id": "449407",
"Score": "3",
"body": "\"Either you comment all methods or none\". That's a horrible requirement. Can you name a single large open source project on GitHub that actually does that? All those internal obvious getters and setters? Obvious internal helper methods and one-liners? I mean I've seen code bases where someone had that genius idea which then ended up with wonderfully helpful comments such as `/* The Product Id */ public int Productid {get;}`. Document the important stuff and the public interfaces, but everything? Pointless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T19:19:33.090",
"Id": "449525",
"Score": "0",
"body": "I partially agree generally _comment everything_ is not a good rule of thumb but I wanted to make the point that the selection of what was commented seemed random and in a coding assignment for a job interview you should IMHO chose consistency and would be one way to achieve it. I'll clarify the answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T08:12:14.610",
"Id": "230528",
"ParentId": "230520",
"Score": "10"
}
},
{
"body": "<h2>Styles and conventions</h2>\n<ul>\n<li>The <code>using</code> should <strong>always</strong> be at the top of your file.</li>\n<li>Variable names like <code>_f</code> means...? Facing? Face? Force (obviously not, but see where I'm going?)? Don't hesitate to use meaningful variable names. Instead of <code>_f</code>, the variable could be named <code>direction</code> since it's a <code>Direction</code> object.</li>\n<li>The indentation of the <code>switch</code> is real bad. But I'd suspect it's because of how you pasted it here, not how your code looks. If the <code>switch</code> in the IDE looks like this, change it because it makes it impossible to read quickly.</li>\n</ul>\n<h2>OOP / Best practices</h2>\n<ul>\n<li>If I use a <code>Robot</code> object, I'd expect to be able to see what's its position. What I mean is that <code>_x</code> should be <code>X {public get; private set;}</code>. The same goes for the other properties.</li>\n<li>In the <code>Helpers</code> class, <code>startIndex</code> and <code>endIndex</code> should be constants, not variables.</li>\n<li>You shouldn't catch <code>Exception</code>. If you catch a specific exception, it shows you understand what could go wrong in the code, that's great.</li>\n<li>Your <code>Main</code> "never finishes".</li>\n<li>You sometimes check for <code>null</code> input, sometimes not. You should be consistent (a.k.a always use it, in my opinion) when accessing a <code>public</code> method.</li>\n<li>I don't think it's the <code>CommandHandler</code>'s responsibility to decide if the robot can move or not (if the placement wasn't made). The <code>Robot</code> class itself should be able to ignore a movement if it isn't placed (or if it causes it to fall). This would also simplify a lot of your checks.</li>\n<li>The whole <code>Command</code> pattern invites a <code>Factory</code> pattern. The advantage of doing this is that your <code>CommandHandler</code> class doesn't have the responsibility of knowing all the possible commands and the commands can be easily tested/mocked.</li>\n<li>You can also take this "further" and have a <code>Robot</code> class that only maintains the state of the robot and <code>Command</code>s classes where you make the robot move. Once again, this makes testing easier. Like this :</li>\n</ul>\n<h1></h1>\n<pre><code>public class Robot \n{\n public int? X { get; set; }\n public int? Y { get; set; }\n public Direction? Direction { get; set; }\n\n public bool IsPlaced() => X == null || Y == null || Direction == null;\n}\n\npublic interface ICommand\n{\n public void Execute(Robot robot);\n public bool Validate(Robot robot);\n}\n\npublic class MoveCommand : ICommand\n{\n public void Execute(Robot robot) { /*Here you can make the robot move*/ }\n public bool Validate(Robot robot) { /*Here you can validate if the command is valid for a robot*/ }\n}\n\npublic class CommandFactory\n{\n public ICommand Create(string command)\n {\n string[] args = Helpers.GetArrayFromSplitInput(command);\n \n switch (args[0]) \n {\n case "move":\n return new MoveCommand();\n //...\n }\n }\n}\n\npublic class CommandHandler : ICommandHandler\n{\n private readonly CommandFactory commandFactory;\n\n //I'm skipping the ctor, but I'm sure you get the point\n\n public void Handle(string commandString)\n {\n ICommand command = commandFactory.Create(commandString);\n \n if (!command.Validate(robot)) return;\n \n command.Execute(robot);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T01:22:35.840",
"Id": "449324",
"Score": "0",
"body": "I normally put the using statements at the top, but i used StyleCop for this in and it has a rule that says the opposite - SA1200. The case indentation is in the code, also due to a StyleCop edit - however in hindsight I realise I misunderstood the rule that made that warning go away so my fault. I will try to learn from your points, Thank you for the feedback"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T09:58:26.277",
"Id": "449352",
"Score": "0",
"body": "Is it good style in `CommandHandler::Handle` to have both the command string and the command object share the variable name `command`? Is it an application of KISS in the same method to not simply combine the last two lines to `if(command.Validate(robot)) command.Execute(robot);`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T20:10:55.480",
"Id": "449408",
"Score": "0",
"body": "\"The using should always be at the top of your file.\" There's several code guides *and* a style cop rule that disagree with that commandment. I don't see any reason why anybody should care about that as long as it's consistent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:21:55.463",
"Id": "449766",
"Score": "0",
"body": "@LutzL lol, no it's not normal, that's my bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:57:33.743",
"Id": "449772",
"Score": "0",
"body": "\"The Robot class itself should be able to ignore a movement if it isn't placed (or if it causes it to fall)\" - What if we wanted to change the behavior so the robot could fall off the table? I don't think this logic belongs in the robot class itself as it could potentially violate open/closed.I think you have sort of addressed this though in a way with your last bullet point."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:04:10.927",
"Id": "230547",
"ParentId": "230520",
"Score": "6"
}
},
{
"body": "<p>Collected thoughts:</p>\n\n<p>Your <code>Helpers</code> class is weird. It mixes e.g. command line input (<code>GetArrayFromSplitInput</code>) with a bad pattern that you don't need, that is, the <code>RunCommandIfTrue</code> method: just use an if statement where you need it instead of using higher-order functions! You just make your code unnecessarily harder to read at the call sites of <code>RunCommandIfTrue</code>. </p>\n\n<p>What's worse, your Helpers class also contains business logic (<code>IsValidPlacement</code>), which is a big no-no. Down that road lie God objects and the death of software architecture. This mixing of responsibilities is actually probably the biggest issue with your code, as it creates the impression that you gave no thought to future-proofing your design. It's the S in SOLID!</p>\n\n<p>There's also basically your entire Main function. You have</p>\n\n<pre><code>bool run = true;\n[...]\nwhile (run)\n{\n</code></pre>\n\n<p>but there's no place where run is ever set to false, making the construct useless. Also, this line: </p>\n\n<pre><code>handler.HandleCommand(Helpers.GetArrayFromSplitInput(Console.ReadLine()));\n</code></pre>\n\n<p>is considerably too busy. Separate state-changing or IO actions should almost always be in separate statements, not be crammed into a single statement like this. This is particularly true here. Your decision to cram it all into one line forces you to keep the entire statement inside a single try-block, even though the exception you are trying to catch can only happen within the <code>GetArrayFromSplitInput</code> method. This can cause your catch-block to catch exceptions that it is not supposed to and then misrepresent the error:</p>\n\n<pre><code>catch (Exception e)\n{\n Console.WriteLine(\"Invalid Input: \" + e.Message);\n}\n</code></pre>\n\n<p>Any error in your <code>HandleCommand</code> routine will be reported as an invalid input. The same is true if <code>Console.ReadLine</code> is called on a broken pipe. That is (potentially) a <strong>bug</strong>! Always keep try blocks as small as at all possible.</p>\n\n<p>Speaking of try blocks, one of your methods represents success or failure with a boolean return value. This isn't the 1970's anymore, if your method fails to execute, throw an exception! A reminder here that other programmers might forget to check for the boolean return value when calling your method.</p>\n\n<p>Then there's snippets like this:</p>\n\n<pre><code>//Calls turn with direction as increment of _f\npublic void Left()\n{\n Turn(() => (int)_f + 1);\n}\n</code></pre>\n\n<p>Without knowing how the <code>Turn</code> method works internally, I am left guessing what this might be doing. And when looking at that <code>Turn</code> method, it is a lot of complexity for a one-liner: </p>\n\n<pre><code>//If value less than zero default, otherwise calculate direction based on modulo\nprivate void Turn(Func<int> newDirection)\n{\n _f = (newDirection() < 0) ? Direction.EAST : (Direction)(newDirection() % 4);\n}\n</code></pre>\n\n<p>This is so much mental overload just to clamp a value in the [0, 3] range that it is not worth the DRY here. Rule of thumb: copying a line of code once (here: the clamping logic in the Left and Right functions) is probably okay, it's the third instance that tells you to start looking for a solution. Even then, it's better for readability if the solution doesn't involve random lambdas and higher-order functions!</p>\n\n<p>All in all, the code looks very much like you were trying to be \"clever\" when writing it. This is a habit that you should work on. Remember the old adage: it is twice as hard to debug code as it is to write code, and by corollary, if you employ your full cleverness to write it, you are unable to debug it! Start writing stupider code, with more emphasis on KISS and clearly delineating the responsibilities of the classes you're writing. Even in a coding interview, the goal should not be to \"show off\" how well you understand higher-order logic, but to show that you are able to write correct and maintainable code that is, first and foremost, also easy to read for other programmers. That is an important skill when working in a team!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:37:07.600",
"Id": "449274",
"Score": "2",
"body": "Hey Colin, great first answer. Let's hope we'll see more of you around"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T02:21:31.920",
"Id": "449327",
"Score": "1",
"body": "Thank you for your points on exception handling and placing business logic in the helper, I clearly missed SRP on the class level. RunCommandIfTrue is there to emulate when (from ie Clojure). Turn performs a ternary operation and takes a function - i dont see how this or lambdas and HOF in general is complex and not KISS. If i kept the Turn logic in ie Left(), it would be : _f = ((int)_f+1) < 0) ? Direction.EAST : (Direction)((int)_f+1 % 4); How would you do this part better ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T15:01:53.973",
"Id": "449375",
"Score": "0",
"body": "You shouldn't emulate `when` from Clojure when not writing Clojure code. C# is not a functional language. Of course, you can \"write Perl in any language\", and probably also \"write LISP in any language\", but it is not idiomatic and should be avoided. Write clear imperative code in C# (and clear functional code in Clojure). Your suggestion for the `Left` code is fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T15:01:58.870",
"Id": "449376",
"Score": "0",
"body": "By the way, even if you do want to write a `Turn` function for DRYness, you do not need `Func<int>`, you can just pass in `int`. Not only does this make your code less needlessly functional, this also fixes a potential bug in your current design: since you evaluate the `Func<int>` argument twice, if a caller passes in an effectful function or another function which might return two different directions on two separate calls, the return value is undefined."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T04:29:00.277",
"Id": "449445",
"Score": "1",
"body": "I don't agree that FP style should always be avoided in C#. I view C# as \"a multi-paradigm language with an increasingly strong functional component\" (this author is more eloquent than me: https://hackernoon.com/is-c-7-starting-to-look-like-a-functional-language-d4326b427aaa). A Microsoft MVP blogs about FP in C# https://weblogs.asp.net/dixin/functional-csharp-fundamentals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T04:43:07.660",
"Id": "449446",
"Score": "0",
"body": "I agree that Turn should take an int instead to avoid evaluating twice. I don't understand the potential bug description, any function returning integer <0 and <=4 results in a direction, larger numbers would never occur with the existing input validation. If despite that a function with larger result would be passed to Turn, the Direction would be set based on wrong logic but not be undefined. Could you please show an example with code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T07:49:54.917",
"Id": "449461",
"Score": "0",
"body": "\"one of your methods represents success or failure with a boolean return value. This isn't the 1970's anymore, if your method fails to execute, throw an exception! A reminder here that other programmers might forget to check for the boolean return value when calling your method.\" This isn't universally true. For example `int.TryParse`, which takes a reference parameter and returns a `bool` is considered better than `int.Parse` which throws an exception. See [Eric Lippert's Vexing Exceptions](https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:26:06.950",
"Id": "230550",
"ParentId": "230520",
"Score": "7"
}
},
{
"body": "<p>I will try to focus on things that have not been said, but I apologise in advance if I have repeated something that has been mentioned in any previous answers.</p>\n\n<hr>\n\n<p>Separating your code into <code>Constatnts</code>, <code>Enums</code> and <code>Interfaces</code> folders probably isn't particularly helpful. Especially when you have only one or two files in each folder.</p>\n\n<p>Similarly naming a folder <code>src</code> isn't particularly helpful. Aside from the fact that <code>src</code> is a contraction (it would make more sense to call it <code>Source</code> in full), you have source files outside your <code>src</code> folder, which sends mixed messages to your end users and confuses matters. If you have a 'source' folder then it should contain all of your source code, not just half of your source code.</p>\n\n<p><code>DataConstants</code> is too generic a name - you're not going to stuff all your constants into a single class (or at least you shouldn't be). Instead your command names should be in a class specifically designated as <code>CommandNames</code>.</p>\n\n<p><strong><code>GetNumberFromString</code>:</strong></p>\n\n<p>Firstly the name is misleading. You should specify that the function only parses integers rather than generic 'numbers' lest anyone using your API think that decimal points are acceptable.\nA better name would be <code>ParseInt</code> or <code>ParseIntAsNullable</code>.</p>\n\n<p>The <code>result</code> variable is redundant. You should get rid of it.\nYou could in fact simplify the whole function as thus:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static int? GetNumberFromString(string text)\n{\n int result;\n return int.TryParse(text, out result) ? result : null;\n}\n</code></pre>\n\n<p>Or, if you have access to C# 7.0 or later then it's a one-liner:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>public static int? GetNumberFromString(string text)\n{\n return int.TryParse(text, out int result) ? result : null;\n}\n</code></pre>\n\n<p><strong><code>GetDirectionFromString</code>:</strong></p>\n\n<p>Does this actually compile for you? According to <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=netframework-4.8\" rel=\"noreferrer\">the documentation</a> (and my compiler), <code>Enum.TryParse</code> only has two overloads, and neither match the arguments you're trying to feed it.</p>\n\n<p>Additionally, you aren't reporting what happens if the parse fails - you're swallowing/ignoring the error.\nYou should either throw an exception like a <code>Parse</code> function does (e.g. <code>Enum.Parse</code>) or you should turn this into a proper <code>TryParse</code> function that returns a <code>bool</code> indicating success and passes the enumeration out as an <code>out</code> parameter.</p>\n\n<p>Also rather than lumping this in with a load of generic <code>Helpers</code>, it might be wiser to put is in a specific <code>static class</code> named <code>DirectionUtils</code> (see <a href=\"https://stackoverflow.com/a/12192155\">Helpers vs Utils</a>).\nSaid class could even be kept in the same file as <code>Direction</code> given how related the two are and how minimalist the helper class would be.</p>\n\n<p>Lastly rather than <code>GetDirectionFromString</code>, this function should simply be named <code>ParseDirection</code> or <code>Parse</code>.</p>\n\n<p>So essentially you should end up with something like:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>public static class DirectionUtils\n{\n public static Direction Parse(string input)\n {\n return Enum.Parse<Direction>(input);\n }\n\n public static bool TryParse(string input, out Direction direction)\n {\n return Enum.TryParse<Direction>(input, out direction);\n }\n}\n</code></pre>\n\n<p>However, note that all this seemingly does is forward to the <code>Enum</code> versions, so perhaps you should just stick to using those directly.</p>\n\n<p><strong><code>IsValidPlacement</code>:</strong></p>\n\n<p>I'd actually recommend turning this into a <code>PlacementValidator</code> object, so that you could easily change which placements are considered valid if the requirements changed.</p>\n\n<p>E.g.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class PlacementValidator\n{\n public PlacementValidator(int min, int max)\n {\n this.Min = min;\n this.Max = max;\n }\n\n public int Min { get; private set; }\n\n public int Max { get; private set; }\n\n public bool IsValid(int position)\n {\n return ((position >= Min) && (position <= Max));\n }\n}\n</code></pre>\n\n<p>Then of course this would have to be weaved into the rest of your code.\nI would recommend putting this kind of validation either in the input validation or the command handler rather than the robot.\nIt makes more sense for the robot to simply be a dumb puppet/bag-of-data that doesn't validate anything, because that makes it more flexible.</p>\n\n<p><strong><code>RunCommandIfTrue</code>:</strong></p>\n\n<p>Completely redundant, and adds to the confusion by making the condition the last argument.\nJust use an <code>if</code> statement instead.</p>\n\n<p><strong><code>HandleCommand</code>:</strong></p>\n\n<p>Something nobody else seems to have mentioned: you check if <code>command</code> is <code>null</code>, but you don't bother to check if <code>command.Length > 0</code> before trying to access <code>command[0]</code>, which would net you an out of bounds error if someone passed in an array with a length of 0.</p>\n\n<p>Your <code>Helpers</code> functions seem to be quite unrelated and should probably be kept under separate APIs.\nE.g. <code>GetNumberFromString</code> should be grouped with <code>GetArrayFromSplitInput</code> because they're both very general, but <code>GetDirectionFromString</code> and <code>IsValidPlacement</code> are more specialist.</p>\n\n<p>Your use of <code>RunCommandIfTrue</code> is actually obscuring your code. While I don't agree that functional style code has no place in C#, this is certainly not the place where it belongs.</p>\n\n<p>This seems to me like a case of \"I have a hammer syndrome\" or \"look what I can do syndrome\" - the desire to show off something one has learned either without knowing where to make use of it or without having a suitable place to use it. This isn't unusual, near enough everybody experiences it at some point.</p>\n\n<p>Your code would be much clearer and probably more efficient if you simply used an <code>if</code> statement.</p>\n\n<p>More crucially, the fact that <code>_placehasBeenExecuted</code> might be <code>false</code> when <code>Move</code>, <code>Left</code>, <code>Right</code> or <code>Report</code> are selected seems to me like it might be an error condition that you should be reporting properly through use of a specific exception (either an <code>InvalidOperationException</code> or a user-defined exception such as <code>InvalidCommandException</code> or <code>RobotNotPlacedException</code>).</p>\n\n<p>You also appear to be lacking errors for an unrecognised command and a place command with an unsuitable number of arguments.</p>\n\n<p>Putting all these things together, a naive improvement would be:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public void HandleCommand(string[] command)\n{\n if (command == null)\n throw new ArgumentNullException(\"command\");\n\n if (command.Length == 0)\n throw new ArgumentException(\"command is empty\");\n\n switch (command[0])\n {\n case CommandNames.Place:\n if(command.Length < 4)\n throw new CommandParameterException(string.Format(\"Not enough parameters. Expected 4, got {0}\", command.Length));\n\n int x;\n if(!int.TryParse(command[1], out x))\n throw new CommandParameterException(string.Format(\"Place parameter 0 is not a proper integer: {0}\", command[1]));\n\n int y;\n if(!int.TryParse(command[2], out y))\n throw new CommandParameterException(string.Format(\"Place parameter 1 is not a proper integer: {0}\", command[2]));\n\n Direction direction;\n if(!DirectionUtils.TryParse(command[3], out direction))\n throw new CommandParameterException(string.Format(\"Place parameter 2 is not a proper direction: {0}\", command[3]));\n\n var placementRequest = new PlacementRequest() { X = x, Y = y, F = direction };\n\n _placeHasBeenExecuted = _rob.Place(placementRequest);\n break;\n case CommandNames.Move:\n if(_placeHasBeenExecuted)\n _rob.Move();\n else\n throw new RobotNotPlacedException(\"Attempt to use the robot before it has been placed\");\n break;\n case CommandNames.Left:\n if(_placeHasBeenExecuted)\n _rob.Left();\n else\n throw new RobotNotPlacedException(\"Attempt to use the robot before it has been placed\");\n break;\n case CommandNames.Right:\n if(_placeHasBeenExecuted)\n _rob.Right();\n else\n throw new RobotNotPlacedException(\"Attempt to use the robot before it has been placed\");\n break;\n case CommandNames.Report:\n if(_placeHasBeenExecuted)\n _rob.Report();\n else\n throw new RobotNotPlacedException(\"Attempt to use the robot before it has been placed\");\n break;\n default:\n throw new UnrecognisedCommandException(string.Format(\"Unrecognised command: {0}\", command[0]));\n }\n}\n</code></pre>\n\n<p>However, as a number of these things are technically problems with the input data rather than the code itself, it may actually be preferable to separate the input validation from the processing logic and actually store the commands in a format that cannot be invalid so that <code>HandleCommand</code> (see @IEatBagels's answer for one possible solution to this, and see <a href=\"http://gameprogrammingpatterns.com/command.html\" rel=\"noreferrer\">here</a> for more info on the command pattern).</p>\n\n<p>At the very least, it makes sense to translate the user's input into some kind of <code>CommandType</code> enum rather than operating on text, that way you can more easily separate format errors (e.g. 'x is not an integer') from logic errors (e.g. 'the robot cannot move because it hasn't been placed').</p>\n\n<p><strong><code>Robot.Turn</code>:</strong></p>\n\n<p>There's actually two places where I think this is going wrong.</p>\n\n<p>Firstly, using a <code>Func</code> here is nothing but a waste of time and resources. It acheives absolutely nothing.</p>\n\n<p>Secondly, you should be hiding the ugly casting that's going on. Rather than making <code>Left</code> and <code>Right</code> cast an <code>enum</code> to an <code>int</code>, you should hide that away in a function in the newly added <code>DirectionUtils</code> class.\nE.g.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static class DirectionUtils\n{\n public static Direction Next(Direction direction)\n {\n return (Direction)(((int)direction + 1) % 4);\n }\n\n public static Direction Previous(Direction direction)\n {\n return (direction == Direction.NORTH) ? Direction.EAST : (Direction)((int)direction - 1);\n }\n}\n</code></pre>\n\n<p>And then you can scrap <code>Turn</code> in favour of:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public void Left()\n{\n _f = DirectionUtils.Next(_f);\n}\n\npublic void Right()\n{\n _f = DirectionUtils.Previous(_f);\n}\n</code></pre>\n\n<p>(Which arguably should be called <code>TurnLeft</code> and <code>TurnRight</code>. Methods should ideally be verbs.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T09:32:33.563",
"Id": "230638",
"ParentId": "230520",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "230638",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T05:09:51.990",
"Id": "230520",
"Score": "12",
"Tags": [
"c#",
".net-core"
],
"Title": "C# Toy Robot Simulator"
}
|
230520
|
<p>I've decided to write some Linux commands in Python. Below is a list, along with some constraints (if you're unfamiliar with Linux, the top of the program along has a description about each command and what it does):</p>
<ul>
<li><code>ls</code>: No constraints, just lists all files/directories in current working directory. No flags.</li>
<li><code>cd</code>: Can only pass <code>..</code> or another directory. No flags.</li>
<li><code>tree</code>: No flags or directories can be passed.</li>
<li><code>clear</code>: No constraints. No flags.</li>
<li><code>whatis</code>: Only defined commands can be passed. No flags.</li>
<li><code>cat</code>: Requires a <em>full</em> path to the file. No flags.</li>
</ul>
<p>I would like feedback on all the functions embodied by the program below, but <code>whatis</code> in particular. I feel there is a better way than checking each individual function. Any and all recommendations are appreciated.</p>
<pre><code>"""
This is a program to simulate a command line interface
Commands to reimplement:
- ls ( lists all files and directories in current directory )
- cd [directory] ( changes directory )
- tree ( lists all files, directories, sub directories and files from current directory )
- clear ( clears the console screen )
- whatis [command] ( gives a description about the command )
- cat [file] ( outputs the content of the file )
"""
import os
def ls() -> None:
"""
Lists all files and directories in current directory
"""
current_directory = os.getcwd()
for _, directories, files in os.walk(current_directory):
for file in files:
print(file)
for directory in directories:
print(directory)
def cd(directory: str) -> str:
"""
Changes directory
"""
current_directory = os.getcwd()
if directory == "..":
current_directory = current_directory.split("/")[:-1]
current_directory = ''.join(f"{x}/" for x in current_directory)
return current_directory
if os.path.isdir(directory):
return directory
return "Not a directory"
def tree() -> None:
"""
Lists all files, directories, sub directories and files from current directory
"""
current_directory = os.getcwd()
tab_count = 1
print(current_directory.split("/")[-1])
for _, directories, files in os.walk(current_directory):
for file in files:
print("|" + ("-" * tab_count) + file)
for directory in directories:
print("|" + ("-" * tab_count) + directory)
tab_count += 1
def clear() -> None:
"""
Clears the console screen
"""
print("\n" * 100)
def whatis(command: str) -> None:
"""
Prints a description about the passed command
"""
if command == "ls":
print(ls.__doc__)
elif command == "cd":
print(cd.__doc__)
elif command == "tree":
print(tree.__doc__)
elif command == "clear":
print(clear.__doc__)
elif command == "whatis":
print(whatis.__doc__)
elif command == "cat":
print(cat.__doc__)
else:
print("Not a valid command!")
def cat(file_path: str) -> None:
"""
Accepts a path to a file, and outputs the contents of that file
"""
if os.path.exists(file_path):
with open(file_path, "r") as file:
print(''.join(line for line in file))
else:
print("Not a file!")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T05:29:22.310",
"Id": "449168",
"Score": "0",
"body": "`ls` is in the `os` module, you can use `os.listdir()` as well as `cd` for which you can use `od.chdir(path)` and for `clear` you may use `os.system('cls')`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T05:34:17.243",
"Id": "449169",
"Score": "2",
"body": "@bullseye I realize those are available commands, but I tried to use the least amount of built in functions as I could."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T16:05:05.430",
"Id": "449248",
"Score": "1",
"body": "@bullseye I think you mean `clear` instead of `cls`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:40:51.217",
"Id": "449276",
"Score": "0",
"body": "These commands look like meant for user interactive session. If that is the case, and you are not implementing them just as an exercise, I highly recommend using some more advanced python shell instead, such as ipython (available both for Python-2 and python-3, both for Linux and Windows, possible to install via pip). It features history access and search, tab completion of commands AND filenames, AND you can execute any actual linux shell command by simply prepending it with \"!\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T20:35:26.587",
"Id": "449296",
"Score": "0",
"body": "@bullseye You have those two confused. `cls` is for windows systems, and `clear` is for unix systems"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T20:36:49.977",
"Id": "449297",
"Score": "0",
"body": "@Linny exactly, I swapped them, `cls` for windows, `clear` for unix @marcelm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T11:35:14.003",
"Id": "449358",
"Score": "0",
"body": "Your `ls` takes no arguments. Is this by choice or did you simply not get around to that yet?"
}
] |
[
{
"body": "<p>Here are a few comments. In general, your code deviates in surprising ways from the UNIX commands (and not just by missing flags or options):</p>\n\n<ul>\n<li><p>Your <code>ls</code> command does more than you claim it does. <code>os.walk</code> recursively \"walks\" down from the current directory, so it returns the content of all subfolders as well (without indicating in which subfolder each file or directory actually is).</p></li>\n<li><p>When working with paths you should use the library <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\"><code>pathlib</code></a> or at least <code>os.path</code> consistently. This allows your tools to also work in Windows, where the symbol separating paths is <code>\\</code> and not <code>/</code>. You could use <code>os.path.join</code> in your <code>cd</code> function. However, all that code there is not needed, because <code>os.path.isdir(\"..\")</code> is also <code>True</code>. Use <a href=\"https://docs.python.org/3/library/os.path.html#os.path.abspath\" rel=\"noreferrer\"><code>os.path.abspath</code></a> to get the absolute name of a path. In my home directory <code>os.path.abspath(\"..\")</code> returns <code>/home</code>.</p></li>\n<li><p>Don't use special return values to indicate failure. What if I want to have a directory called <code>\"Not a directory\"</code>? It may not be the most common name for a directory, but it is at least a plausible name. Instead raise an exception and catch it in the surrounding scope.</p></li>\n<li><p>Note that your <code>cd</code> does not <em>actually</em> change the directory, so any calls in another function to <code>os.getcwd()</code> (like in <code>ls</code>) will still return the old directory.</p></li>\n<li><p>Instead of hard-coding 100 blank lines, try to find out how many lines the terminal has, as taken from this <a href=\"https://stackoverflow.com/a/943921/4042267\">answer</a> by <a href=\"https://stackoverflow.com/users/68595/brokkr\">@brokkr</a>:</p>\n\n<pre><code>import os\nrows, columns = os.popen('stty size', 'r').read().split()\n</code></pre>\n\n<p>This probably works only on linux, though.</p></li>\n<li><p>Instead of reading the whole file into memory, joining it and then printing it, you can print it one line at a time. This is slightly slower, but has no memory limitation:</p>\n\n<pre><code>def cat(file_path: str) -> None:\n \"\"\"\n Accepts a path to a file, and outputs the contents of that file\n \"\"\"\n if os.path.exists(file_path):\n with open(file_path, \"r\") as file:\n for line in file:\n print(line, end=\"\")\n else:\n print(\"Not a file!\")\n</code></pre></li>\n<li><p>As long as all your functions are defined in the same module, you can simplify your <code>whatis</code> command:</p>\n\n<pre><code>def whatis(command: str) -> None:\n \"\"\"\n Prints a description about the passed command\n \"\"\"\n try:\n print(globals()[command].__doc__)\n except KeyError:\n print(\"Not a valid command!\")\n</code></pre>\n\n<p>Although this does open you up slightly to a user getting access to the <code>__doc__</code> attribute of any object in the global namespace (not sure if that is a security risk, though). To avoid this, you can also built a white-listed dictionary:</p>\n\n<pre><code>DOCS = {f.__name__: f.__doc__ for f in [ls, cd, clear, tree, whatis, cat]}\n\ndef whatis(command: str) -> None:\n \"\"\"\n Prints a description about the passed command\n \"\"\"\n try:\n print(DOCS[command])\n except KeyError:\n print(\"Not a valid command!\")\n</code></pre></li>\n<li><p>I think the docstrings should be in the same style as linux manpages, i.e. like you have in your module docstring.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:45:44.007",
"Id": "449255",
"Score": "0",
"body": "You could say that the OP's code implements `ls -R` without the directory-name headers that actual `ls` prints when recursing. Or more exactly: `find -printf '%f\\n'` instead of `ls`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:46:54.523",
"Id": "449256",
"Score": "0",
"body": "@PeterCordes True. But then this should be reflected in the docstring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:49:09.603",
"Id": "449259",
"Score": "1",
"body": "Oh yeah, I assume it was unintentional, and certainly not very useful. Just maybe fun to put it in those terms to illustrate to the OP what the symptom of their bug is, and what command they actually implemented by mistake. (Maybe they do want to implement `find` next...)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T07:49:52.963",
"Id": "230525",
"ParentId": "230521",
"Score": "17"
}
},
{
"body": "<p>There are a few ways to programmatically get the docs, and one that I find cool to use is <a href=\"https://docs.python.org/3.5/library/inspect.html\" rel=\"noreferrer\"><code>inspect</code></a>.</p>\n\n<p><code>inspect</code> allows you, among other things, to check what's in your file (module):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import inspect\nimport sys\n\ndocs = {} # a dictionary\nmodule = sys.modules[__name__] # Gets us a reference to the current module\n\nfor name, object in inspect.getmembers(module):\n # getmembers returns the name of the object, then the object itself.\n if inspect.isfunction(func): # Filter the functions\n docs[name] = object.__doc__\n</code></pre>\n\n<p>This can be rewritten as a dictionary <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"noreferrer\">list comprehension</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>module = sys.modules[__name__]\ndocs = {name: func.__doc__ for name, obj in inspect.getmembers(module) \n if inspect.isfunction(obj)}\n</code></pre>\n\n<p>Then, this could be defined as a constant:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>module = sys.modules[__name__]\nDOCS = {name: func.__doc__ for name, obj in inspect.getmembers(module) \n if inspect.isfunction(obj)}\n\ndef whatis(command: str) -> None:\n print(DOCS.get(command, \"Not a valid command!\"))\n</code></pre>\n\n<p><code>dict.get</code> allows to specify a default value if the key is not in the dict (here, the error message).</p>\n\n<p>This shows an alternative to your implementation, but I would not use it myself, for it's not so clear at first glance. What I like about it, though, is to have a constant dictionary, for this module is concise enough:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>DOCS = {\n 'ls' = ls.__doc__,\n 'cd' = cd.__doc__,\n 'tree' = tree.__doc__,\n 'clear' = clear.__doc__,\n 'whatis' = whatis.__doc__,\n 'cat' = cat.__doc__,\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:45:16.130",
"Id": "449199",
"Score": "2",
"body": "You already use `inspect`, so it might be worth to have a look at [`inspect.getdoc(...)`](https://docs.python.org/3/library/inspect.html#inspect.getdoc)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T08:03:14.487",
"Id": "230527",
"ParentId": "230521",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "230525",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T05:17:20.873",
"Id": "230521",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"reinventing-the-wheel",
"linux"
],
"Title": "Linux Commands in Python"
}
|
230521
|
<p>There is a small <a href="https://www.fluentcpp.com/2019/10/11/code-it-yourself-merging-consecutive-elements-in-a-c-collection/" rel="nofollow noreferrer">programming exercise</a> to merge adjacent identical elements in a collection.</p>
<p>Here are two <a href="http://coliru.stacked-crooked.com/a/6b4f94f6e8fbaf66" rel="nofollow noreferrer">solutions</a> (passing the tests from the exercise).
I am asking for review of the first version using standard algorithms.
The second is just for reference of the expected behavior.</p>
<pre><code>template <typename ForwardIterator, typename OutputIterator, typename Equal, typename Merge>
void merge_adjacent(ForwardIterator first, ForwardIterator last, OutputIterator out, Equal equal, Merge merge)
{
while(first != last){
auto start = first;
auto stop = std::find_if_not(start,last,[&](auto const &t){return equal(*start,t);});
if(start != stop){
out = std::accumulate(start+1,stop,*start,merge);
}
else{
out = *start;
}
first = stop;
}
/*
while(first != last)
{
auto next = *first;
first++;
while((first != last) && (equal(next,*first)))
{
next = merge(next,*first);
first++;
}
out = next;
}
*/
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T06:51:25.390",
"Id": "449173",
"Score": "0",
"body": "Are you sure the data is sorted? If yes, then you could just [std::upper_bound](https://en.cppreference.com/w/cpp/algorithm/upper_bound) your way to the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T07:00:45.403",
"Id": "449175",
"Score": "0",
"body": "I do not have an `compare`, only an `equal`. So the data is not sorted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T08:24:00.690",
"Id": "449180",
"Score": "0",
"body": "If I understand correctly, this is `std::unique_copy()`, but instead of discarding duplicates, we have to use `merge` to combine them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T08:44:47.913",
"Id": "449181",
"Score": "0",
"body": "@Toby correct, but I want to clarify: We only merge adjacent duplicates and the element we push write to the output is the result of this merge."
}
] |
[
{
"body": "<p>Generally looks okay (though I would prefer shorter line lengths, and the indentation needs cleaning up).</p>\n\n<p>It seems that we've focused on using <code>std::back_insert_iterator</code> as the output iterator; this leads to a couple of problems that are visible when we switch to a different iterator, such as a collection iterator or raw pointer:</p>\n\n<ul>\n<li>The caller doesn't know where the output finished; we should return the final value of <code>out</code>, just as <code>std::unique_copy()</code> does.</li>\n<li>The assignment <code>out =</code> neither indirects nor advances the iterator; it should be <code>*out++ =</code>.</li>\n</ul>\n\n<p>We don't need a separate <code>start</code> copied from <code>first</code>, and we can use <code>std::adjacent_find</code> to determine the range of equal elements:</p>\n\n<pre><code>#include <algorithm>\n#include <functional>\n#include <numeric>\n\ntemplate <typename ForwardIterator, typename OutputIterator,\n typename Equal, typename Merge>\nOutputIterator merge_adjacent(ForwardIterator first, ForwardIterator last,\n OutputIterator out,\n Equal equal, Merge merge)\n{\n while (first != last) {\n auto stop = std::adjacent_find(first, last, std::not_fn(equal));\n if (stop != last) {\n // advance to include the first of the pair\n ++stop;\n }\n *out++ = std::accumulate(first+1, stop, *first, merge);\n first = stop;\n }\n\n return out;\n}\n</code></pre>\n\n<p>This version still performs two passes (one for the search, and one for the accumulate). The commented-out, lower-level version of the function should be able to accept <em>input</em> iterators, as a single-pass algorithm.</p>\n\n<p>Looking at that version, there's only a little to improve. I'd probably post-increment the iterators while dereferencing, rather than as a separate statement, but that's just a style preference. One thing I would change would be to use <code>std::move()</code> when finishing with <code>next</code>, to minimise unnecessary copying:</p>\n\n<pre><code>#include <algorithm>\n#include <numeric>\n#include <utility>\n\ntemplate <typename InputIterator, typename OutputIterator,\n typename Equal, typename Merge>\nOutputIterator merge_adjacent(InputIterator first, InputIterator last,\n OutputIterator out,\n Equal equal, Merge merge)\n{\n while (first != last) {\n auto next = *first++;\n while (first != last && equal(next, *first)) {\n next = merge(std::move(next), *first++);\n }\n *out++ = std::move(next);\n }\n\n return out;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:09:03.457",
"Id": "230532",
"ParentId": "230522",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230532",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T06:22:09.933",
"Id": "230522",
"Score": "2",
"Tags": [
"c++",
"programming-challenge",
"c++17",
"iteration",
"stl"
],
"Title": "Merge adjacent occurrences of identical elements in data collection"
}
|
230522
|
<p>Here is my problem statement: </p>
<p>There is a matrix of octagons, for example, 4 octagons in a row and 3 such rows. So 4 columns and 3 rows of octagons. But they are not arranged in a perfect rectangle form. </p>
<p><strong>Case1:</strong></p>
<p><a href="https://i.stack.imgur.com/bi1NH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bi1NH.png" alt="Matrix of Octagons"></a></p>
<p>The first Octagon, O(0,0) has coordinates(0,0), while the one at its right and the one at bottom are at a bit offset. So O(0,1) has coordinates (15,50) and O(1,0) has coordinates (30,15). This information is enough to define the whole array of octagons. Now next requirement is to find how much is the net visible area of these octagons. In the first example, as the coordinates are far away, there would be no overlapping and total visible area is simply...</p>
<pre><code>Total_Visible_Area = Area_of_Single_Octagon * No_Of_Rows * No_Of_Columns
</code></pre>
<p>But when the coordinates are bit complex, for example, <strong>Case 2:</strong>
<a href="https://i.stack.imgur.com/QVa6H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QVa6H.png" alt="enter image description here"></a>
Here, the the distance between the adjacent octagons is less than their width and hence they are overlapping. Coordinates also are negative (which does not matter much actually, just something to note). Now to determine visible area for this I wrote the following function.</p>
<pre><code>//Inputs of the function:
//S = Side of the octagon/2, 5*Accuracy_Factor for both of the case
//G = Total Width of the octagon/2, 5*2.41*Accuracy_Factor for both of the case
//NSX = X distance of the octagon O(1,0), 8.09*Accuracy_Factor in Case 2
//NSY = Y distance of the octagon O(1,0), -20.98*Accuracy_Factor in Case 2
//EWX = X distance of the octagon O(0,1), 17.37*Accuracy_Factor in Case 2
//EWY = Y distance of the octagon O(0,1), 12*Accuracy_Factor in Case 2
//NSCount = Total no of rows, 4 in this example
//EWCount = Total no of columns, 3 in this example
//The following function initializes a big 2D array. Each pixel of the octagon is one
//element of the array. Program calculates coordinates of all octagons. Picking the
//octagons one by one, it forms an octagon around that coordinate in the
//2D array by allotting 1 to the array. At the end I find a total number
//of 1s ant that's my total visible area.
double OverlapArea(double S, double G, double NSX, double NSY, double EWX, double EWY, int NSCount, int EWCount)
{
int count = 0, i, j, x, y, ArrayColSize, ArrayRowSize, TotalArea;
double XMax = 0, XMin = 0, YMax = 0, YMin = 0, DishX[3], DishY[3], A, B, Ai, Bi;
std::vector<std::vector<int>> Area;
//Next few line, until the next comment, are written to find the
//size of the 2D array that will be required.
DishX[0] = EWX * (EWCount - 1);
DishX[1] = NSX * (NSCount - 1);
DishX[2] = EWX * (EWCount - 1) + NSX * (NSCount - 1);
DishY[0] = EWY * (EWCount - 1);
DishY[1] = NSY * (NSCount - 1);
DishY[2] = EWY * (EWCount - 1) + NSY * (NSCount - 1);
for (i = 0; i < 3; i++)
{
if (DishX[i] < XMin)
XMin = DishX[i];
if (DishX[i] > XMax)
XMax = DishX[i];
if (DishY[i] < YMin)
YMin = DishY[i];
if (DishY[i] > YMax)
YMax = DishY[i];
}
A = Ai = G - XMin;
B = Bi = G - YMin;
ArrayRowSize = (int)ceil(XMax - XMin + 2 * G);
ArrayColSize = (int)ceil(YMax - YMin + 2 * G);
Area.resize(ArrayRowSize+5, std::vector<int>(ArrayColSize+5, 0));
//Array is resized in the above line, not the loop that forms the octagons
for (i = 0; i < NSCount; i++)
{
for (j = 0; j < EWCount; j++)
{
for (x = A - G; x < A + G; x++)
{
for (y = B - G; y < B + G; y++)
{
if ((x - y >= A - B - S - G) && (y <= B + G) && (x + y <= A + B + S + G) && (x <= A + G) && (x - y <= A + G - B + S) && (y >= B - G) && (x + y >= A + B - S - G) && (x >= A - G))
{
Area[x][y] = 1;
}
}
}
A = Ai + EWX * (j+1);
B = Bi + EWY * (j+1);
count++;
}
A = Ai + NSX;
B = Bi + NSY;
Ai = A;
Bi = B;
}
TotalArea = 0;
for (i = 0; i < ArrayRowSize; i++)
{
for (j = 0; j < ArrayColSize; j++)
{
TotalArea = TotalArea + Area[i][j];
std::cout << Area[i][j]<<',';
}
std::cout <<std::endl;
}
return (double)TotalArea;
}
</code></pre>
<p>Now the problem with this method:</p>
<ol>
<li>The Accuracy factor that I set in the main function determines how accurate this method is. Higher the accuracy is, more the time to calculate. It's as simple as increasing resolution.</li>
<li>I can only use the shapes that I can define with equations (rectangle, circle, triangle octagon etc...) If it's an irregular shape, I'll have a tough time defining which pixel to count and which to not. </li>
</ol>
<p>I'd like to know other methods I can calculate visible area. One thing I can think of is inputting the shape as an image, overlapping it, and then calculate the pixels at the end. But not sure if there is a more simple way.</p>
<p>Edit: The main function is going to calculate 8000+ cases, out of which approx 3000 cases will require to go through this function. The Accuracy Factor needs to be an odd multiple of 7 (7,21,35,49...Found this via experimenting. 7 has more accuracy than 20.). With Accuracy factor = 21, the program took around 1 hour for its first 2000 calculations, after which I terminated it cause I had the idea that it's working good. But this time is unacceptable.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T02:41:34.703",
"Id": "449328",
"Score": "0",
"body": "Is your input an image? Or a bunch of shapes, i.e., equations that determine what you see? In your test all shapes are arranged on a grid, but will it actually be the case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T03:31:56.107",
"Id": "449329",
"Score": "0",
"body": "@ALX23z As of now, input are just parameters. Coordinates of the center & side length are enough to form the octagon in a 2D array. But for irregular shapes, this method won't work & I may not be able to formulate an equation to define the shape's boundary conditions. Hence when it comes to inputting the shape, inputting it via image is the only thing that comes to my mind. If anyone can suggest something more efficient, I'm open to it. I've no exp with images in C++.\n\nGrid will always be regular & won't have non-linear pattern. Eg: https://i.imgur.com/0PrHOG8.png grid with irregular shape."
}
] |
[
{
"body": "<p>There are two general approaches.</p>\n\n<h1>The first is to use image, and modify as you see fit.</h1>\n\n<p>Pros:</p>\n\n<ol>\n<li>Simple to use.</li>\n<li>Can be easily applied to all shapes.</li>\n<li>Reliable.</li>\n<li>There might already be a free suitable implementation you can use.</li>\n</ol>\n\n<p>Cons:</p>\n\n<ol>\n<li>Fixed limited accuracy.</li>\n<li>You might need to implement a GPU or SIMD based code to achieve required performance.</li>\n<li>Requires too much resources for trivial cases.</li>\n</ol>\n\n<h1>Second approach: use polygons.</h1>\n\n<p>There is a simple formula to compute area of a polygon.</p>\n\n<p>Say, you have a polygon <code>{(x_1, y_1)...(x_n, y_n)}</code> then its area is the sum</p>\n\n<pre><code>(x_2-x_1)*(y_1+y_2)/2 + ... + (x_1-x_n)*(y_n+y_1)/2\n// technically, it equals to either area or -area depending on orientation of the polygon\n</code></pre>\n\n<p>The problem is that union/intersection of polygons is not, in general, a polygon - instead, it can be expressed as a union of non-intersecting polygons. But then after repeated use number of polygons might blow up depending on input... so utilizing this method requires care and attention, though in your case it might be quite simple.</p>\n\n<p>It is harder to apply this method for all shapes: you ought to approximate the shape via a polygon.</p>\n\n<p><strong>Note</strong>: suitable for both approaches. Since your grid is regular, <em>under a mild additional assumption</em>, computation of Total Area can be to simplified to computation of area of a few pieces of it.</p>\n\n<ol>\n<li>Area in a cell of the grid. (A)</li>\n<li>4 types of areas that lie on the sides of the grid. (B1,B2,B3,B4)</li>\n<li>Remaining corner area - 4 regions at the corners. (C = C1+C2+C3+C4, it is the area of the base shape).</li>\n</ol>\n\n<p>See <a href=\"https://imgur.com/a/1Azo4us\" rel=\"nofollow noreferrer\">https://imgur.com/a/1Azo4us</a> for clarification. In the image I showed only two types of side areas and one corner area - there are also two types of side area on the other side of the grid.</p>\n\n<p>Total Area is <code>C + (B1+B3)*(Rows-1) + (B2+B4)*(Cols-1) + A*(Rows-1)*(Cols-1)</code></p>\n\n<p>Though, this simplification works only if the base shape is fully contained its four neighbor cells... if it is not the case the formula becomes more complicated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T04:56:49.123",
"Id": "449333",
"Score": "0",
"body": "I was really convinced that I may have to get into image manipulation for better accuracy, but the section method that you pointed out is really amazing and may save me the trouble getting into images. This algorithm may save me much of calculation time. I'm thinking of defining a 3x3 grid with very high accuracy factor, get all the section areas, and just use that info to calculate area for a larger grid of, let's say 25x30 grid. I'll start working on this and see how much it is viable. Thank You very much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T06:12:22.457",
"Id": "449342",
"Score": "0",
"body": "@AdityaSoni Glad to help! As a side note, there are simple ways to improve accuracy for image based computation: in the image data you can store greyscale or float instead of binary, with the extra info you try to approximate how much of the pixel is filled. Usually, you don't lose performance when you switch from boolean image to greyscale - unless you use optimized boolean images."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T04:07:26.490",
"Id": "230581",
"ParentId": "230524",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230581",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T06:35:57.523",
"Id": "230524",
"Score": "6",
"Tags": [
"c++",
"performance",
"algorithm",
"computational-geometry"
],
"Title": "Find overlapping area of octagons"
}
|
230524
|
<p>I learn about OS development and follow the tutorial <a href="https://wiki.osdev.org/Bare_Bones" rel="noreferrer">Bare Bones</a> on OSDev. And I did some extra tasks from the Moving Forward section.</p>
<p>I would like to get any suggestion about code improvement, especially about the Makefile and the <a href="https://github.com/Eanmos/kernel/tree/725bbf282c8f9065458ed39188e2ec9d7f2a58d7" rel="noreferrer">project</a> layout on GitHub.</p>
<p><strong><code>kernel.c</code></strong>:</p>
<pre class="lang-c prettyprint-override"><code>#include "string.h"
#include "vga.h"
#include "terminal.h"
void KernelMain(void)
{
Terminal_Init();
Terminal_SetColor(Vga_CreateEntryColor(VGA_COLOR_LIGHT_BLUE, VGA_COLOR_BLACK));
Terminal_Write("Hello, World!");
}
</code></pre>
<p><strong><code>string.h</code></strong>:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef STRING_H
#define STRING_H
#include <stddef.h>
size_t strlen(const char *);
#endif
</code></pre>
<p><strong><code>string.c</code></strong>:</p>
<pre class="lang-c prettyprint-override"><code>#include "string.h"
/*
===============
strlen
===============
*/
size_t strlen(const char* s)
{
size_t length = 0;
while (s[length])
length++;
return length;
}
</code></pre>
<p><strong><code>vga.h</code></strong>:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef VGA_H
#define VGA_H
#include <stdint.h>
#include <stddef.h>
#define VGA_TEXT_MODE_BUFFER_ADDRESS ((VgaEntryChar *) 0xB8000)
#define VGA_WIDTH 80
#define VGA_HEIGHT 26
enum VgaColor {
VGA_COLOR_BLACK,
VGA_COLOR_BLUE,
VGA_COLOR_GREEN,
VGA_COLOR_CYAN,
VGA_COLOR_RED,
VGA_COLOR_MAGENTA,
VGA_COLOR_BROWN,
VGA_COLOR_LIGHT_GREY,
VGA_COLOR_DARK_GREY,
VGA_COLOR_LIGHT_BLUE,
VGA_COLOR_LIGHT_GREEN,
VGA_COLOR_LIGHT_CYAN,
VGA_COLOR_LIGHT_RED,
VGA_COLOR_LIGHT_MAGENTA,
VGA_COLOR_LIGHT_BROWN,
VGA_COLOR_WHITE
};
typedef uint8_t VgaEntryColor;
typedef uint16_t VgaEntryChar;
VgaEntryColor Vga_CreateEntryColor(enum VgaColor, enum VgaColor);
VgaEntryChar Vga_CreateEntryChar(char, VgaEntryColor);
void Vga_PutEntryChar(VgaEntryChar, size_t, size_t);
char Vga_GetCharacterFromEntryChar(VgaEntryChar);
#endif
</code></pre>
<p><strong><code>vga.c</code></strong>:</p>
<pre class="lang-c prettyprint-override"><code>#include "vga.h"
/*
===============
Vga_CreateEntryColor
===============
*/
VgaEntryColor Vga_CreateEntryColor(enum VgaColor fg, enum VgaColor bg)
{
return fg | bg << 4;
}
/*
===============
Vga_CreateEntryChar
===============
*/
VgaEntryChar Vga_CreateEntryChar(char c, VgaEntryColor color)
{
return (VgaEntryChar) c | (VgaEntryChar) color << 8;
}
/*
===============
Vga_PutEntryChar
===============
*/
void Vga_PutEntryChar(VgaEntryChar c, size_t x, size_t y)
{
VGA_TEXT_MODE_BUFFER_ADDRESS[y * VGA_WIDTH + x] = c;
}
/*
===============
Vga_GetCharacterFromEntryChar
===============
*/
char Vga_GetCharacterFromEntryChar(VgaEntryChar c)
{
return c & 0x00FF;
}
</code></pre>
<p><strong><code>terminal.h</code></strong>:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef TERMINAL_H
#define TERMINAL_H
#include <stdint.h>
#include <stddef.h>
#include "vga.h"
/* Terminal width should always equals to VGA_WIDTH. */
#define TERMINAL_WIDTH VGA_WIDTH
#define TERMINAL_HEIGHT 1000
void Terminal_Init(void);
void Terminal_Write(const char *);
void Terminal_SetColor(VgaEntryColor);
void Terminal_PutChar(char);
void Terminal_Clear(void);
#endif
</code></pre>
<p><strong><code>terminal.c</code></strong>:</p>
<pre class="lang-c prettyprint-override"><code>#include "terminal.h"
struct Terminal {
size_t row, column;
VgaEntryColor color;
VgaEntryChar backBuffer[TERMINAL_HEIGHT][TERMINAL_WIDTH];
} terminal = {
0, 0,
0,
{{0}}
};
static void PutCharToBackBuffer(VgaEntryChar);
static void PutCharToBackBufferAtCoordinates(VgaEntryChar, size_t, size_t);
static void DisplayBackBuffer(void);
static VgaEntryChar GetCharFromBackBuffer(size_t, size_t);
static void ClearBackBuffer(void);
static void GoToNewLineInBackBuffer(void);
/*
===============
Terminal_Init
===============
*/
void Terminal_Init(void)
{
Terminal_SetColor(Vga_CreateEntryColor(VGA_COLOR_LIGHT_GREY, VGA_COLOR_BLACK));
Terminal_Clear();
}
/*
===============
Terminal_Clear
===============
*/
void Terminal_Clear(void)
{
ClearBackBuffer();
DisplayBackBuffer();
}
/*
===============
ClearBackBuffer
===============
*/
static void ClearBackBuffer(void)
{
const VgaEntryChar c = Vga_CreateEntryChar(' ', Vga_CreateEntryColor(VGA_COLOR_LIGHT_GREY, VGA_COLOR_BLACK));
for (size_t y = 0; y < TERMINAL_HEIGHT; ++y)
for (size_t x = 0; x < TERMINAL_WIDTH; ++x)
PutCharToBackBuffer(c);
terminal.row = 0;
terminal.column = 0;
}
/*
===============
PutCharToBackBuffer
Puts a colored character to the back buffer on the current cursor position.
If there is no line space left, the cursor moves to the new line. If there
is no vertical space, the cursor moves to the first line.
===============
*/
static void PutCharToBackBuffer(VgaEntryChar c)
{
if (Vga_GetCharacterFromEntryChar(c) == '\n') {
GoToNewLineInBackBuffer();
} else {
PutCharToBackBufferAtCoordinates(c, terminal.column, terminal.row);
if (++terminal.column == TERMINAL_WIDTH)
GoToNewLineInBackBuffer();
}
}
/*
===============
GoToNewLineInBackBuffer
===============
*/
static void GoToNewLineInBackBuffer(void)
{
terminal.column = 0;
if (++terminal.row == TERMINAL_HEIGHT)
terminal.row = 0;
}
/*
===============
PutCharToBackBufferAtCoordinates
===============
*/
static void PutCharToBackBufferAtCoordinates(VgaEntryChar c, size_t x, size_t y)
{
terminal.backBuffer[y][x] = c;
}
/*
===============
DisplayBackBuffer
===============
*/
static void DisplayBackBuffer(void)
{
const size_t offset = terminal.row > VGA_HEIGHT ? terminal.row - VGA_HEIGHT : 0;
for (size_t y = 0; y < VGA_HEIGHT; ++y)
for (size_t x = 0; x < VGA_WIDTH; ++x)
Vga_PutEntryChar(GetCharFromBackBuffer(x, y + offset), x, y);
}
/*
===============
Terminal_SetColor
===============
*/
void Terminal_SetColor(VgaEntryColor c)
{
terminal.color = c;
}
/*
===============
Terminal_Write
===============
*/
void Terminal_Write(const char *s)
{
while (*s)
Terminal_PutChar(*s++);
DisplayBackBuffer();
}
/*
===============
Terminal_PutChar
===============
*/
void Terminal_PutChar(char c)
{
PutCharToBackBuffer(Vga_CreateEntryChar(c, terminal.color));
DisplayBackBuffer();
}
/*
===============
GetCharFromBackBuffer
===============
*/
static VgaEntryChar GetCharFromBackBuffer(size_t x, size_t y)
{
return terminal.backBuffer[y][x];
}
</code></pre>
<p><strong><code>Makefile</code></strong>:</p>
<pre><code>#
# Compiler and assembler options
#
CC = i686-elf-gcc
AS = i686-elf-as
CFLAGS = -std=c99 -ffreestanding -nostdlib -O0 -Wall -Wextra -pedantic
#
# Project's hierarchy
#
SRCDIR = src
BINDIR = bin
BINARY = kernel.bin
ISODIR = isodir
RESULTING_ISO = kernel.iso
#
# Colored printing
#
BLUE_COLOR = $(shell tput setaf 4)
GREEN_COLOR = $(shell tput setaf 2)
RESET_COLOR = $(shell tput sgr0)
BOLD = $(shell tput bold)
OFFBOLD = $(shell tput rmso)
MESSAGE_BEGIN = ${BOLD}${GREEN_COLOR}
MESSAGE_END = ${RESET_COLOR}${OFFBOLD}
.PHONY: clean makeiso run
${BINDIR}/${BINARY}: boot.o kernel.o string.o vga.o terminal.o
${info }
${info ${MESSAGE_BEGIN}Binary is linking...${MESSAGE_END}}
${CC} -T linker.ld ${CFLAGS} $^ -o $@ -lgcc
boot.o: ${SRCDIR}/boot.s
${info ${MESSAGE_BEGIN}boot.s is compiling...${MESSAGE_END}}
${AS} $< -o $@
kernel.o: ${SRCDIR}/kernel.c
${info }
${info ${MESSAGE_BEGIN}kernel.c is compiling...${MESSAGE_END}}
${CC} ${CFLAGS} -c $< -o $@
string.o: ${SRCDIR}/string.c ${SRCDIR}/string.h
${info }
${info ${MESSAGE_BEGIN}string.c is compiling...${MESSAGE_END}}
${CC} ${CFLAGS} -c $< -o $@
vga.o: ${SRCDIR}/vga.c ${SRCDIR}/vga.h
${info }
${info ${MESSAGE_BEGIN}vga.c is compiling...${MESSAGE_END}}
${CC} ${CFLAGS} -c $< -o $@
terminal.o: ${SRCDIR}/terminal.c ${SRCDIR}/terminal.h
${info }
${info ${MESSAGE_BEGIN}terminal.c is compiling...${MESSAGE_END}}
${CC} ${CFLAGS} -c $< -o $@
clean: ${BINDIR}/${BINARY}
rm -rf *.o
makeiso: ${BINDIR}/${BINARY}
${info }
${info ${MESSAGE_BEGIN}Making an ISO...${MESSAGE_END}}
cp ${BINDIR}/${BINARY} ${ISODIR}/boot/
grub-mkrescue ${ISODIR} -o ${RESULTING_ISO}
run: makeiso
${info }
${info ${MESSAGE_BEGIN}Running the ISO...${MESSAGE_END}}
qemu-system-x86_64 --cdrom ${RESULTING_ISO}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:47:40.390",
"Id": "449191",
"Score": "0",
"body": "Where does `boot.s` come from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:44:35.080",
"Id": "449254",
"Score": "0",
"body": "@TobySpeight, `boot.s` is the same as the Bare Bone's `boot.s`. I did not add it in order to keep the question text as minimal as possible."
}
] |
[
{
"body": "\n<h2>Makefile review</h2>\n<p>We're missing the instruction to tell Make to remove partial results from failing rules; all Makefiles should somewhere contain</p>\n<pre class=\"lang-make prettyprint-override\"><code>.DELETE_ON_ERROR:\n</code></pre>\n<p><code>makeiso</code> is never up to date. We don't want to re-run it unless the binary has changed, so I'd write:</p>\n<pre class=\"lang-make prettyprint-override\"><code>makeiso: $(RESULTING_ISO)\n\n$(RESULTING_ISO): $(BINDIR)/$(BINARY)\n $(info )\n $(info $(MESSAGE_BEGIN)Making an ISO...$(MESSAGE_END))\n cp $(BINDIR)/$(BINARY) $(ISODIR)/boot/\n grub-mkrescue $(ISODIR) -o $(RESULTING_ISO)\n</code></pre>\n<p>Why does <code>clean</code> depend on having built the binary? I think it should have no dependencies. We could also use the built-in <code>$(RM)</code> rather than writing <code>rm -f</code>.</p>\n<p>There's a lot of repetition in the compilation rules:</p>\n<blockquote>\n<pre class=\"lang-make prettyprint-override\"><code>boot.o: ${SRCDIR}/boot.s\n ${info ${MESSAGE_BEGIN}boot.s is compiling...${MESSAGE_END}}\n ${AS} $< -o $@\n\nkernel.o: ${SRCDIR}/kernel.c\n ${info }\n ${info ${MESSAGE_BEGIN}kernel.c is compiling...${MESSAGE_END}}\n ${CC} ${CFLAGS} -c $< -o $@\n\nstring.o: ${SRCDIR}/string.c ${SRCDIR}/string.h\n ${info }\n ${info ${MESSAGE_BEGIN}string.c is compiling...${MESSAGE_END}}\n ${CC} ${CFLAGS} -c $< -o $@\n</code></pre>\n</blockquote>\n<p>We're duplicating much of what's built-in to make. If we add <code>$(SRCDIR)</code> to the <code>vpath</code>, then we can replace those three rules with just:</p>\n<pre class=\"lang-make prettyprint-override\"><code>string.o: string.h\n</code></pre>\n<p>(Note that there are many more header dependencies not yet mentioned in the rules - but instead of writing them by hand, we should make ourselves a dependency generator here.)</p>\n<p>If we really need the fancy printing, then we could override the built-in rules; e.g. for the C sources:</p>\n<pre class=\"lang-make prettyprint-override\"><code>%.o: %.c\n $(info )\n $(info $(MESSAGE_BEGIN)$< is compiling...$(MESSAGE_END))\n $(COMPILE.c) $(OUTPUT_OPTION) $<\n</code></pre>\n<p>The link line can easily be make to work with the built-in rules:</p>\n<pre class=\"lang-make prettyprint-override\"><code>LDFLAGS =+ -T linker.ld\nLDLIBS += -lgcc\n${BINDIR}/${BINARY}: boot.o kernel.o string.o vga.o terminal.o\n $(LINK.o) $^ $(LDLIBS) -o $@\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:46:57.333",
"Id": "230537",
"ParentId": "230530",
"Score": "6"
}
},
{
"body": "<p>To complement the Makefile review, here are a few more points that may help you improve your program.</p>\n\n<h2>Use <code>VPATH</code></h2>\n\n<p><code>make</code> already has a number of builtin rules that could be used for this project with no loss of generality. If you omit the colored printing (which I would advocate) and use <code>VPATH</code>, you could use replace most of your <code>Makefile</code> with a single rule:</p>\n\n<pre><code>VPATH = src\n${BINDIR}/${BINARY}: boot.o kernel.o string.o vga.o terminal.o\n ${CC} -T linker.ld ${CFLAGS} $^ -o $@ -lgcc\n</code></pre>\n\n<h2>Add missing dependencies</h2>\n\n<p>The iso image is dependent on the configuration file as well as the kernel image, so I'd add that file to the <code>Makefile</code> rule.</p>\n\n<h2>Specify flags using standard variables</h2>\n\n<p>The compiler uses <code>CFLAGS</code> and the assembler uses <code>ASFLAGS</code> by default. Set those variables and simplify your <code>Makefile</code>.</p>\n\n<h2>Reorder your targets</h2>\n\n<p>Remember that the first target is the default one run if <code>make</code> is invoked with no arguments. For that reason, I'd recommend that the iso image file rule, which is the most derived rule that is a real target, should be first, followed by the target for the kernel, followed by the <code>.PHONY</code> targets.</p>\n\n<h2>Create a list of objects</h2>\n\n<p>Best practice for a project like this is to use a variable for the created objects like this:</p>\n\n<pre><code>OBJECTS = boot.o kernel.o string.o vga.o terminal.o\n</code></pre>\n\n<p>This can then be used for both the kernel target and the <code>clean</code> target.</p>\n\n<h2>Don't clean files you haven't created</h2>\n\n<p>While the existing rule for <code>clean</code> probably works just fine, it will also delete all <code>.o</code> files anywhere in the subtree, whether or not this <code>makefile</code> created them. Better practice is to only delete files created by this <code>makefile</code>. </p>\n\n<h2>Revised makefile</h2>\n\n<p>Using all of those suggestions, here's what I came up with:</p>\n\n<pre><code>CFLAGS = -m32 -std=c99 -ffreestanding -nostdlib -O0 -Wall -Wextra -pedantic\nASFLAGS = -32\n\nVPATH = src\n\nISODIR = isodir\nKERNEL = ${ISODIR}/boot/kernel.bin\nGRUBFCFG = ${ISODIR}/boot/grub/grub.cfg\nISO_IMAGE = kernel.iso\nOBJECTS = boot.o kernel.o string.o vga.o terminal.o\n\n.PHONY: clean run\n\n${ISO_IMAGE}: ${KERNEL} ${GRUBCFG}\n grub2-mkrescue ${ISODIR} -o ${ISO_IMAGE}\n\n${KERNEL} : ${OBJECTS}\n ${CC} -T linker.ld ${CFLAGS} $^ -o $@ -lgcc\n\nclean: \n -rm -f ${OBJECTS} ${KERNEL} ${ISO_IMAGE}\n\nrun: ${ISO_IMAGE}\n qemu-system-x86_64 --cdrom ${ISO_IMAGE}\n</code></pre>\n\n<p>Note that this uses the default compiler and assembler and changes their behavior using flags. It also builds the <code>kernel.bin</code> file where it is needed instead of introducing another step to copy it.</p>\n\n<h2>Use something more modern than plain <code>make</code></h2>\n\n<p>I'd recommend looking at <code>autotools</code> or <code>cmake</code> to use as a solid foundation for a maintainable, modern and sophisticated project. For example, neither the original nor revised <code>makefile</code> is capable of out-of-source builds which both of the mentioned tools can easily handle. Further, both support the addition of other things such as unit tests, documentation generation, and multiple types of build (e.g. debug vs. release) that, while possible to do with plain <code>make</code>, quickly becomes more effort than it's worth.</p>\n\n<h2>Use the latest standards</h2>\n\n<p>The old version of grub uses the original multiboot standard, but things have moved on since then. The current is the <a href=\"https://www.gnu.org/software/grub/manual/multiboot2/multiboot.html\" rel=\"noreferrer\">multiboot2 standard</a> which is implemented by <code>grub2</code> among others. I modified your code to use the multiboot2 standard instead in just a few minutes.</p>\n\n<h2>Consider unit tests</h2>\n\n<p>Unit testing of code provides a higher level of assurence that things are working as you intend. For that reason, I'd highly recommend getting into the habit of introducing unit tests into the code base as early as possible. One way that can be simplified is by using the next suggestion.</p>\n\n<h2>Create and use libraries</h2>\n\n<p>The <code>string.c</code> file only contains a single function at the moment but is likely to grow as your project does. One efficient way to group and maintain such functions is via the use of libraries, either shared or static. As mentioned above, this also makes unit testing simpler, since one can write tests against a library.</p>\n\n<h2>Consider using compiler optimization</h2>\n\n<p>The compiler is currently set to do no optimization (<code>-O0</code>). While it may be instructive so see what the unoptimized code looks like, modern compilers are quite good at optimization. It would be a shame to forego all of those benefits.</p>\n\n<h2>Consider efficiency and clarity</h2>\n\n<p>The code currently includes <code>Terminal_Init</code> which calls <code>Terminal_Clear</code> which calls <code>ClearBackBuffer</code> which calls <code>PutCharToBackBuffer</code> in a loop. We know for a fact that there are no newline characters in that, but the first part of every call to <code>PutCharToBackBuffer</code> checks to see if the character is a newline. I'd suggest that it would make more sense to call <code>PutCharToBackBufferAtCoordinates</code> instead at that location.</p>\n\n<h2>Use <code>static</code> where appropriate</h2>\n\n<p>Mostly, the use of <code>static</code> is appropriate within this code, but there are some other places it could and should be applied. One example is the <code>Terminal</code> struct within <code>terminal.c</code>.</p>\n\n<h2>Don't check build artifacts into version control</h2>\n\n<p>Although it's not in the code posted, I notice that the iso and bin files are checked into your <code>git</code> project. Don't do that. Version control is for <em>source</em> files, not the products of them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T10:09:27.633",
"Id": "449476",
"Score": "0",
"body": "Your answers always are great! Thank you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T20:52:06.660",
"Id": "230619",
"ParentId": "230530",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "230619",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T09:33:37.233",
"Id": "230530",
"Score": "7",
"Tags": [
"c",
"console",
"makefile"
],
"Title": "Simple VGA driver for a toy kernel"
}
|
230530
|
<p>I wanted a neat iterator that will always give me neat sequence of <code>step</code> spaced numbers. This is what I came up with, but I am a bit skeptical that I covered all cases.</p>
<pre><code>/**
* Creates numeric range iterator. The iterator will iterate between start and end.
* Start may be larger than end. The output will contain both start and end, but no value
* will appear twice.
* @param {number} start
* @param {number} end
* @param {number} step
* @yields {number}
* @returns {IterableIterator<number>}
*/
function* numrange(start = 0, end = 100, step = 1) {
if (start > end) {
step = -1 * step;
}
let i = start;
for (; shouldLoop(i); i += step) {
yield i;
if (i!=end && !shouldLoop(i + step)) {
yield end;
}
}
function shouldLoop(ival) {
return start > end ? ival >= end : ival <= end;
}
}
</code></pre>
<p>Can this be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:27:57.070",
"Id": "449185",
"Score": "0",
"body": "Does it work well and as intended for negative values passed for `end` but positive vaules of `step`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:41:34.917",
"Id": "449190",
"Score": "0",
"body": "Good question. Step must be positive, it is inverted internally if needed. And yeah, it works in that case: `[...numrange(3,-5)] ->\nArray(9) [ 3, 2, 1, 0, -1, -2, -3, -4, -5 ]`"
}
] |
[
{
"body": "<h2>Counter intuitive?</h2>\n\n<h3>Infinite loops.</h3>\n\n<p>The function is an iterator so this may not be undesired or potentially fatal for the application. However some inputs would make one wonder about the callers intent.</p>\n\n<pre><code>numrange(0, 100, 0); // will endlessly return 0\nnumrange(0, 100, -1); // will return 0, -1, -2, ... Infinity\nnumrange(0, -100, 1); // will return 0, 1, 2, ... Infinity\n</code></pre>\n\n<h3>Not part of sequence.</h3>\n\n<p>There are situation where the last value can be out of sequence</p>\n\n<pre><code>numrange(0, 4, 2); // will return 0, 2.5, 4.\n</code></pre>\n\n<p>Or two values are returned rather than one.</p>\n\n<pre><code>numrange(4, 4, 1); // will return 4, 4.\n</code></pre>\n\n<h2>Names</h2>\n\n<ul>\n<li>The function name should be <code>numRange</code> to be consistent with JS camelCase convention.</li>\n<li>The argument <code>ival</code> (should be <code>iVal</code>) in <code>shouldLoop</code> is excessive, you could just have used <code>i</code>.</li>\n<li>The function name <code>shouldLoop</code> can also be simplified as it expresses a question \"should loop?\" which can be shortened considering the context of its use to \"loop?\"</li>\n</ul>\n\n<h2>Logic and flow</h2>\n\n<p>The function <code>shouldLoop</code> is called 2 times each iteration, there is no need to do this, on top of this there are cases where the first clause of the inner statement is redundant. eg <code>numRange(0, 20, 1.01)</code> BTW use strict inequality <code>!==</code> rather than <code>!=</code></p>\n\n<p>You can improve efficiency if you removed the inner statement and yielded <code>end</code> after the loop. You would also need to change the return condition inside the function <code>shouldLoop</code> to <code>start > end ? ival > end : ival < end</code></p>\n\n<p>Each time you iterate you test if <code>start > end</code> This is known from the very start of the function and is thus repeating the same logic for no need. Use the condition to assign one of two functions and avoid the repeated logic.</p>\n\n<h2>Rewrite</h2>\n\n<p>Thus you can have the same behavior as your original code with</p>\n\n<pre><code>function* numRange(start = 0, end = 100, step = 1) {\n const loop = start > end ? (i) => i > end : (i) => i < end;\n if (start > end) { step = -1 * step }\n for (let i = start; loop(i); i += step) { \n yield i;\n }\n yield end;\n}\n</code></pre>\n\n<h2>Example</h2>\n\n<ul>\n<li>Fixing what I see as problems (as outlined at the start of the answer) \n\n<ul>\n<li>Ensure that step is in the correct direction no matter what its sign.</li>\n<li>Check if step is 0 and just return the <code>start</code> if so.</li>\n<li>Check if end is part of the sequence and ignore it if not.</li>\n</ul></li>\n<li>Using the <code>var</code> as argument <code>start</code> to count.</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>function* numRange(start = 0, end = 100, step = 1) {\n step = Math.sign(end - start) * Math.abs(step);\n if (step) {\n const loop = step > 0 ? () => start < end : () => end < start;\n while (loop()) {\n yield start;\n start += step;\n }\n if (start !== end) { return }\n }\n yield start; \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T13:15:11.750",
"Id": "230546",
"ParentId": "230534",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T10:24:37.943",
"Id": "230534",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"ecmascript-6",
"iterator"
],
"Title": "Bidirectional numeric (floating point) sequence iterator"
}
|
230534
|
<p>I took some boilerplate code that I have been using for determining an active windows user's info to either send emails with their details, or to pass to a error logging class, and encapsulated it in its own class. </p>
<p>What I would like to know about my implementation of this is: Are there more efficient ways of doing this over using <code>ADO</code> to query the directory, and should <code>ActiveWindowsSession</code> be made accessible as a <em>Predclared</em> Class?</p>
<p>The reason I ask about making it Predclared is, the active user is static as is their info, so I would think that a static implementation would be more suitable, but I am not sure. </p>
<p><strong>Class: ActiveWindowsSession</strong></p>
<pre><code>Option Explicit
Private Const CONNECTION_STRING As String = "ADsDSOObject"
Private Const CONNECTION_PROVIDER As String = "Active Directory Provider"
Private Const ADODB_OBJECT_STATE As Integer = 1 'the adStateOpen constant's value
Private Type TActiveWindowsSession
UserName As String
UserDisplayName As String
UserFirstName As String
UserLastName As String
UserCommonName As String
UserEmailAddress As String
UserTelephoneNumber As String
UserDepartment As String
CompanySiteName As String
DomainName As String
MachineName As String
WindowsVerion As String
AppVersion As String
End Type
Private this As TActiveWindowsSession
Private Sub Class_Initialize()
GetUserAttributes
GetSystemAttributes
End Sub
Private Sub Class_Terminate()
With this
.UserName = Empty
.UserDisplayName = Empty
.UserFirstName = Empty
.UserLastName = Empty
.UserCommonName = Empty
.UserEmailAddress = Empty
.UserTelephoneNumber = Empty
.UserDepartment = Empty
.CompanySiteName = Empty
.DomainName = Empty
.MachineName = Empty
.WindowsVerion = Empty
.AppVersion = Empty
End With
End Sub
Public Property Get UserName() As String
UserName = this.UserName
End Property
Public Property Get UserDisplayName() As String
UserDisplayName = this.UserDisplayName
End Property
Public Property Get UserFirstName() As String
UserFirstName = this.UserFirstName
End Property
Public Property Get UserLastName() As String
UserLastName = this.UserLastName
End Property
Public Property Get UserCommonName() As String
UserCommonName = this.UserCommonName
End Property
Public Property Get UserEmailAddress() As String
UserEmailAddress = this.UserEmailAddress
End Property
Public Property Get UserDepartment() As String
UserDepartment = this.UserDepartment
End Property
Public Property Get UserTelephoneNumber() As String
UserTelephoneNumber = this.UserTelephoneNumber
End Property
Public Property Get CompanySiteName() As String
CompanySiteName = this.CompanySiteName
End Property
Public Property Get DomainName() As String
DomainName = this.DomainName
End Property
Public Property Get MachineName() As String
MachineName = this.MachineName
End Property
Public Property Get WindowsVerion() As String
WindowsVerion = this.WindowsVerion
End Property
Public Property Get AppVersion() As String
AppVersion = this.AppVersion
End Property
Private Sub GetUserAttributes()
Dim Conn As Object, Cmnd As Object, Rcrdset As Object
Dim rootDSE As Object
Dim Base As String, Filter As String, _
UserAttributes As String
Dim UserName As String
Const Scope As String = "subtree"
this.UserName = VBA.Environ$("Username")
On Error GoTo CleanFail
Set rootDSE = GetObject("LDAP://RootDSE")
Base = "<LDAP://" & rootDSE.Get("defaultNamingContext") & ">"
'filter on user objects with the given account name
Filter = "(&(objectClass=user)(objectCategory=Person)"
Filter = Filter & "(sAMAccountName=" & this.UserName & "))"
UserAttributes = "physicalDeliveryOfficeName,department,displayName," & _
"givenName,sn,mail,telephoneNumber"
Set Conn = CreateObject("ADODB.Connection")
Conn.Provider = CONNECTION_STRING
Conn.Open CONNECTION_PROVIDER
Set Cmnd = CreateObject("ADODB.Command")
Set Cmnd.ActiveConnection = Conn
Cmnd.CommandText = Base & ";" & Filter & ";" _
& UserAttributes & ";" & Scope
Set Rcrdset = Cmnd.Execute
If Rcrdset.EOF Then GoTo CleanExit
'at times, some of these fields aren't supported so
'so I am usesing on error resume next to avoid any errors
'thrown by and empty field value
On Error Resume Next
With this
.CompanySiteName = Rcrdset.Fields("physicalDeliveryOfficeName").value
.UserDepartment = Rcrdset.Fields("department").value
.UserDisplayName = Rcrdset.Fields("displayName").value
.UserFirstName = Rcrdset.Fields("givenName").value
.UserLastName = Rcrdset.Fields("sn").value
.UserCommonName = Trim$(.UserFirstName & " " & .UserLastName)
.UserEmailAddress = Rcrdset.Fields("mail").value
.UserTelephoneNumber = Rcrdset.Fields("telephoneNumber").value
End With
CleanExit:
CleanUpADODBObjects Conn, Rcrdset
Exit Sub
CleanFail:
Resume CleanExit
End Sub
Private Sub GetSystemAttributes()
With this
.DomainName = LCase$(Environ$("USERDNSDOMAIN"))
.MachineName = Environ$("COMPUTERNAME")
.WindowsVerion = Application.OperatingSystem
.AppVersion = Application.Version
End With
End Sub
Public Sub PrintToImmediateWindow()
With this
Debug.Print "Windows Verion: "; Tab(20); .WindowsVerion
Debug.Print "App Version: "; Tab(20); .AppVersion
Debug.Print "Machine Name: "; Tab(20); .MachineName
Debug.Print "Site Name: "; Tab(20); .CompanySiteName
Debug.Print "Domain DNS Name: "; Tab(20); .DomainName
Debug.Print "User Name: "; Tab(20); .UserName
Debug.Print "Display Name: "; Tab(20); .UserDisplayName
Debug.Print "First Name: "; Tab(20); .UserFirstName
Debug.Print "Last Name: "; Tab(20); .UserLastName
Debug.Print "Common Name: "; Tab(20); .UserCommonName
Debug.Print "Email Address: "; Tab(20); .UserEmailAddress
End With
End Sub
Private Sub CleanUpADODBObjects(ByRef ConnectionIn As Object, ByRef RecordsetIn As Object)
'bit-wise comparison
If Not ConnectionIn Is Nothing Then
If (ConnectionIn.State And ADODB_OBJECT_STATE) = ADODB_OBJECT_STATE Then
ConnectionIn.Close
End If
End If
Set ConnectionIn = Nothing
If Not RecordsetIn Is Nothing Then
If (RecordsetIn.State And ADODB_OBJECT_STATE) = ADODB_OBJECT_STATE Then
RecordsetIn.Close
End If
End If
Set RecordsetIn = Nothing
End Sub
</code></pre>
<p><strong>Usage:</strong> </p>
<pre><code>Sub TestingWindowsSession()
Dim WinSession As ActiveWindowsSession
Set WinSession = New ActiveWindowsSession
WinSession.PrintToImmediateWindow
End Sub
</code></pre>
<p>The immediate window: </p>
<p><a href="https://i.stack.imgur.com/M2Y24.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M2Y24.png" alt="enter image description here"></a></p>
|
[] |
[
{
"body": "<p>Very clean code, reads very nicely, well done!</p>\n\n<p>Watch for inconsistencies in indentation:</p>\n\n<blockquote>\n<pre><code>Public Sub PrintToImmediateWindow()\n\n With this\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code>Private Sub GetSystemAttributes()\n With this\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://www.rubberduckvba.com/\" rel=\"nofollow noreferrer\">Rubberduck</a> can fix that for you (across the entire project) with a single click.</p>\n\n<p>Consistent indentation is normally understood as \"executable statements within a code block are all lined up\". I don't see code blocks here, and yet I'm looking at 3 levels of indentation:</p>\n\n<blockquote>\n<pre><code> Const Scope As String = \"subtree\"\n\n this.UserName = VBA.Environ$(\"Username\")\n\n On Error GoTo CleanFail\n Set rootDSE = GetObject(\"LDAP://RootDSE\")\n\n Base = \"<LDAP://\" & rootDSE.Get(\"defaultNamingContext\") & \">\"\n</code></pre>\n</blockquote>\n\n<p>That's distracting.</p>\n\n<p>So is having a block of declarations at the top of a procedure scope, and/or having multiple declarations in a single instruction:</p>\n\n<blockquote>\n<pre><code>Dim Conn As Object, Cmnd As Object, Rcrdset As Object\nDim rootDSE As Object\nDim Base As String, Filter As String, _\n UserAttributes As String\nDim UserName As String\n</code></pre>\n</blockquote>\n\n<p>Of particular note, the line-continuated <code>UserAttributes</code> makes me wonder <em>why</em> that one had to be on its own line (while still being part of the previous <code>Dim</code> statement): I shouldn't have to ask myself these questions when reading code. Also disemvoweling (removing random vowels) should not be needed.</p>\n\n<blockquote>\n<pre><code>Dim Conn As Object, Cmnd As Object, Rcrdset As Object\n</code></pre>\n</blockquote>\n\n<p>I'm not a zealot, so to me <code>Dim db As Object</code>, <code>Dim cmd As Object</code>, and <code>Dim rs As Object</code> would be fine (as long as the declarations are right next to where they're set, so there's more context to it than just \"well it's an object\"), but <code>Rcrdset</code> is extremely typo-prone (kudos for <code>Option Explicit</code> to pick that up!).</p>\n\n<p>Contrast to how seamless reading becomes, if declarations are right where they're relevant:</p>\n\n<pre><code>Dim rootDSE As Object\nSet rootDSE = GetObject(\"LDAP://RootDSE\")\n\nDim base As String '<~ casing\nbase = \"<LDAP://\" & rootDSE.Get(\"defaultNamingContext\") & \">\"\n\nDim filter As String '<~ casing\nfilter = \"(&(objectClass=user)(objectCategory=Person)\"\n\n'..\n\nDim conn As Object '<~ casing\nSet conn = CreateObject(\"ADODB.Connection\")\n</code></pre>\n\n<p>I know this is harder to do in a case-insensitive language, but using <code>PascalCase</code> for <em>some</em> local variables, and <code>camelCase</code> for others, is also inconsistent and distracting, readability-wise.</p>\n\n<p>A note about this:</p>\n\n<blockquote>\n<pre><code> 'at times, some of these fields aren't supported so\n 'so I am usesing on error resume next to avoid any errors\n 'thrown by and empty field value\n On Error Resume Next\n With this\n .CompanySiteName = Rcrdset.Fields(\"physicalDeliveryOfficeName\").value\n .UserDepartment = Rcrdset.Fields(\"department\").value\n .UserDisplayName = Rcrdset.Fields(\"displayName\").value\n .UserFirstName = Rcrdset.Fields(\"givenName\").value\n .UserLastName = Rcrdset.Fields(\"sn\").value\n .UserCommonName = Trim$(.UserFirstName & \" \" & .UserLastName)\n .UserEmailAddress = Rcrdset.Fields(\"mail\").value\n .UserTelephoneNumber = Rcrdset.Fields(\"telephoneNumber\").value\n End With\n</code></pre>\n</blockquote>\n\n<p>It's not wrong, but it's not ideal either. Consider extracting the OERN into its own reduced scope:</p>\n\n<pre><code>Private Function GetFieldValueOrDefault(ByVal rs As Recordset, ByVal fieldName As String) As Variant\n On Error Resume Next\n GetFieldValueOrDefault = rs.Fields(fieldName).Value\n On Error GoTo 0\nEnd Function\n</code></pre>\n\n<p>There's a bunch of implicit conversions happening here:</p>\n\n<blockquote>\n<pre><code>Private Sub Class_Terminate()\n With this\n .UserName = Empty\n .UserDisplayName = Empty\n .UserFirstName = Empty\n .UserLastName = Empty\n .UserCommonName = Empty\n .UserEmailAddress = Empty\n .UserTelephoneNumber = Empty\n .UserDepartment = Empty\n .CompanySiteName = Empty\n .DomainName = Empty\n .MachineName = Empty\n .WindowsVerion = Empty\n .AppVersion = Empty\n End With\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p><code>Empty</code> is a special type in VBA, that works with <code>Variant</code>: <code>vbEmpty</code> would be the constant for it, but then if you assign <code>vbEmpty</code> to a <code>String</code> value, you're implicitly converting <code>Variant/Empty</code> to <code>String</code>, and so the value that ends up being assigned is <code>\"\"</code> - note that the implicit conversion is making an implicit allocation; the value of <code>StrPtr(Empty)</code> will be different for every single call - meanwhile the value of <code>StrPtr(vbNullString)</code> is <code>0</code>, i.e. using <code>= vbNullString</code> instead of <code>= Empty</code> would remove the implicit conversions <em>and</em> the intermediate memory allocations.</p>\n\n<p>I'm not sure what to think of <code>CleanUpADODBObjects</code>: on one hand I can appreciate taking that concern out of the calling procedure, on the other I can't help but wave a red flag when an object is being destroyed in another scope than the scope it was created in. This could be because <code>GetUserAttributes</code> is responsible for too many things. Also, an error in that scope can result in an infinite loop:</p>\n\n<blockquote>\n<pre><code>CleanExit:\n CleanUpADODBObjects Conn, Rcrdset '<~ raises an error, goto cleanfail\n Exit Sub\n\nCleanFail:\n Resume CleanExit '<~ ok, but if CleanUpADODBObjects raises an error...\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T21:43:49.790",
"Id": "449307",
"Score": "0",
"body": "Why you you would clear a variable in `Class_Terminate`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T21:45:10.090",
"Id": "449308",
"Score": "0",
"body": "@TinMan Good point: I wouldn't - at least not for a `String` (or any other kind of non-problematic reference) value"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T21:55:01.220",
"Id": "449311",
"Score": "0",
"body": "Hmm... that the `t as TypeA` had object field, `newT as TypA : t = NewT` should still reset all the fields. Correct? Better question, when a Open ADODB.Connection fails out of scope is it automatically closed? Is there a why to test the number of open ADODB.Connections?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:02:56.310",
"Id": "449313",
"Score": "0",
"body": "Client-side, I would think if the object falls out of scope, it's destroyed (and yes, closed)... but bugs in the implementation can keep this from happening. I'd monitor connections server-side, see if they're left lingering, and adjust accordingly. In any case I wouldn't `Set foo = Nothing` explicitly without a solid reason to do so (and a comment explaining why it's needed)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:13:55.157",
"Id": "449316",
"Score": "0",
"body": "I never gave much thought to bugs in the implementation, makes sense. I know that I have been victimized by them in the past. `Rem No foo for you` ..seems appropriate Thanks for your time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T17:22:06.747",
"Id": "449391",
"Score": "0",
"body": "@MathieuGuindon \"Very clean code, reads very nicely, well done!\"- Coming from you that means a lot, thank you! Excellent points on my code formatting, variable naming convention, and declaration style. These are all things that I struggle with and I need to adhere to a common standard. As for `CleanUpADODBObjects`, I wrote that just before posting this, thinking that it would make `GetUserAttributes` look less cluttered, but you are very much correct in saying that the destruction of an object should be handled within its scope. Great point on the implicit conversions as well!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:26:36.533",
"Id": "230564",
"ParentId": "230545",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230564",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T12:36:28.650",
"Id": "230545",
"Score": "4",
"Tags": [
"vba",
"windows",
"active-directory",
"adodb"
],
"Title": "Getting Windows User Info From The Active Directory"
}
|
230545
|
<p>I have previously worked on this program in <a href="https://codereview.stackexchange.com/questions/226782/javarpn-calculator">this question</a>, and have gotten some very good answers and help! Now, I have done some more work on the program, and would love if you could give me honest feedback on what I need to change.</p>
<h1>Main</h1>
<pre class="lang-java prettyprint-override"><code>package owl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Stack<Double> stack = new Stack<Double>();
System.out.println("JavaRPN: Input numbers and operands separated by newline or space");
while (true) {
try {
String input = reader.readLine().toLowerCase();
RPNcli.parse(input, stack);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
</code></pre>
<p>This class just gets the input and passes it into the parse class. I think I am not using the Object Oriented part here correctly, with separating the program into the Main and RPNcli classes...</p>
<h1>RPNcli</h1>
<pre class="lang-java prettyprint-override"><code>package owl;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
public class RPNcli {
public static void parse(String input, Stack<Double> stack) {
String[] parts = input.split(" ");
for (int i = 0; i < parts.length; i++) {
Double num = isNumber(parts[i]);
if (num != null) {
stack.push(num);
} else
operation(parts[i], stack);
}
}
private static void operation(String input, Stack<Double> stack) {
Set<String> simples = new HashSet<>(Arrays.asList("+", "-", "*", "/", "^"));
Set<String> functions = new HashSet<>(Arrays.asList("sin", "cos", "tan", "asin", "acos", "atan", "sq"));
Set<String> commands = new HashSet<>(Arrays.asList("p", "e", "c", "pop", "swap"));
if (simples.contains(input)) {
simple(input, stack);
} else if (functions.contains(input)) {
function(input, stack);
} else if (commands.contains(input)) {
command(input, stack);
} else {
System.out.println("ERROR: Invalid Command");
}
}
private static void command(String input, Stack<Double> stack) {
DecimalFormat df = new DecimalFormat("#,###.#########");
switch (input) {
case "e":
System.exit(0);
break;
case "p":
if (stack.size() > 0) {
System.out.println(df.format(stack.peek()));
} else
System.out.println("ERROR: no stacks to peek");
break;
case "c":
stack.clear();
break;
case "pop":
if (stack.size() > 0) {
stack.pop();
} else
System.out.println("ERROR: no stacks to pop");
break;
case "swap":
if (stack.size() > 1) {
double num2 = stack.pop();
double num1 = stack.pop();
stack.push(num2);
stack.push(num1);
} else
System.out.println("ERROR: can't swap empty stack");
}
}
private static void function(String input, Stack<Double> stack) {
if (stack.size() > 0) {
double num = stack.pop();
double rads = Math.toRadians(num);
double ans = 0;
switch (input) {
case "sq":
ans = num * num;
case "sin":
ans = Math.sin(rads);
break;
case "cos":
ans = Math.cos(rads);
break;
case "tan":
ans = Math.tan(rads);
break;
case "asin":
ans = Math.asin(rads);
break;
case "acos":
ans = Math.acos(rads);
break;
case "atan":
ans = Math.atan(rads);
break;
}
stack.push(ans);
} else
System.out.println("ERROR: can't operate on empty stack");
}
private static void simple(String input, Stack<Double> stack) {
if (stack.size() > 1) {
double num2 = stack.pop();
double num1 = stack.pop();
double ans = 0;
switch (input) {
case "+":
ans = num1 + num2;
break;
case "-":
ans = num1 - num2;
break;
case "*":
ans = num1 * num2;
break;
case "/":
ans = num1 / num2;
break;
case "^":
ans = Math.pow(num1, num2);
break;
}
stack.push(ans);
} else
System.out.println("ERROR: can't operate on empty stack");
}
private static Double isNumber(String input) {
try {
double num = Double.parseDouble(input);
return num;
} catch (NumberFormatException n) {
return null;
}
}
}
</code></pre>
<p>Here the input is parsed and all of the operations happen, based on the data parsed. I think maybe I could split this class into two classes called "Parser" and "Calculator". Please give me your opinion on this, I really want to learn how to do this better.</p>
<p>P.S. If you'd rather look at the code on GitHub or clone to run it, here is the GitHub <a href="https://github.com/ViceroyFaust/JavaRPN" rel="nofollow noreferrer">page</a>.</p>
|
[] |
[
{
"body": "<h2>Bugs</h2>\n\n<p>The input to <code>asin</code>, <code>acos</code>, and <code>atan</code> is not radians. That is the output unit. <code>sin(30°) == sin(π/2) == 0.5</code>. Converting the input to radians makes sense. <code>asin(0.5) == π/2 == 30°</code>. You should call <code>toDegrees</code> on the output, not <code>toRadians</code> on the input.</p>\n\n<p>Fall-through causes <code>\"sq\"</code> to produce <code>sin(rads)</code> instead:</p>\n\n<pre><code> case \"sq\":\n ans = num * num;\n case \"sin\":\n ans = Math.sin(rads);\n break;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T20:31:45.703",
"Id": "449409",
"Score": "0",
"body": "Thank you so much! Somehow I did not realise I forgot to put a break on sq. Also, but isn't 30 degrees to pi/2 going to produce the same output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T22:01:51.230",
"Id": "449418",
"Score": "0",
"body": "30° is the number `30.0`; π/2 is the number `1.57079632679...`. Those are quite different floating point values. `Math.toRadians(30.0) = 1.57079...`, `Math.sin(1.57979...) = 0.5`, `Math.asin(0.5) = 1.57079...`, and `Math.toDegrees(1.57079...) = 30.0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T00:02:17.073",
"Id": "449433",
"Score": "0",
"body": "Oh, thank you for the clarification! I will fix that asap. @AJNeufeld"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T04:59:38.337",
"Id": "230584",
"ParentId": "230548",
"Score": "4"
}
},
{
"body": "<p>As you already said, it is a good idea separate commands from maths operations with the creation of two classes , I made two classes to give you a rough idea. In your <code>Main</code> class you can use <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">Try with resources</a> construct with your buffer, below the code</p>\n\n<p><strong>Main.java</strong></p>\n\n<pre><code>public class Main {\n\n public static void main(String[] args) {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {\n System.out.println(\"JavaRPN: Input numbers and operands separated by newline or space\");\n RpnCli cli = new RpnCli();\n while (true) {\n String input = reader.readLine().toLowerCase();\n cli.parse(input);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n\n<p>You can see I created a <code>RpnCli</code> instance to avoid <code>static</code> method (I put static just the set of commands for possible future purposes). I updated the <code>RpnCli</code> class in the followind way:</p>\n\n<p><strong>RpnCli.java</strong></p>\n\n<pre><code>import java.util.ArrayDeque;\nimport java.util.Arrays;\nimport java.util.Deque;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class RpnCli {\n private final static Set<String> commands = new HashSet<>(Arrays.asList(\"p\", \"e\", \"c\", \"pop\", \"swap\"));\n private Deque<Double> stack;\n private Calculator calculator;\n\n public RpnCli() {\n this.stack = new ArrayDeque<>();\n this.calculator = new Calculator(stack);\n }\n\n public void parse(String input) {\n String[] parts = input.split(\" \");\n for (int i = 0; i < parts.length; i++) {\n try {\n Double num = Double.parseDouble(input);\n stack.push(num);\n } catch (NumberFormatException ex) { \n operation(parts[i]);\n }\n }\n }\n\n private void operation(String input) {\n if (calculator.contains(input)) {\n calculator.calculate(input);\n } else {\n if (commands.contains(input)) {\n command(input);\n } else {\n System.out.println(\"ERROR: Invalid Command\");\n }\n }\n }\n\n private void command(String input) { /*omitted for brevity*/ }\n}\n</code></pre>\n\n<p>I divided math operations from command operations, so I created a new class <code>Calculator</code> for math operations that in its constructor has as its parameter the stack you use for all operations. You can see I used <code>Deque</code> class for variable <code>stack</code> because <code>Stack</code> java class is less complete compared to it. I also modified your <code>parse</code> method so if the input is not a <code>double</code> value will be parsed by <code>operation</code> method as you already made in your code. \nI added a new class called Calculator, below the code:</p>\n\n<p><strong>Calculator.java</strong></p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Deque;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class Calculator {\n private final static Set<String> simples = new HashSet<>(Arrays.asList(\"+\", \"-\", \"*\", \"/\", \"^\"));\n private final static Set<String> functions = new HashSet<>(Arrays.asList(\"sin\", \"cos\", \"tan\", \"asin\", \"acos\", \"atan\", \"sq\"));\n private Deque<Double> stack;\n\n public Calculator(Deque<Double> stack) {\n this.stack = stack;\n }\n\n public boolean contains(String input) {\n return simples.contains(input) || functions.contains(input);\n }\n\n public void calculate(String input) {\n if (simples.contains(input)) {\n simple(input);\n } else {\n function(input);\n }\n }\n\n private void function(String input) { /*omitted for brevity*/ }\n\n private void simple(String input) { /*omitted for brevity*/ }\n}\n</code></pre>\n\n<p>The most important thing is this class is the field <code>Stack</code> passed by the <code>RpnCli</code> class: it will no more appear as a parameter in the methods like the methods of the containing class <code>RpnCli</code> and so there is no more need of static methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T23:11:12.327",
"Id": "452150",
"Score": "0",
"body": "I know I am late, but I would like to take a look at the \"contains\" method. The calculate method decides if we are using simples if contains returns true. But contains will always return true if there is a function or a simple..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T23:17:27.190",
"Id": "452152",
"Score": "0",
"body": "And when I try to use my function and simple methods, it tells me that I \"cannot make a static reference to a non static field."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-04T11:13:53.803",
"Id": "452321",
"Score": "0",
"body": "@ViceroyFaust, the `contains` method checks if your token is a simple or a function , if you define an instance `calc` you can call like `if(calc.contains()) {calc.calculate()}`. The error is due to the fact you have a static method and you are calling inside of it an instance calc defined outside it, so you have to remove static from method."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T18:19:09.513",
"Id": "230612",
"ParentId": "230548",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230612",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T14:17:09.500",
"Id": "230548",
"Score": "4",
"Tags": [
"java",
"beginner",
"object-oriented",
"calculator"
],
"Title": "JavaRPN (Updated)"
}
|
230548
|
<p>I used the following to split sequence into batches:</p>
<pre><code>source
.Select((item, index) => new {Item = item, Index = index})
.ToLookup(x => x.Index / batchSize, x => x.Item);
</code></pre>
<p>but it requires full materialization of the sequence - memory complexity could be high.</p>
<p>Are there anything ready to be used? I think there is nothing in <code>MoreLinq</code> for that.</p>
<p>Here is a custom solution I am trying now:</p>
<pre><code>public static class Batch
{
public static IEnumerable<T[]> Split<T>(this IEnumerable<T> source, int batchSize)
{
var it = source.GetEnumerator();
for (var b = split(); b.Length > 0; b = split())
yield return b;
T[] split() => Enumerable
.Range(0, batchSize)
.TakeWhile(i => it.MoveNext())
.Select(i => it.Current)
.ToArray();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:21:20.777",
"Id": "449267",
"Score": "0",
"body": "This sounds like what you want, and there are some pretty simple answers: https://stackoverflow.com/questions/1258162/linq-how-to-group-by-maximum-number-of-items"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:05:49.890",
"Id": "449280",
"Score": "0",
"body": "@410_Gone `GroupBy` will make full sequence being materialized before going to the next group - it will try to find everything potentially matching the very first one. I would like to read no more than necessary from the source sequence to reduce memory complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:09:53.360",
"Id": "449281",
"Score": "0",
"body": "Doh, silly me. Nevermind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:16:13.367",
"Id": "449282",
"Score": "0",
"body": "@DmitryNogin morelinq Batch is what would be equivalent. It's not IEnumerable of an array it's IEnumerable of an IEnumerable but if you look at the source code it's actually an IEnumerable of an array https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/Batch.cs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:17:52.517",
"Id": "449283",
"Score": "1",
"body": "If you keeping yours you should put GetEnumerable should be put in a using statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:25:07.643",
"Id": "449284",
"Score": "1",
"body": "@CharlesNRice could you please post an answer? I will upvote :)"
}
] |
[
{
"body": "<p>Since you mentioned morelinq in your question. It does have the Batch method which is similar. It's an <code>IEnumerable<IEnumerable<TSource>></code> instead of <code>IEnumerable<TSource[]></code> but if you look at the <a href=\"https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/Batch.cs\" rel=\"nofollow noreferrer\">source code</a> it's actually an IEnumerable of an array but you can't count on that as it's an implementation detail. </p>\n\n<p>The only issue I see with your implementation is that <code>source.GetEnumerator()</code> returns back <code>IEnumerator<T></code> which implements <code>IDisposable</code> and should be wrapped in a <code>using</code> statement. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:30:39.423",
"Id": "230565",
"ParentId": "230561",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230565",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T17:56:53.197",
"Id": "230561",
"Score": "4",
"Tags": [
"c#",
"functional-programming",
"linq",
"iterator"
],
"Title": "Paginate IEnumerable<T> sequence"
}
|
230561
|
<p>This function should return a string that is comprised from all the letters in the Alphabet except the letters in a pre-defined list in alphabetical order.</p>
<p>Assuming all letters in the pre-defined list are all lowercase;</p>
<p>I came up with two ways to do this and I would like to know which way is more efficient or more 'Pythonic'.
Thanks in advance.</p>
<p><strong>The first way:</strong></p>
<pre><code>import string
def get_remaining_letters(list_of_characters):
# casting the Alphabet to a list so that it becomes mutable
list_of_all_letters = list(string.ascii_lowercase)
# looping for each character in the pre-defined list
for char in list_of_characters :
if char in list_of_all_letters: # to avoid possible errors caused by the .remove in case of a duplicate charcter in the pre-defined list
list_of_all_letters.remove(char)
return ''.join(list_of_all_letters) # returns a string
# ----------------------------------------------------------- #
pre_defined_list = ['a', 'b', 'b']
test = get_remaining_letters(pre_defined_list)
print(test)
</code></pre>
<p>output :</p>
<pre><code>>>> cdefghijklmnopqrstuvwxyz
</code></pre>
<p><strong>The second way:</strong></p>
<pre><code>import string
def get_remaining_letters(list_of_characters):
if list_of_characters == []:
return string.ascii_lowercase
else:
remaining_letters = ''
for char in string.ascii_lowercase:
if char not in list_of_characters:
remaining_letters += char
return remaining_letters
pre_defined_list = ['a', 'b', 'b']
test = get_remaining_letters(pre_defined_list)
print(test)
</code></pre>
<p>output :</p>
<pre><code>>>> cdefghijklmnopqrstuvwxyz
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T21:11:18.437",
"Id": "449302",
"Score": "0",
"body": "Each line of code was written by me, both code sets are working. I edited the question, I didn't word myself appropriately. I apologize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T21:19:53.430",
"Id": "449304",
"Score": "0",
"body": "it's okay, just making sure"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:00:06.427",
"Id": "449312",
"Score": "0",
"body": "Does the order of the returned result matter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:04:40.300",
"Id": "449314",
"Score": "0",
"body": "Yes, it needs to be in alphabetical order."
}
] |
[
{
"body": "<p>I suggest you check PEP0008 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide and Flake8 <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">http://flake8.pycqa.org/en/latest/</a> as a tool for style enforcement.</p>\n\n<ul>\n<li><strong>Docstrings:</strong> Python documentation strings or docstrings are a way of documenting your classes/function/modules and are usually accessed through <code>help()</code>. You should include docstrings to your functions indicating what they do and what they return.</li>\n<li><p><strong>Type hints:</strong> Type Annotations are a new feature added in PEP 484 that allow for adding type hints to variables. They are used to inform someone reading the code what the type of a variable should be. As you're taking a list as input and will return a string, you should have some documentation indicating that. Use type hints.</p>\n\n<p><strong>function should look like:</strong></p>\n\n<pre><code>def get_remaining_letters(letters: list) -> str:\n \"\"\"Return lowercase alphabetic letters that are not present in letters.\"\"\"\n</code></pre></li>\n<li><p><strong>Blank lines:</strong> instead of this <code># ----------------------------------------------------------- #</code> an empty line is sufficient and note that according to PEP0008 empty lines as well as comments should be used sparingly (when necessary) to separate logical sections as well as explain the not-so-obvious parts of the code.</p></li>\n<li><p><strong><code>main</code> guard</strong>: use <code>if __name__ == '__main__':</code> guard at the end of the script to allow outside modules to import this module without running it as a whole. You will be calling your functions from there.</p>\n\n<pre><code>if __name__ == '__main__':\n pre_defined_list = ['a', 'b', 'b']\n test = get_remaining_letters(pre_defined_list)\n print(test)\n</code></pre></li>\n<li><p><strong>Evaluation to empty list:</strong> In Python empty sequences evaluate to False.\ninstead of <code>if list_of_characters == []:</code> it is written: <code>if not list_of_characters:</code></p></li>\n<li><p><strong>Adding to strings:</strong> Python strings are immutable which means that each time you're adding to a string like in <code>remaining_letters += char</code> a new string is created and assigned the new value which is inefficient and should be replaced with list comprehension syntax which is shorter and more efficient or Pythonic as you call it.</p>\n\n<p><strong>An improved version of the code:</strong></p>\n\n<pre><code>import string\n\n\ndef get_remaining_letters(letters: list) -> str:\n \"\"\"Return lowercase alphabetic letters not present in letters.\"\"\"\n return ''.join(letter for letter in string.ascii_lowercase if letter not in letters)\n\n\nif __name__ == '__main__':\n chosen = [letter for letter in 'sdfmmmsvvd']\n print(get_remaining_letters(chosen))\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:16:28.470",
"Id": "449317",
"Score": "0",
"body": "You should drop your inner list `[]` from the `join`. That can accept a generator directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:19:49.340",
"Id": "449318",
"Score": "1",
"body": "Okay, I'll edit, thanks"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T21:42:27.900",
"Id": "230571",
"ParentId": "230568",
"Score": "2"
}
},
{
"body": "<p>I messed around with performance of some alternate implementations:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nfrom collections import OrderedDict\nfrom string import ascii_lowercase\nfrom timeit import timeit\n\n\ndef method_1(exclude):\n list_of_all_letters = list(ascii_lowercase)\n for char in exclude:\n if char in list_of_all_letters:\n list_of_all_letters.remove(char) \n return ''.join(list_of_all_letters)\n\n\ndef method_2(exclude):\n if exclude == []:\n return string.ascii_lowercase\n else:\n remaining_letters = ''\n for char in ascii_lowercase:\n if char not in exclude:\n remaining_letters += char\n return remaining_letters\n\n\ndef bullseye(exclude):\n return ''.join(letter for letter in ascii_lowercase if letter not in exclude)\n\n\n\nALL_LETS = set(ascii_lowercase)\n\n\ndef subtract_set(exclude):\n return ''.join(sorted(ALL_LETS - exclude))\n\n\nLET_DICT = OrderedDict((l, l) for l in ascii_lowercase)\n\n\ndef update_dict(exclude):\n lets = LET_DICT.copy()\n lets.update((l, '') for l in exclude)\n return ''.join(lets.values())\n\n\nmethods = (method_1,\n method_2,\n bullseye,\n subtract_set,\n update_dict,\n )\n\ndef test():\n for method in methods:\n assert method(set()) == 'abcdefghijklmnopqrstuvwxyz'\n assert method(set('bcd')) == 'aefghijklmnopqrstuvwxyz'\n assert method(set('abcdefghijklmnopqrstuvwxyz')) == ''\n\n\ndef time_them():\n N = 100_000\n exclude = set('abcdefghi')\n for method in methods:\n def exec():\n method(exclude) \n us = timeit(exec, number=N) * 1e6 / N\n print(f'{method.__name__:15} {us:.2f} us')\n\nif __name__ == '__main__':\n test()\n time_them()\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>method_1 3.05 us\nmethod_2 1.98 us\nbullseye 2.40 us\nsubtract_set 1.76 us\nupdate_dict 6.38 us\n</code></pre>\n\n<p>Of note:</p>\n\n<ul>\n<li>You should always be passing the exclusion argument as a <code>set</code>, not a <code>list</code>, because set membership tests are O(1) and list membership tests are O(N)</li>\n<li>@bullseye provided the typical list comprehension implementation, but it performs more poorly than your method 2, interestingly. This will vary based on Python version; I'm on 3.7.4.</li>\n<li><code>subtract_set</code> is so fast because set subtraction is itself fast, and if you hold onto a pre-constructed set for the whole alphabet, the added cost of a post-sort step is still worth it.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T17:53:54.017",
"Id": "449943",
"Score": "0",
"body": "Thanks for the help!, can you please explain why method 1 way takes more time to evaluate than method 2 ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T17:58:16.150",
"Id": "449946",
"Score": "0",
"body": "Probably the `remove` which does an O(n) search on every call"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T16:12:36.050",
"Id": "450176",
"Score": "0",
"body": "Can you please explain the method used to measure execution time ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T18:00:31.197",
"Id": "450186",
"Score": "0",
"body": "https://docs.python.org/3.7/library/timeit.html"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T23:50:23.710",
"Id": "230576",
"ParentId": "230568",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230576",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T20:25:31.893",
"Id": "230568",
"Score": "2",
"Tags": [
"python",
"comparative-review"
],
"Title": "A function that returns all letters in the Alphabet except the ones in a pre-defined list"
}
|
230568
|
<p>This program is used to get names and numbers of N person, print out the numbers of a person. Please help me improve this code.</p>
<p>Additional Question:</p>
<p>To avoid a very long name that exceeds char's size, I limit it to 255. Is there a better way?</p>
<p>To avoid buffer, I included a space before % sign when using scanf and not use getchar(). Is there a better way?</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Limiting string input
const unsigned int STRINGCONSTRAINT = 255;
// Person struct to store name and numbers
typedef struct {
char name[STRINGCONSTRAINT];
char numbers[STRINGCONSTRAINT];
} person;
void getNameNumber(person people[], int size);
void printNumber(person people[], int size, char personFind[]);
// Asked for array's size and a person's name to find
int main(void) {
unsigned int size = 0;
printf("Enter the amount of people: ");
scanf(" %d", &size);
person people[size];
getNameNumber(people, size);
char personFind[STRINGCONSTRAINT];
puts("Who do you want to find?");
printf("Person to find: ");
scanf(" %[^\n]s", personFind);
printNumber(people, size, personFind);
return 0;
}
// Get name and numbers for the array
void getNameNumber(person people[], int size) {
unsigned int i;
for (i = 0; i < size; i++) {
printf("Name: ");
scanf(" %[^\n]s", people[i].name);
printf("Numbers: ");
scanf(" %[^\n]s", people[i].numbers);
}
}
// Find the person and print the numbers
void printNumber(person people[], int size, char personFind[]) {
unsigned int i;
int flag = 1;
for (i = 0; i < size; i++) {
flag = strcmp(people[i].name, personFind);
if (flag == 0) {
puts("Found!");
printf("You can call %s at %s.\n", personFind, people[i].numbers);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h2><code>static</code> functions</h2>\n\n<p>Both of your <code>getNameNumber</code> and <code>printNumber</code> should be made <code>static</code>, because I doubt that you plan to export them.</p>\n\n<h2>Simpler functions</h2>\n\n<pre><code>printf(\"Enter the amount of people: \");\n</code></pre>\n\n<p>can simply use <code>puts</code>, which doesn't have any formatting code in it. You use <code>puts</code> below, so this would also help with consistency.</p>\n\n<h2>Stack allocation</h2>\n\n<pre><code>person people[size];\n</code></pre>\n\n<p>is not available in all versions of C, since <code>size</code> is not a constant. For best portability you'd want to <code>malloc</code> this, or perhaps <code>alloca</code> if you feel strongly that the memory should be in the stack and not on the heap.</p>\n\n<h2><code>const</code></h2>\n\n<p><code>printNumber</code>'s array arguments should be <code>const</code>, since you don't mutate them.</p>\n\n<h2>Your questions</h2>\n\n<blockquote>\n <p>To avoid a very long name that exceeds char's size, I limit it to 255. Is there a better way?</p>\n</blockquote>\n\n<p>For your use case, not really. A fixed array is the most appropriate. <em>However</em>, your code is vulnerable to overflows. You should be putting a width in your <a href=\"http://www.cplusplus.com/reference/cstdio/scanf/\" rel=\"nofollow noreferrer\">format specifier</a>.</p>\n\n<blockquote>\n <p>To avoid buffer, I included a space before % sign and not use getchar(). Is there a better way?</p>\n</blockquote>\n\n<p>I'm not sure which usage of <code>%</code> you're referring to, but they all look fairly sane, so no; there's not really a better way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T04:22:35.643",
"Id": "449829",
"Score": "0",
"body": "\"*is not available in all versions of C, since size is not a constant*\". VLA available in C99 and since C11 compiler might not support VLA (in this case macro constant `__STDC_NO_VLA__` equals 1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T04:24:36.550",
"Id": "449830",
"Score": "1",
"body": "Wasn't `puts` the function that adds a newline, in contrast to `fputs`? Therefore it is not a good replacement for this `printf` call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T09:38:32.190",
"Id": "451153",
"Score": "0",
"body": "\"can simply use puts\" --> not same functionality."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T00:09:14.667",
"Id": "230578",
"ParentId": "230572",
"Score": "3"
}
},
{
"body": "<p><strong>Strange format</strong></p>\n\n<p>The <code>s</code> in <code>scanf(\" %[^\\n]s\", personFind)</code> serves no purpose. Use <code>\" %[^\\n]\"</code> instead </p>\n\n<p>... or better, use a width limit. See <a href=\"https://stackoverflow.com/a/3301451/2410359\">scanf / field lengths</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T04:02:32.023",
"Id": "230799",
"ParentId": "230572",
"Score": "1"
}
},
{
"body": "<p>Consider this line:</p>\n\n<blockquote>\n<pre><code> scanf(\" %d\", &size);\n</code></pre>\n</blockquote>\n\n<p>We throw away the return value from this function, which means we have no way of knowing whether a value was written to <code>size</code>. In this case, we don't have undefined behaviour, because we initialised it to zero before calling <code>scanf()</code>, but that's not the case later in the program where we read strings into uninitialized memory. In any case, it's rude to users to silently change invalid input into a default answer, rather than giving a meaningful error message.</p>\n\n<p>BTW, the space at the beginning of that conversion is redundant - numeric conversions always skip leading whitespace.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:13:11.167",
"Id": "230810",
"ParentId": "230572",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230578",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T21:56:06.510",
"Id": "230572",
"Score": "3",
"Tags": [
"performance",
"c",
"search"
],
"Title": "Find a String in an Array"
}
|
230572
|
<p>I try to dealing with sessions.. including arrays before moving to "database".</p>
<p>Sessions class.file </p>
<pre><code><?php
session_start();
class Sessions {
public static function ready($name){
return isset($_SESSION[$name]) ? true : false;
}
public static function get($name){
if(isset($_SESSION[$name])){
return $_SESSION[$name];
}else {
return false;
}
}
public static function set($name, $val = []){
return $_SESSION[$name] = $val;
}
public static function des($name){
if(self::ready($name)){
unset($_SESSION[$name]);
}
}
}
</code></pre>
<p>index.php file </p>
<pre><code><?php
include_once "Sessions.php";
const BR = '<br>';
$er = [];
$data = array([
'id'=> '1',
'username'=> 'user1',
'password'=>'123456'
],
[
'id'=> '2',
'username'=> 'user2',
'password'=>'654321'
]
);
//submit
if(isset($_POST['submit'])){
// Error Msgs
$er[] = "Not found in array";
// Forms Inputs
$username = $_POST['username'];
$password = $_POST['password'];
//fetch users in array
foreach ($data as $key => $value) {
if(in_array($username, $value)){
if( $username == $value['username'] && $password == $value['password'] ){
$uid = $value['id'];
$unm = $value['username'];
//Sessions class
Sessions::set('id', $uid);
Sessions::set('username', $unm );
// Error Msgs
unset($er[0]);
}
}
}
}
?>
<?php
//Sessions class
$susername = Sessions::ready('username');
$sid = Sessions::ready('id');
if( $susername AND $sid) { ?>
<?$sid?>
<?$susername?>
<?=BR.Sessions::get('username').BR?>
<?=BR.Sessions::get('id').BR?>
<br>
<a href='log.php'>Out</a>
<br>
<? if( isset( $er[0] ) ) { echo $er[0];}else { unset( $er[0] ); } ?>
<form method="post">
<input type="text" name="username" value="">
<input type="password" name="password" value="">
<input type="submit" name="submit" value="submit">
</form>
</code></pre>
<p>logout.php file </p>
<pre><code><?php
include_once "Sessions.php";
Sessions::des('username');
Sessions::des('id');
header("Location:session.php");
?>
</code></pre>
<p>Is it good for beginner..! is there something wrong..! is there better way for that messy code ?</p>
|
[] |
[
{
"body": "<ul>\n<li><p><code>return isset($_SESSION[$name]) ? true : false;</code> is more succintly written as:</p>\n\n<pre><code>return isset($_SESSION[$name]);\n</code></pre>\n\n<p>The boolean evaluation of <code>isset()</code> is all you need.</p></li>\n<li><p>You can use the <a href=\"https://www.tutorialspoint.com/php7/php7_coalescing_operator.htm\" rel=\"nofollow noreferrer\">null coalescing operator</a> to tight up:</p>\n\n<pre><code>if(isset($_SESSION[$name])){\n return $_SESSION[$name];\n}else {\n return false;\n}\n</code></pre>\n\n<p>Into:</p>\n\n<pre><code>return $_SESSION[$name] ?? false;\n</code></pre></li>\n<li><p>You never need to check if a variable exists before calling <code>unset()</code>. If the variable doesn't exist, the script smoothly, silently continues processing as usual.</p></li>\n<li><p>The tabbing of your code is needing a fair amount of tender loving care. Use 4 spaces to indent where necessary. PSR standards are available for everyone's benefit.</p></li>\n<li><p>I don't think I support the technique of pushing an error message into an array pre-emptively, then removing the element if everything passes. Add a descriptive error to the error array ONLY if an error is detected.</p></li>\n<li><p>If you are not going to use a variable (e.g. <code>$key</code> in your loop), then don't bother declaring it. </p></li>\n<li><p>I realize this is just practice, but try to store only <code>id</code> values in session data if your project permits it. There is such a thing as Session Hijacking -- it may be an extreme scenario, but it is best to avoid storing any \"real world\" identifying data in session arrays.</p></li>\n<li><p>I generally avoid using <code>AND</code> and <code>OR</code> in my <code>if</code> expressions so that I am never tripped up by a fringe \"precedence\" gotcha.</p></li>\n<li><p>If you want to display boolean values for diagnostics, I recommend <code>var_export()</code>.</p></li>\n<li><p>Finally, read about how to destroy a session on logout: <a href=\"https://stackoverflow.com/questions/9001702/php-session-destroy-on-log-out-button\">PHP Session Destroy on Log Out Button</a></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:01:56.890",
"Id": "230603",
"ParentId": "230573",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "230603",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:17:46.813",
"Id": "230573",
"Score": "3",
"Tags": [
"php",
"html"
],
"Title": "Sessions class With assoc-array - practicing"
}
|
230573
|
<p>Funny thing, the following test works:</p>
<pre><code> [TestMethod]
public void Iterate_Once()
{
var x = new[] { 1, 2, 3, 4, 5, 6 }.ToIterable();
CollectionAssert.AreEqual(new[] { 1, 2 }, x.Take(2).ToArray());
CollectionAssert.AreEqual(new[] { 3, 4, 5 }, x.Take(3).ToArray());
}
</code></pre>
<p>Where:</p>
<pre><code>static class Iterable
{
public static IEnumerable<T> ToIterable<T>(this IEnumerable<T> source)
{
var it = source.ToList().GetEnumerator();
return once();
IEnumerable<T> once()
{
while (it.MoveNext())
yield return it.Current;
}
}
}
</code></pre>
<p>That should be safe to do not dispose an iterator of in-memory collection.</p>
<p>Please do not put me in jail for that :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T05:49:32.537",
"Id": "449340",
"Score": "1",
"body": "IMO this is more of a theoretical than a review question, but could you please explain your assertion \"that should be safe to do not dispose of in-memory collection\" - at least for me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T05:57:12.647",
"Id": "449341",
"Score": "1",
"body": "@HenrikHansen We use `List<T>` iterator here which is `IDisposable`. I bet that this concrete `Dispose()` implementation does nothing, so it should be safe to do not invoke it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T07:51:23.580",
"Id": "449346",
"Score": "2",
"body": "OK, betting is a strange kind of development paradigm and relying on an implementation detail is likewise probably not a good idea :-). BtW: the meaning of x.Take(3) (after calling x.Take(2)) is somewhat different than the normal behavior on this kind of IEnumerable<T> return by ToIterable(). Further will for instance `x.Take(3); x.Any(i => i == 1);` return false for `Any()`, and many other `IEnumerable<T>` linq-apis will behave unexpectedly on this kind of `IEnumerable<T>`. IMO you're mixing two distinct concepts that should be kept distinct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T12:27:24.313",
"Id": "449360",
"Score": "0",
"body": "Why would you do this and not just use ToArray or ToList?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T13:51:38.263",
"Id": "449365",
"Score": "0",
"body": "@CharlesNRice Because i am getting here something like a “stream reader” semantics, which behaves differently from ToList or ToArray."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T13:53:50.100",
"Id": "449366",
"Score": "0",
"body": "It's the same as saying ToList().AsEnumerable() I'm not understanding what the root requirement is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T13:56:40.663",
"Id": "449367",
"Score": "0",
"body": "@CharlesNRice it is not :) try the code. We have a second degree function here, a functional programming trick - it requires some FP experience to see what is going on here :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T14:07:04.383",
"Id": "449368",
"Score": "2",
"body": "I see what you doing now. You want something like obserable.publish"
}
] |
[
{
"body": "<p>So what you are trying to do is to have an implementation of <code>IEnumerable<T></code> which has a singleton <code>IEnumerator<T></code>? Why not implement that explicitly, instead of using undocumented (?) behaviour of <code>List<T></code>'s iterator?</p>\n\n<p>Simply create a class that consumes a <code>IEnumerable<T></code>, takes its iterator and wraps it in an implementation of <code>IEnumerator<T></code> that has a dysfunctional <code>Reset</code> method. <code>IEnumerator<T>.GetEnumerator()</code> can then return the instance to that same iterator instead of creating a new one for each call. It could look something like this:</p>\n\n<pre><code> public class OnlyOnceIterator<T> : IEnumerable<T>, IEnumerator<T> {\n private readonly IEnumerator<T> enumerator;\n internal OnlyOnceIterator(IEnumerable<T> sequence) {\n enumerator = sequence.GetEnumerator();\n }\n\n public T Current => enumerator.Current;\n\n object IEnumerator.Current => enumerator.Current;\n\n public void Dispose() {\n enumerator.Dispose();\n }\n\n public IEnumerator<T> GetEnumerator() => this;\n\n public bool MoveNext() {\n return enumerator.MoveNext();\n }\n\n public void Reset() {\n return;\n }\n\n IEnumerator IEnumerable.GetEnumerator() => this;\n }\n</code></pre>\n\n<p>This could then be used in an extension method:</p>\n\n<pre><code> public static OnlyOnceIterator<T> ToOnlyOnceIterator<T>(this IEnumerable<T> sequence) {\n if (sequence == null) {\n throw new System.ArgumentNullException(nameof(sequence));\n }\n\n return new OnlyOnceIterator<T>(sequence);\n }\n</code></pre>\n\n<p>Additionally, I would prefer a more specific return type than <code>IEnumerable<T></code>, since the returned behaviour is significantly different to what any user might expect from <code>IEnumerable<T></code>. Consider creating a new interface that inherits from <code>IEnumerable<T></code> with a more descriptive name. Through inheritance, Linq will still be able to be used, and you can create methods that only accept this specific interface, (compare this to <code>IOrderedEnumerable<T></code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:30:12.593",
"Id": "449383",
"Score": "1",
"body": "I bet it will not work with EF as you would dispose original decorated iterator on the very first run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T17:41:36.260",
"Id": "449397",
"Score": "0",
"body": "The points you make are all valid, but I also believe @DmitryNogin is right on this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T17:47:16.247",
"Id": "449398",
"Score": "0",
"body": "@DmitryNogin You might be right, I have no experience with EF. Maybe changing the implementation of `OnlyOnceIterator.Dispose` to not dispose the enumerable (I overlooked that) might work. OTOH, in your answer you are eagerly evaluating your input sequence, so if you immediately consume that, that would mitigate the disposing risk as well."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T15:30:13.097",
"Id": "230598",
"ParentId": "230574",
"Score": "1"
}
},
{
"body": "<p>I think the following would be the reasonable approach to implement it. Please note that <code>To</code> prefix in <code>ToIterable</code> documents full sequence materialization as framework design guideline naming conventions dictate - compare to <code>As</code> prefix.</p>\n\n<p>It would be interesting to figure out how <code>AsIterable</code> could be done :)</p>\n\n<pre><code>public static class Iterable\n{\n public static IEnumerable<T> ToIterable<T>(this IEnumerable<T> source)\n {\n var array = source.ToArray();\n var i = 0;\n IEnumerable<T> once()\n {\n while (i < array.Length)\n yield return array[i++];\n }\n\n return once();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:27:08.153",
"Id": "230604",
"ParentId": "230574",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T23:18:35.723",
"Id": "230574",
"Score": "7",
"Tags": [
"c#",
"linq"
],
"Title": "Iterate only once using LINQ"
}
|
230574
|
<p>This assumes there is no need to aggregate results from the listeners of a broadcast signal.</p>
<p>Technically I guess the slots are whatever your <code>std::function</code> holds, so they aren't special. So I guess this is more of a Signals/Connections design.</p>
<p>The "connection" or <code>Signal<T...>::Listener</code> is the owner of the callback. It's ideal to have this owned by the object that has the callback function or on the object your lambda captures. That way when that object goes out of scope so does the callback, which prevents it from being called anymore.</p>
<p>You could dump listeners into a container on the object and forget about them. Or store specifically named instances of them which is very useful for switching the object you're listening to or disconnecting.</p>
<pre><code>template <typename... FuncArgs>
class Signal
{
using fp = std::function<void(FuncArgs...)>;
std::forward_list<std::weak_ptr<fp> > registeredListeners;
public:
using Listener = std::shared_ptr<fp>;
Listener add(const std::function<void(FuncArgs...)> &cb) {
// passing by address, until copy is made in the Listener as owner.
Listener result(std::make_shared<fp>(cb));
registeredListeners.push_front(result);
return result;
}
void raise(FuncArgs... args) {
registeredListeners.remove_if([&args...](std::weak_ptr<fp> e) -> bool {
if (auto f = e.lock()) {
(*f)(args...);
return false;
}
return true;
});
}
};
</code></pre>
<p>usage</p>
<pre><code>Signal<int> bloopChanged;
// ...
Signal<int>::Listener bloopResponse = bloopChanged.add([](int i) { ... });
// or
decltype(bloopChanged)::Listener bloopResponse = ...
// let bloopResponse go out of scope.
// or re-assign it
// or reset the shared_ptr to disconnect it
bloopResponse.reset();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T02:17:52.967",
"Id": "449326",
"Score": "0",
"body": "One design question I had was if it was worth wrapping the \"std::shared_ptr<fp>\" in a totally different object that has a more canonical interface. Though pretty much the only thing it would do is rename reset to disconnect, and reset seems fine, so this kept the implementatiton really minimal."
}
] |
[
{
"body": "<ul>\n<li><p>Sink arguments (objects we want to make a copy of and store internally) are generally passed by value, then moved into place, so the <code>add</code> function can take its parameter by value rather than <code>const&</code>.</p></li>\n<li><p>We could perhaps make <code>fp</code> public with a name like <code>Function</code>, and use it for the <code>add</code> function parameter.</p></li>\n<li><p><code>raise</code> will make unnecessary copies of the arguments. We can avoid that with perfect forwarding.</p></li>\n<li><p>We don't need to copy the <code>weak_ptr</code> in the <code>raise</code> lambda, we can use a <code>const&</code>. We also don't need to specify the return value.</p></li>\n</ul>\n\n<p>.</p>\n\n<pre><code>#include <forward_list>\n#include <functional>\n#include <memory>\n\ntemplate <class... FuncArgs>\nclass Signal\n{ \npublic:\n\n using Function = std::function<void(FuncArgs...)>;\n using Listener = std::shared_ptr<Function>;\n\n Listener add(Function cb) {\n auto const result = std::make_shared<Function>(std::move(cb));\n listeners.push_front(result);\n return result;\n }\n\n template<class... Args>\n void raise(Args&&... args) {\n listeners.remove_if([&args...](std::weak_ptr<Function> const& e) {\n if (auto f = e.lock()) {\n (*f)(std::forward<Args>(args)...);\n return false;\n }\n return true;\n });\n }\n\nprivate:\n\n std::forward_list<std::weak_ptr<Function>> listeners;\n};\n\n#include <iostream>\n\nstruct Noisy\n{\n Noisy() = default;\n\n Noisy(Noisy const&) { std::cout << \"copy\\n\"; }\n Noisy& operator=(Noisy const&) { std::cout << \"copy assign\\n\"; return *this; }\n\n Noisy(Noisy&&) { std::cout << \"move\\n\"; }\n Noisy& operator=(Noisy&&) { std::cout << \"move assign\\n\"; return *this; }\n};\n\nint main()\n{\n {\n auto s = Signal<int>();\n auto const l = s.add([] (int v) { std::cout << \"value: \" << v << std::endl; });\n s.raise(5);\n }\n {\n auto s = Signal<Noisy const&>();\n auto const l = s.add([] (Noisy const&) { });\n auto const n = Noisy();\n s.raise(n);\n }\n}\n</code></pre>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T06:24:23.303",
"Id": "449450",
"Score": "0",
"body": "Nice feedback. I tried analyzing the std::function target to see if I could determine the address and realized even if passing by reference, some kind of copy was made automatically anyway.\nGood catch on the forwarding. As for the using for the Function, I was a little torn on whether or not to alias it. As part of the public interface it seemed appropriate to be more direct. But certainly it makes the implementation a little cleaner to alias it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T06:34:53.297",
"Id": "449451",
"Score": "0",
"body": "I'm not sure it's a good idea to force the args to be an rvalue though. What if someone wants to pass an argument that's already an lvalue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T11:34:48.280",
"Id": "449483",
"Score": "1",
"body": "In the altered version, `raise` was changed to be a template function, and the `args` are now template arguments of the template function. The type deduction means that the `Args&&` are \"universal\" or \"forwarding\" references, rather than r-value references. More details: https://eli.thegreenplace.net/2014/perfect-forwarding-and-universal-references-in-c"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T12:36:11.743",
"Id": "230594",
"ParentId": "230577",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230594",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T00:07:34.087",
"Id": "230577",
"Score": "6",
"Tags": [
"c++",
"event-handling"
],
"Title": "Light weight C++ Signals/Slots or Event System"
}
|
230577
|
<p>This is a part of my calculator program. I have to check if the input entered by the user is a valid mathematical expression. The first check is performed by another program, where the program checks if the numbers and symbols are valid and it converts the string into tokens for further verification. The implementation of that program is trivial and thus not covered here.</p>
<p>The following program processes these tokens and outputs whether the expression is valid or not. The tokens are of two types:</p>
<ol>
<li><p>Numbers: <code>{"10", "5.27", "-91.22"}</code></p></li>
<li><p>Symbols: <code>{"+", "-", "*", "/", "^", "!", "(", ")"}</code></p></li>
</ol>
<p>The program handles parentheses differently and does not care about factorial as it's an unary operator. First, I'll describe the <code>Expression</code> class as it defines what an expression is and how its state is calculated.</p>
<p>A valid expression is a number or an unchanged state. So, if the whole expression contains a number then it's valid. If it contains a number, an operator and another number, it makes the entire expression a number. It also makes sure that parentheses are balanced (if present).</p>
<p>Valid expressions: <code>{"1", "1+2", "1+2*3", "1*(2+3)", "(1+2)"}</code></p>
<p>Invalid expressions: <code>{"1*(2", "1+", "+", "1)*2"}</code></p>
<p>The state of the expression is considered <code>true</code> if it's valid and <code>false</code> otherwise. The state of the expression is changed when a number is added or parenthesis count is changed. Exceptions are thrown whenever an invalid combination is found.</p>
<p>Note: The program doesn't calculate the expression it just verifies it.</p>
<p>Expression.java</p>
<pre class="lang-java prettyprint-override"><code>/**
* Tracks the state of the expression.
*/
class Expression {
private boolean numberPresent;
private boolean operatorPresent;
private boolean state;
private int openParCount;
private boolean stateChanged;
private boolean parStateChanged;
void addNumber() throws ExpressionFormatException {
if (!numberPresent) {
numberPresent = true;
} else if (operatorPresent) {
// if operator is present, make the entire expression a number
operatorPresent = false;
} else {
throw new ExpressionFormatException();
}
stateChanged = true;
}
void addOperator(String aOperator) throws ExpressionFormatException {
if (numberPresent && !operatorPresent) {
operatorPresent = true;
} else {
throw new ExpressionFormatException();
}
}
/**
* Modify open parenthesis count.
*/
void modParCount(int n) {
openParCount += n;
parStateChanged = true;
stateChanged = true;
}
boolean hasStateChanged() {
return stateChanged;
}
/**
* Get the current state of the expression.
* @return a boolean value.
*/
boolean getState() {
if (!numberPresent && !operatorPresent) {
// if parenthesis state is changed a number needs to be present
state = !parStateChanged;
} else if (numberPresent && operatorPresent) {
state = false;
} else if (numberPresent) {
state = true;
}
// return true only if the state is true and parentheses are balanced
return state && openParCount == 0;
}
}
</code></pre>
<p>Now, I'll describe the <code>Verifier</code> class, mainly its <code>isComputable</code> method. The <code>verify</code> method starts the ball rolling, it passes <code>isComputable</code> the token array and the starting offset. The <code>isComputable</code> method makes a <code>localExpression</code> and adds a number or an operator whenever it encounters it. The method recurses when it encounters a <code>"("</code> and if the <code>localExpression</code>'s state is changed. It returns when the control flow drops or it encounters a <code>")"</code>. The method also changes the state of the parentheses in a <code>localExpression</code>. The method returns immediately if the <code>subState</code>, the expression nested inside it, is not valid or <code>ExpressionFormatException</code> is caught.</p>
<p>Verifier.java</p>
<pre class="lang-java prettyprint-override"><code>import java.util.*;
class Verifier {
private static Set<String> validOperators = Set.of("+", "-", "*", "/", "^");
/**
* Passes tokens and the starting offset to isComputable to verify the expression
*
* @param tokens contains valid numbers and symbols.
* @return a boolean value returned by isComputable.
*/
static boolean verify(ArrayList<String> tokens) {
return isComputable(tokens, new int[] {0});
}
/**
* Verifies the state of the expression and its nested expressions recursively.
*
* @param tokens a list containing valid numbers and symbols.
* @param offset keeps track of the current position in the list.
* @return a boolean value denoting whether the expression is valid.
*/
private static boolean isComputable(ArrayList<String> tokens, int[] offset) {
var localExpression = new Expression();
var subState = true;
while(offset[0] < tokens.size()) {
String token = tokens.get(offset[0]);
try {
if (Evaluator.isNumber(token)) {
localExpression.addNumber();
} else if (validOperators.contains(token)) {
localExpression.addOperator(token);
} else if (token.equals("(")) {
if (localExpression.hasStateChanged()) {
// recurse if the state of the current expression has changed
subState = isComputable(tokens, offset);
if (!subState) {
return false;
} else {
localExpression.addNumber();
}
} else {
// if state is unchanged increase open parenthesis count
localExpression.modParCount(1);
}
} else if (token.equals(")")) {
// decrease open parenthesis count
localExpression.modParCount(-1);
return localExpression.getState();
}
} catch (ExpressionFormatException e) {
return false;
}
offset[0]++;
}
return localExpression.getState();
}
}
</code></pre>
<p><code>Evaluator.isNumber</code> and <code>ExpressionFormatException</code> are not a part of this program and are too trivial to include here.</p>
<p>Below are some tests:</p>
<pre class="lang-none prettyprint-override"><code>Output Input
true -> "2+1"
true -> "2+2*(5+6)"
true -> "2+3+4+5+6"
true -> "2!+3^5"
true -> "-5*3+-1"
true -> "4+2*(6+2)/(4-2)/(2*(65+(3*4)))"
true -> "3"
false -> "(2+2"
false -> "2!(3)"
false -> "2**2"
false -> "5+()"
false -> "--1"
false -> "+3"
false -> ")"
</code></pre>
<p>Note: The input is shown in Strings to aid readability.</p>
<p>Issues:</p>
<ol>
<li><p>Expression like <code>"1/0"</code> are considered valid as the <code>Expression</code> object does not care what kind of number it's receiving. Similarly, negative factorials are also allowed.</p></li>
<li><p>Unary minus is supported but unary plus is not (not yet).</p></li>
<li><p>The index is the first element in the <code>int[] offset</code> that is passed recursively to keep track of index.</p></li>
</ol>
<p>Any help would be appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T04:34:36.340",
"Id": "449332",
"Score": "0",
"body": "Just a sidenote: if unary minus is supported, --1 should be ok, just as ---1, ----1 and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T05:16:53.650",
"Id": "449336",
"Score": "0",
"body": "_The index is the first element in the `int[] offset` that is passed recursively to keep track of index.- — I don't understand what you are trying to say. What index?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T18:56:00.187",
"Id": "449404",
"Score": "0",
"body": "@mtj Thanks for pointing that out. I''ll fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T19:08:25.913",
"Id": "449405",
"Score": "0",
"body": "@200_success `while(offset[0] < tokens.size())` as we don't have mutable integers in Java, I am passing an int array recursively to keep tack of the current index. It's more of a hack that's why it's one of the issues. There were many alternatives but this is easy to implement and doesn't lead to bloated code. You can read more about it here: https://stackoverflow.com/a/4520163."
}
] |
[
{
"body": "<h2>State nomenclature</h2>\n\n<p><code>stateChanged</code> vaguely makes sense, but <code>state</code> doesn't. The word \"state\" is a fairly vague descriptor. What does <code>state</code> as a boolean actually mean? This should probably be renamed to <code>isValid</code>.</p>\n\n<h2>Boolean factorization</h2>\n\n<pre><code> if (!numberPresent && !operatorPresent) {\n // if parenthesis state is changed a number needs to be present\n state = !parStateChanged;\n } else if (numberPresent && operatorPresent) {\n state = false;\n } else if (numberPresent) {\n state = true;\n }\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>if (numberPresent)\n isValid = !operatorPresent;\nelse\n isValid = !parStateChanged;\n</code></pre>\n\n<h2><code>else</code> after <code>return</code></h2>\n\n<p>This:</p>\n\n<pre><code> if (!subState) {\n return false;\n } else {\n</code></pre>\n\n<p>doesn't need the <code>else</code>, due to the <code>return</code> stopping the function beforehand.</p>\n\n<h2>Surprise mutation</h2>\n\n<p><code>getState</code> has a problem. One would assume, reading only the function signature and not the source, that it doesn't change the class - and only computes a value to return it. However, that's not the case - a member is changed. There are several different ways to deal with this depending on your intent:</p>\n\n<ul>\n<li>Rename the function to describe what it actually does (<code>checkValidity</code>?)</li>\n<li>Separate the <code>check</code> function from the <code>isValid</code> function</li>\n<li>Don't store a <code>state</code> as a member at all, and only have an <code>isValid</code> function</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T15:54:56.423",
"Id": "230647",
"ParentId": "230579",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230647",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T03:07:20.760",
"Id": "230579",
"Score": "2",
"Tags": [
"java",
"math-expression-eval"
],
"Title": "Verifying Mathematical Expressions"
}
|
230579
|
<p>I wrote the following password generator, to generate a password in which each character group appears at least at once.</p>
<pre class="lang-java prettyprint-override"><code>import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class PWGen {
public static final ArrayList<ArrayList<Character>> groups = new ArrayList<ArrayList<Character>>();
static {
ArrayList<Character> g1 = new ArrayList<Character>();
for (int i = 'a'; i <= 'z'; i++) {
g1.add((char) i);
}
// Remove similar characters
for (Iterator<Character> iterator = g1.iterator(); iterator.hasNext();) {
Character character = (Character) iterator.next();
if (character == 'l')
iterator.remove();
}
ArrayList<Character> g2 = new ArrayList<Character>();
for (int i = 'A'; i <= 'Z'; i++) {
g2.add((char) i);
}
// Remove similar characters
for (Iterator<Character> iterator = g2.iterator(); iterator.hasNext();) {
Character character = (Character) iterator.next();
if ("IO".contains(String.valueOf(character)))
iterator.remove();
}
ArrayList<Character> g3 = new ArrayList<Character>();
for (int i = '0'; i <= '9'; i++) {
g3.add((char) i);
}
ArrayList<Character> g4 = new ArrayList<Character>();
g4.add('-');
ArrayList<Character> g5 = new ArrayList<Character>();
g5.add('_');
ArrayList<Character> g6 = new ArrayList<Character>();
g6.add(' ');
ArrayList<Character> g7 = new ArrayList<Character>();
g7.add('!');
g7.add('$');
g7.add('%');
g7.add('&');
groups.addAll(List.of(g1, g2, g3, g4, g5, g6, g7));
}
public static final String getPassword(final int len, final int gs, final boolean any) {
SecureRandom sr = new SecureRandom();
while (true) {
StringBuilder b = new StringBuilder();
int mask = 0;
while (b.length() < len) {
int i1 = sr.nextInt(7);
if (((1 << i1) & (gs)) != 0) {
int i2 = sr.nextInt(groups.get(i1).size());
b.append(groups.get(i1).get(i2));
mask |= (1 << i1);
}
}
if (!any || mask == gs) {
return b.toString();
}
}
}
public static void main(String[] args) {
System.out.println(getPassword(10, 0b1011111, false));
System.out.println(getPassword(10, 0b1011111, true));
}
}
</code></pre>
<p><strong>Edit / Version 2</strong></p>
<pre class="lang-java prettyprint-override"><code>import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class PWGen {
public static final ArrayList<ArrayList<Character>> groups = new ArrayList<ArrayList<Character>>();
static {
ArrayList<Character> g1 = new ArrayList<Character>();
for (int i = 'a'; i <= 'z'; i++) {
g1.add((char) i);
}
// Remove similar characters
for (Iterator<Character> iterator = g1.iterator(); iterator.hasNext();) {
Character character = (Character) iterator.next();
if (character == 'l')
iterator.remove();
}
ArrayList<Character> g2 = new ArrayList<Character>();
for (int i = 'A'; i <= 'Z'; i++) {
g2.add((char) i);
}
// Remove similar characters
for (Iterator<Character> iterator = g2.iterator(); iterator.hasNext();) {
Character character = (Character) iterator.next();
if ("IO".contains(String.valueOf(character)))
iterator.remove();
}
ArrayList<Character> g3 = new ArrayList<Character>();
for (int i = '0'; i <= '9'; i++) {
g3.add((char) i);
}
ArrayList<Character> g4 = new ArrayList<Character>();
g4.add('-');
ArrayList<Character> g5 = new ArrayList<Character>();
g5.add('_');
ArrayList<Character> g6 = new ArrayList<Character>();
g6.add(' ');
ArrayList<Character> g7 = new ArrayList<Character>();
g7.add('!');
g7.add('$');
g7.add('%');
g7.add('&');
groups.addAll(List.of(g1, g2, g3, g4, g5, g6, g7));
}
public static final String getPassword(final int len, final int gs, final boolean any) {
ArrayList<Character> list = new ArrayList<Character>();
for (int i = 0; i < 7; i++) {
if (((1 << i) & gs) != 0) {
for (Character character : groups.get(i)) {
list.add(character);
list.add((char) i);
}
}
}
int n = list.size() / 2;
SecureRandom sr = new SecureRandom();
while (true) {
StringBuilder b = new StringBuilder();
int mask = 0;
while (b.length() < len) {
int i1 = sr.nextInt(n) * 2;
b.append(list.get(i1));
mask |= (1 << list.get(i1 + 1));
}
if (!any || mask == gs) {
return b.toString();
}
}
}
public static void main(String[] args) {
System.out.println(getPassword(10, 0b1111111, false));
System.out.println(getPassword(10, 0b1111111, true));
System.out.println();
System.out.println( getPassword(Integer.parseInt(args[0]), Integer.parseInt(args[1], 2), Boolean.parseBoolean(args[2])) );
System.out.println();
}
}
</code></pre>
<p>which version is better? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T02:21:14.463",
"Id": "449441",
"Score": "2",
"body": "While \"comparative reviews\" (A vs B) are *technically* on-topic (see [tag:comparative-review]), IMO you would get the best out of this site if you presented us the version of the code you're using, and expanded a bit more on how it's used; you can also include unit tests if you have any: give reviewers information about the *intent* of your code (readability/maintainability, performance, security, etc.), it helps defining what \"better\" means for you. Feel free to [edit] your post and tell us more!"
}
] |
[
{
"body": "<p>To be honest: Neither. </p>\n\n<ul>\n<li><p>Both are equally unnecessarily complicated and difficult to read. They use old-fashioned, maybe over-optimized techniques instead of Java/OOP features. </p></li>\n<li><p>The code lacks readable variable names and any documentation for the reader/reviewer or for other programmers who need to use this. </p></li>\n<li><p>And finally (if I read it correctly) they have the danger to getting caught in an infinite loop if called with specific arguments.</p></li>\n</ul>\n\n<hr>\n\n<h1>Building the character lists</h1>\n\n<h2>Memory management</h2>\n\n<p>In the building of the character lists one of the problems is that the <code>ArrayList</code>s are used in a way that (internally) the data is copied in memory multiple times. To avoid that when filling an <code>ArrayList</code>, if you know number of elements you will be adding, set the capacity when creating the <code>ArrayList</code>:</p>\n\n<pre><code>ArrayList<Character> g1 = new ArrayList<Character>(26);\n</code></pre>\n\n<p>After filling the list you loop over the items to find one you remove. Removing items from an <code>ArrayList</code> also requires coping of data in order to fill the gaps in the array. Since you are already looping over the letters to fill the array list, you shouldn't add the letters you don't want in the first place:</p>\n\n<pre><code>ArrayList<Character> g1 = new ArrayList<Character>();\nfor (char i = 'a'; i <= 'z'; i++) {\n if (i != 'l') {\n g1.add(i);\n }\n}\n</code></pre>\n\n<p>Also notice: <code>'a'</code> is already a literal of the type <code>char</code>. Declaring <code>i</code> as a <code>char</code> avoids casting twice - one implicit and one explicit). </p>\n\n<h2>Use interfaces instead of specific classes</h2>\n\n<p>Don't declare object variables, generic types and method parameters as their specific type, but as the most constraining interface possible. So your character list should be:</p>\n\n<pre><code>public static final List<List<Character>> groups = new ArrayList<List<Character>>();\n</code></pre>\n\n<p>This is because code that uses this list does not need (and should not need) to know that these are <code>ArrayList</code>s.</p>\n\n<p>This also allows you to use something other than <code>ArrayList</code>. For example the small lists of special characters would be much nicer the create with <code>List.of</code> (which uses its own implementation of <code>List</code>):</p>\n\n<pre><code>List<Character> g4 = List.of('-');\nList<Character> g5 = List.of('_');\nList<Character> g6 = List.of(' ');\nList<Character> g7 = List.of('!', '$', '%', '&');\n</code></pre>\n\n<p>This also comes back to another memory management point. The line </p>\n\n<pre><code> groups.addAll(List.of(g1, g2, g3, g4, g5, g6, g7));\n</code></pre>\n\n<p>creates a list (<code>List.of</code>) but its content is added to <code>groups</code> and then it's discarded again. Instead don't create an <code>ArrayList</code> and use the list created by <code>List.of</code> directly:</p>\n\n<pre><code>public static final List<List<Character>> groups;\n\nstatic {\n // ...\n groups = List.of(g1, g2, g3, g4, g5, g6, g7);\n}\n</code></pre>\n\n<h2>A more Java appropriate data structure</h2>\n\n<p>(This review is getting quite a bit longer that I expected, so I'll be more abstract from here on.)</p>\n\n<p>Is is really needed to fill an array with all possible characters? Instead consider a data structure that represents a character range for example storing only the first, last and missing characters. It can have methods that return the number of characters it represents and return the <code>n</code>th character.</p>\n\n<p>Also the different character sets, which are currently represented by the index of the outer <code>ArrayList</code> and the bits in the <code>gs</code> parameter of the actual password generator, could be instead represented by a Java <code>enum</code>. Java also provides a <code>EnumSet</code> which would be used to replace the bitset.</p>\n\n<p>(I could go into details and write much more, but unfortunately I don't have the time anymore.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:23:08.813",
"Id": "449656",
"Score": "0",
"body": "_most constraining interface_ should be _least_ constraining interface. The best practice in OOP is to pass around the weakest type that meets the requirements of the caller."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T06:51:04.887",
"Id": "449735",
"Score": "0",
"body": "@Reinderien Maybe we have different definitions of \"constrainting\" in this context? For me, for example, `Collection` is more constrainting than `List`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:18:13.373",
"Id": "230690",
"ParentId": "230582",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T04:13:30.150",
"Id": "230582",
"Score": "4",
"Tags": [
"java",
"strings",
"comparative-review",
"random"
],
"Title": "Random password generator that ensures diversity of character types and absence of confusing characters"
}
|
230582
|
<p>I have a working code that groups items by their type values. The types can be one or multiple, however they are always returned as an array. </p>
<p>To illustrate: if an item has types with values <code>type1</code> and <code>type2</code>, it should be included in both <code>type1</code> and <code>type2</code> properties of the resulting grouped object.</p>
<p>Although the code works, I was wondering if it would be possible to rewrite it without using nested <code>for</code> loops, to make it more aligned with the principles of functional programming, ideally using <code>reduce</code>. Since the data sets are not too large, performance is a secondary consideration, but should be taken into account if possible.</p>
<p>The code is as follows. <code>getTypes</code> is added primarily to show how the types are extracted and ideally shouldn't be changed.</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 items = [{
name: 'First item',
types: [{
value: 'type1',
},
{
value: 'type2',
},
],
},
{
name: 'Second item',
types: [{
value: 'type1',
},
{
value: 'type3',
},
],
},
{
name: 'Third item',
types: [{
value: 'type1',
},
{
value: 'type2',
},
],
},
];
const getTypes = item => item.types.map(type => type.value);
const groupedItems = {};
for (const item of items) {
for (const type of getTypes(item)) {
groupedItems[type] = [...(groupedItems[type] || []), item];
}
}
console.log(JSON.stringify(groupedItems, null, 4));</code></pre>
</div>
</div>
</p>
<p>Code output:</p>
<pre><code>{
"type1": [
{
"name": "First item",
"types": [
{
"value": "type1"
},
{
"value": "type2"
}
]
},
{
"name": "Second item",
"types": [
{
"value": "type1"
},
{
"value": "type3"
}
]
},
{
"name": "Third item",
"types": [
{
"value": "type1"
},
{
"value": "type2"
}
]
}
],
"type2": [
{
"name": "First item",
"types": [
{
"value": "type1"
},
{
"value": "type2"
}
]
},
{
"name": "Third item",
"types": [
{
"value": "type1"
},
{
"value": "type2"
}
]
}
],
"type3": [
{
"name": "Second item",
"types": [
{
"value": "type1"
},
{
"value": "type3"
}
]
}
]
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T11:10:11.433",
"Id": "449356",
"Score": "0",
"body": "Not quite sure why you want to change perfectly readable code to use reduce? JavaScript seems to lack \"array comprehensions\" ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions ) / \"object comprehensions\" (not sure about the latter term), so till it will get those using for loops looks perfect to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T10:46:37.737",
"Id": "449479",
"Score": "0",
"body": "@RomanSusi I was just wondering if it were possible to make this code more concise with `reduce`."
}
] |
[
{
"body": "<h2>Poor memory usage</h2>\n<p>Javascript has managed memory. That means it does all the hard work of allocating and releasing memory, which is great (managing memory manually is a real pain).</p>\n<p>But this useful feature comes with a down sides...</p>\n<ul>\n<li>Managed memory environments are inherently slow,</li>\n<li>Managed memory environments encourage very poor memory usage patterns</li>\n</ul>\n<h2>Looking at your memory and CPU usage.</h2>\n<p>In your code you create a total of 9 arrays, keeping only 3 of them. (using the data example you provided)</p>\n<p>Each time you add an item to a group you create a new array, that must be iterated over when you copy the existing group. <code>groupedItems[type] = [...(groupedItems[type] || []), item]</code></p>\n<p>There are only 6 type values yet you iterate over them 12 times. Once each with <code>item.types.map(type => type.value);</code> and then again with <code>for (const type of getTypes(item))</code></p>\n<p>For the 6 items you add to the 3 groups your code needed 16 iterations.</p>\n<h2>Less overhead</h2>\n<p>The example avoids copying the item.types array for each item and assigns a new array to new groups. If a group has been defined the item added is pushed rather than copy the whole array.</p>\n<p>The resulting code only needs 6 iterations executing in half the time and using several times less memory</p>\n<pre><code>function groupTypes(items) {\n const groups = {};\n for (const item of items) {\n for (const {value: type} of item.types) {\n groups[type] ? groups[type].push(item) : groups[type] = [item];\n }\n }\n return groups;\n}\n</code></pre>\n<p>Or slightly quicker by avoiding the copy of the <code>type.value</code> string to to the variable <code>type</code></p>\n<pre><code>function groupTypes(items) {\n const grps = {};\n for (const item of items) {\n for (const type of item.types) {\n grps[type.value] ? grps[type.value].push(item) : grps[type.value] = [item];\n }\n }\n return grps ;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T10:48:00.797",
"Id": "449480",
"Score": "0",
"body": "Thanks for the detailed explanation! Would the implementation change if we had no control over `getTypes` and just knew that it returns an array of type values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T11:32:16.373",
"Id": "449482",
"Score": "1",
"body": "@Clarity In the first example you would replace the inner loop with `for (const type of getTypes()) {` If the function `getTypes` is inhouse you can suggest politely that such functions should be generators eg `getTypes(item) { for(const {value} of item.types) { yield value } }` saving the need to use a temp array to transport data. For more on generators https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T06:38:53.733",
"Id": "449563",
"Score": "0",
"body": "Great, thanks, didn't know about performance benefits of generators in this case."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T13:04:33.537",
"Id": "230596",
"ParentId": "230589",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230596",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T09:13:31.713",
"Id": "230589",
"Score": "1",
"Tags": [
"javascript",
"performance",
"functional-programming"
],
"Title": "Group items by types: replace nested for loops with reduce"
}
|
230589
|
<p>I would like to receive some advice on how to improve a small concatenative stack-based interpreter, executing a <a href="https://en.wikipedia.org/wiki/Joy_(programming_language)" rel="nofollow noreferrer">joy</a>-like programming language. It is really minimal, and is in fact a subset of a larger version that should, a priori, be used as a compilation target.</p>
<p>The version I would like to review here, however, is functional and representative of the other's base. In short, I would like to have global opinions on what should be improved or prohibited, and I would also like to draw more attention to the way the interpreter manages function calls:</p>
<pre><code>void evalfunc(Stack *stack, struct Function *function, struct Dico *dico)
{
for (size_t i = 0; i < function->body.size; i++)
evalop(stack, &function->body.array[i], dico);
}
</code></pre>
<p>I actually have the impression that it's quite rudimentary as a way of doing things, and it doesn't allow you to recursion infinitely since it uses the program's stack; and as in this style of language, the notion of loop doesn't exist, there's only recursion, I wonder if there wasn't something you could do to allow a function like these:</p>
<pre><code>undefined = undefined
forever = doSomeStuff forever // If we need to execute an entire program in an "infinite loop" for example, it would be really nice
</code></pre>
<p>not to cause a stack-overflow, even if the recursion limit is most of the time unreachable and sufficient. But, in a superset version of this project, programs to be interpreted will likely perform operations as we would with a simple <code>while(true)</code> loop, and recursion is the only way to do it now; I would not like to have to implement something that goes beyond the philosophy of concatenative functional programming... But if there is no other way to do it, let me know :)</p>
<p>So, here are the files and the makefile (using GCC, compiled under Windows with mingw):</p>
<p><strong>Makefile</strong></p>
<pre><code>CC = gcc
CCFLAGS = -g -W -Wall -Wno-missing-braces -O2 -Wno-unused-value
OBJS = Combinator.o Function.o Interpret.o RawCode.o Stack.o Show.o
all : main
main : ${OBJS} main.o
@echo Linking...
${CC} ${CCFLAGS} ${OBJS} main.o -o main
Stack.o : Stack.c
${CC} ${CCFLAGS} -c Stack.c
Combinator.o : Combinator.c
${CC} ${CCFLAGS} -c Combinator.c
Function.o : Function.c
${CC} ${CCFLAGS} -c Function.c
Interpret.o : Interpret.c
${CC} ${CCFLAGS} -c Interpret.c
RawCode.o : RawCode.c
${CC} ${CCFLAGS} -c RawCode.c
Show.o : Show.c
${CC} ${CCFLAGS} -c Show.c
</code></pre>
<p><strong>Combinator.h</strong></p>
<pre><code>#pragma once
enum Combinator
{ POP, DUP, SWAP
, FLIP, ID, QUOTE
, UNQUOTE, UNKNOWN };
static const char Str_Combs[][8] =
{ "pop", "dup", "swap"
, "flip", "id", "quote"
, "unquote" };
enum Combinator string_to_comb(const char*);
</code></pre>
<p><strong>Combinator.c</strong></p>
<pre><code>#include <string.h>
#include "Combinator.h"
enum Combinator string_to_comb(const char *s)
{
for (unsigned int i = 0; i < sizeof(Str_Combs) / sizeof(Str_Combs[0]); i++)
if (!strcmp(Str_Combs[i], s))
return (enum Combinator)i;
return UNKNOWN;
}
</code></pre>
<p><strong>Function.h</strong></p>
<pre><code>#pragma once
#include <ctype.h>
#include "RawCode.h"
struct Function
{
char *name;
RawCode body;
};
struct Dico
{
struct Function *functions;
size_t size;
size_t used;
};
void init_dico(struct Dico *, size_t);
void push_dico(struct Dico *, struct Function);
struct Function make_Function(char *, RawCode);
struct Function *get_specific_function(char *, struct Dico *);
</code></pre>
<p><strong>Function.c</strong></p>
<pre><code>#include <stdlib.h>
#include <string.h>
#include "Function.h"
#include "RawCode.h"
void init_dico(struct Dico *dico, size_t size)
{
dico->functions = (struct Function *)malloc(size * sizeof(struct Function));
dico->used = 0;
dico->size = size;
}
void push_dico(struct Dico *dico, struct Function function)
{
if (dico->used == dico->size)
{
dico->size *= 2;
dico->functions = (struct Function *)realloc(dico->functions, dico->size * sizeof(struct Function));
if (dico->functions == NULL)
perror("Out of vector memory");
}
dico->functions[dico->used++] = make_Function(function.name, function.body);
}
struct Function make_Function(char *name, RawCode body)
{
return (struct Function){.name = name, .body = body};
}
struct Function *get_specific_function(char *name, struct Dico *dico)
{
for (size_t i = 0; i < dico->used; i++)
if (!strcmp(dico->functions[i].name, name))
return &dico->functions[i];
return NULL;
}
</code></pre>
<p><strong>Interpret.h</strong></p>
<pre><code>#pragma once
#include <ctype.h>
#include "Stack.h"
#include "RawCode.h"
#include "Combinator.h"
#include "LiteralOperation.h"
#include "Function.h"
// Execute the code from RawCode and return the resulting stack
Stack interpret(RawCode, struct Dico);
// Evaluate the given operation on the stack
void evalop(Stack *, struct Value *, struct Dico *);
// Evaluate the given combinator on the stack
void evalcomb(Stack *, enum Combinator, struct Dico *);
// Evalute a word on the stack
void evalword(Stack *, struct Dico *, char *);
// Evaluate a function on the stack
void evalfunc(Stack *, struct Function *, struct Dico *);
// Evalute the given literal operation on the stack
void evallo(Stack *, enum LiteralOperation, struct Dico *);
</code></pre>
<p><strong>Interpret.c</strong></p>
<pre><code>#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "Interpret.h"
#include "RawCode.h"
#include "Function.h"
#include "Stack.h"
#include "Combinator.h"
#include "LiteralOperation.h"
#include "Show.h"
Stack interpret(RawCode rcode, struct Dico dico)
{
Stack runtime_stack;
init_stack(&runtime_stack, rcode.used);
for (size_t i = 0; i < rcode.used; i++)
evalop(&runtime_stack, &rcode.array[i], &dico);
return runtime_stack;
}
void evalop(Stack *stack, struct Value *value, struct Dico *dico)
{
switch (value->kind)
{
// If the value is a quotation or any literal, then just push it on the stack
case Val_Quotation ... Val_String:
push(stack, *value);
break;
// If this is a stack combinator, then apply it on the stack
case Val_Combinator:
evalcomb(stack, value->u.comb_.comb, dico);
break;
// If this is a "word" (a function), then evaluate it
case Val_Word:
evalword(stack, dico, value->u.word_.word);
break;
case Val_LiteralOperation:
evallo(stack, value->u.literalOperation_.literalOperation, dico);
break;
case Val_Empty:
printf("Empty stack!\n");
break;
}
}
void evalcomb(Stack *stack, enum Combinator comb, struct Dico *dico)
{
switch (comb)
{
case POP:
pop(stack);
break;
case DUP:
push(stack, *top_ptr(stack));
break;
case SWAP:
{
struct Value tmp = *topx_ptr(stack, 1);
*topx_ptr(stack, 1) = *topx_ptr(stack, 2);
*topx_ptr(stack, 2) = tmp;
}
break;
case FLIP:
{
struct Value tmp = *topx_ptr(stack, 1);
*topx_ptr(stack, 1) = *topx_ptr(stack, 3);
*topx_ptr(stack, 3) = tmp;
}
break;
case ID:
break;
case QUOTE:
{
RawCode *quote = (RawCode *)malloc(sizeof(*quote));
init_rcode(quote, 1);
push_rcode(quote, *top_ptr(stack));
*top_ptr(stack) = make_Val_Quotation(quote);
}
break;
case UNQUOTE:
{
struct Value quote = drop(stack);
for (size_t i = 0; i < quote.u.quote_.quote->used; i++)
evalop(stack, &quote.u.quote_.quote->array[i], dico);
}
break;
case UNKNOWN:
default:
printf("Unknown combinator '%d'\n", (int)comb);
}
}
void evalfunc(Stack *stack, struct Function *function, struct Dico *dico)
{
for (size_t i = 0; i < function->body.size; i++)
evalop(stack, &function->body.array[i], dico);
}
void evalword(Stack *stack, struct Dico *dico, char *word)
{
struct Function *tmptr_function = get_specific_function(word, dico);
if (tmptr_function != NULL)
{
evalfunc(stack, tmptr_function, dico);
}
else if (!strcmp(word, "lowereq"))
{
// `x y lowereq` returns 1 or 0 depending on x is lower or equals to y
evalcomb(stack, SWAP, dico);
*top_ptr(stack) = make_Val_Integer((bool)(drop(stack).u.integer_.integer <= top(*stack).u.integer_.integer));
}
else if (!strcmp(word, "if"))
{
if ((bool)topx_ptr(stack, 3)->u.integer_.integer == true)
{
pop(stack);
evalcomb(stack, SWAP, dico);
pop(stack);
evalcomb(stack, UNQUOTE, dico);
}
else
{
evalcomb(stack, SWAP, dico);
pop(stack);
evalcomb(stack, SWAP, dico);
pop(stack);
evalcomb(stack, UNQUOTE, dico);
}
}
else
{
printf("Unknown word '%s'\n", word);
}
}
void evallo(Stack *stack, enum LiteralOperation lo, struct Dico *dico)
{
// We have to swap the top of the stack for more logic:
// `5 3 -` will give 3 - 5 with the method below,
// it's more logic for us to think that as `5 - 3`
evalcomb(stack, SWAP, dico);
switch (lo)
{
case ADD:
push(stack, make_Val_Integer(drop(stack).u.integer_.integer + drop(stack).u.integer_.integer));
break;
case SUB:
push(stack, make_Val_Integer(drop(stack).u.integer_.integer - drop(stack).u.integer_.integer));
break;
case MUL:
push(stack, make_Val_Integer(drop(stack).u.integer_.integer * drop(stack).u.integer_.integer));
break;
case DIV:
push(stack, make_Val_Integer(drop(stack).u.integer_.integer / drop(stack).u.integer_.integer));
break;
}
}
</code></pre>
<p><strong>LiteralOperation.h</strong></p>
<pre><code>#pragma once
enum LiteralOperation
{ ADD, SUB, MUL, DIV };
</code></pre>
<p><strong>RawCode.h</strong></p>
<pre><code>#pragma once
#include <ctype.h>
#include "Combinator.h"
#include "LiteralOperation.h"
typedef struct RawCode RawCode;
typedef enum Kind Kind;
struct Value {
enum Kind
{ Val_Quotation, Val_Integer, Val_String, Val_Word, Val_LiteralOperation, Val_Combinator, Val_Empty } kind;
union {
// Quotation
struct { RawCode* quote; } quote_;
// Integer literal
struct { int integer; } integer_;
// Char literal
struct { char character; } character_;
// char* literal
struct { char* string; } string_;
// A stack combinator
struct { enum Combinator comb; } comb_;
// A word on the stack (a function)
struct { char* word; } word_;
// A literal operation (+, -, *, /)
struct { enum LiteralOperation literalOperation; } literalOperation_;
} u;
};
struct Value make_Val_Quotation(RawCode*);
struct Value make_Val_Integer(int);
struct Value make_Val_string(char*);
struct Value make_Val_Word(char*);
struct Value make_Val_LiteralOperation(enum LiteralOperation);
struct Value make_Val_Combinator(enum Combinator);
struct RawCode {
struct Value* array;
size_t used;
size_t size;
};
void init_rcode(RawCode*, size_t);
void push_rcode(RawCode*, struct Value);
void pop_rcode(RawCode*);
struct Value drop_rcode(RawCode*);
struct Value top_rcode(RawCode);
// When the stack is empty
static const struct Value empty_value = { .kind = Val_Empty };
</code></pre>
<p><strong>RawCode.c</strong></p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "RawCode.h"
#include "Combinator.h"
#include "LiteralOperation.h"
struct Value make_Val_Quotation(RawCode *rcode)
{
return (struct Value){.kind = Val_Quotation, .u = {.quote_ = rcode}};
}
struct Value make_Val_Integer(int x)
{
return (struct Value){.kind = Val_Integer, .u = {.integer_ = x}};
}
struct Value make_Val_String(char *s)
{
return (struct Value){.kind = Val_String, .u = {.string_ = s}};
}
struct Value make_Val_Word(char *s)
{
return (struct Value){.kind = Val_Word, .u = {.word_ = s}};
}
struct Value make_Val_LiteralOperation(enum LiteralOperation lo)
{
return (struct Value){.kind = Val_LiteralOperation, .u = {.literalOperation_ = lo}};
}
struct Value make_Val_Combinator(enum Combinator comb)
{
return (struct Value){.kind = Val_Combinator, .u = {.comb_ = comb}};
}
void init_rcode(RawCode *rcode, size_t initSize)
{
rcode->array = (struct Value *)malloc(initSize * sizeof(struct Value));
rcode->used = 0;
rcode->size = initSize;
}
void push_rcode(RawCode *rcode, struct Value item)
{
if (rcode->used == rcode->size)
{
rcode->size *= 2;
rcode->array = (struct Value *)realloc(rcode->array, rcode->size * sizeof(struct Value));
if (rcode->array == NULL)
perror("Out of raw code memory");
}
rcode->array[rcode->used++] = item;
}
void pop_rcode(RawCode *rcode)
{
rcode->array[rcode->used--];
}
struct Value drop_rcode(RawCode *rcode)
{
struct Value last = top_rcode(*rcode);
pop_rcode(rcode);
return last;
}
struct Value top_rcode(RawCode rcode)
{
if (rcode.size == 0)
return empty_value;
return rcode.array[rcode.used - 1];
}
</code></pre>
<p><strong>Show.h</strong></p>
<pre><code>#pragma once
#include "Stack.h"
#include "RawCode.h"
#include "Combinator.h"
char* showStack(Stack);
char* showValue(struct Value);
char* showLo(enum LiteralOperation);
char* showQuote(RawCode);
char* showComb(enum Combinator);
</code></pre>
<p><strong>Show.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Stack.h"
#include "Show.h"
#include "RawCode.h"
#include "Combinator.h"
char *showValue(struct Value value)
{
char *result;
switch (value.kind)
{
case Val_Integer:
__mingw_asprintf(&result, "%d", value.u.integer_.integer);
break;
case Val_String:
__mingw_asprintf(&result, "\"%s\"", value.u.string_.string);
break;
case Val_Word:
__mingw_asprintf(&result, "%s", value.u.word_.word);
break;
case Val_Quotation:
__mingw_asprintf(&result, "%s", showQuote(*value.u.quote_.quote));
break;
case Val_Combinator:
__mingw_asprintf(&result, "%s", showComb(value.u.comb_.comb));
break;
case Val_Empty:
return ""; // 'empty-stack
case Val_LiteralOperation:
__mingw_asprintf(&result, showLo(value.u.literalOperation_.literalOperation));
break;
default:
return "'Unknown";
}
return result;
}
char *showComb(enum Combinator comb)
{
return (char *)Str_Combs[(int)comb];
}
char *showLo(enum LiteralOperation lo)
{
switch (lo)
{
case ADD:
return "+";
case SUB:
return "-";
case MUL:
return "*";
case DIV:
return "/";
}
return "??";
}
char *showStack(Stack stack)
{
char *result;
__mingw_asprintf(&result, "[ ");
for (size_t i = 0; i < stack.used; i++)
{
if (stack.used >= 100 && i == 50)
{
i = stack.used - 1;
__mingw_asprintf(&result, "%s (...) ", result);
}
__mingw_asprintf(&result, "%s%s ", result, showValue(stack.array[i]));
}
__mingw_asprintf(&result, "%s]", result);
return result;
}
char *showQuote(RawCode rcode)
{
if (rcode.used >= 50)
return "[...]";
char *result;
__mingw_asprintf(&result, "[");
for (size_t i = 0; i < rcode.used; i++)
{
if (rcode.used >= 100 && i == 50)
{
i = rcode.used - 1;
__mingw_asprintf(&result, "%s (...) ", result);
}
__mingw_asprintf(&result, "%s%s ", result, showValue(rcode.array[i]));
}
__mingw_asprintf(&result, "%s\b]", result);
return result;
}
</code></pre>
<p><strong>Stack.h</strong></p>
<pre><code>#pragma once
#include <stdio.h>
#include <stdbool.h>
#include "RawCode.h"
typedef struct Stack
{
struct Value *array;
size_t used;
size_t size;
} Stack;
void init_stack(Stack *, size_t);
// Adds an item to the top of the stack
void push(Stack *, struct Value);
// Removes the most recently added item
void pop(Stack *);
// Removes the most recently added item and returns it
struct Value drop(Stack *);
// Gets the last added item => the top of the stack
struct Value top(Stack);
struct Value *top_ptr(Stack *);
struct Value *topx_ptr(Stack *, const size_t);
</code></pre>
<p><strong>Stack.c</strong></p>
<pre><code>#include <stdlib.h>
#include <string.h>
#include "Stack.h"
void init_stack(Stack *stack, const size_t initSize)
{
stack->array = (struct Value *)malloc(initSize * sizeof(struct Value));
stack->used = 0;
stack->size = initSize;
}
void push(Stack *stack, const struct Value item)
{
if (stack->used == stack->size)
{
stack->size *= 2;
stack->array = (struct Value *)realloc(stack->array, stack->size * sizeof(struct Value));
if (stack->array == NULL)
perror("Out of stack memory");
}
stack->array[stack->used++] = item;
}
void pop(Stack *stack)
{
stack->array[stack->used == 0 ? 0 : stack->used--];
}
struct Value drop(Stack *stack)
{
struct Value last = top(*stack);
pop(stack);
return last;
}
struct Value top(const Stack stack)
{
return stack.used == 0 ? empty_value : stack.array[stack.used - 1];
}
struct Value *top_ptr(Stack *stack)
{
return &stack->array[stack->used - 1];
}
struct Value *topx_ptr(Stack *stack, const size_t x)
{
return &stack->array[stack->used - x];
}
</code></pre>
<p><strong>main.c</strong></p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include "Interpret.h"
#include "RawCode.h"
#include "Function.h"
#include "Show.h"
// Define a function that just call itself
void _undefined(struct Dico *dico)
{
RawCode body;
init_rcode(&body, 1);
push_rcode(&body, make_Val_Word("undefined"));
push_dico(dico, make_Function("undefined", body));
}
// Define a function with a const value
void _const(struct Dico *dico)
{
RawCode body;
init_rcode(&body, 1);
push_rcode(&body, make_Val_Integer(42));
push_dico(dico, make_Function("const", body));
}
// Define the factorial function
void _fac(struct Dico *dico)
{
// fac = dup 1 lowereq [pop 1] [dup -- fac *] if
RawCode body;
init_rcode(&body, 6);
push_rcode(&body, make_Val_Combinator(DUP));
push_rcode(&body, make_Val_Integer(1));
push_rcode(&body, make_Val_Word("lowereq"));
RawCode *if_true = (RawCode *)malloc(sizeof(*if_true));
init_rcode(if_true, 2);
push_rcode(if_true, make_Val_Combinator(POP));
push_rcode(if_true, make_Val_Integer(1));
RawCode *if_false = (RawCode *)malloc(sizeof(*if_false));
init_rcode(if_false, 4);
push_rcode(if_false, make_Val_Combinator(DUP));
push_rcode(if_false, make_Val_Integer(1));
push_rcode(if_false, make_Val_LiteralOperation(SUB));
push_rcode(if_false, make_Val_Word("fac"));
push_rcode(if_false, make_Val_LiteralOperation(MUL));
push_rcode(&body, make_Val_Quotation(if_true));
push_rcode(&body, make_Val_Quotation(if_false));
push_rcode(&body, make_Val_Word("if"));
push_dico(dico, make_Function("fac", body));
}
int main(void)
{
struct Dico dico;
RawCode rcode;
init_dico(&dico, 1);
init_rcode(&rcode, 1);
_undefined(&dico);
_fac(&dico);
_const(&dico);
push_rcode(&rcode, make_Val_Integer(4000));
push_rcode(&rcode, make_Val_Word("fac"));
// So now, the raw code is like `5 fac`
// The interpreter will interpret that and return 120
Stack result = interpret(rcode, dico);
printf("%s\n", showStack(result));
return 0;
}
</code></pre>
<p>PS: I use a function specific to MINGW in the <strong>Show.c</strong> file, it is <code>__mingw_asprintf</code>. If there are compilation problems, it probably comes from there, so it has to be removed.</p>
<p>PPS: Here is <a href="https://drive.google.com/file/d/114i0fI8sKlTSY7h6Jej2zJCbxq7QhUWI/view?usp=sharing" rel="nofollow noreferrer">a link to download the files</a>.</p>
|
[] |
[
{
"body": "<h2>Convenience <code>typedef</code>s</h2>\n\n<p>Consider adding convenience <code>typedef</code> declarations on your <code>struct</code>s and <code>enum</code>s, i.e.</p>\n\n<pre><code>struct Value {\n // ...\n};\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>typedef struct ValueTag {\n // ...\n} Value;\n</code></pre>\n\n<p>You've already done this with <code>Stack</code>, though I recommend renaming the tag:</p>\n\n<pre><code>typedef struct TagStack\n{\n struct Value *array;\n size_t used;\n size_t size;\n} Stack;\n</code></pre>\n\n<h2>Uniformity of reference</h2>\n\n<pre><code>struct Value top(const Stack stack)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>struct Value top(const Stack *stack)\n</code></pre>\n\n<p>since your other functions (correctly) accept pointers. Also, have a read through this:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/44157072/const-in-c-function-declaration-and-implementation\">https://stackoverflow.com/questions/44157072/const-in-c-function-declaration-and-implementation</a></p>\n\n<p>Your declaration and definition should agree on the <code>const</code>-ness of the argument.</p>\n\n<h2>Makefile variables</h2>\n\n<p>This:</p>\n\n<pre><code>OBJS = Combinator.o Function.o Interpret.o RawCode.o Stack.o Show.o\n</code></pre>\n\n<p>shouldn't include <code>.o</code> in its members. For more flexibility, to get this list just use extension substitution, a la</p>\n\n<p><a href=\"https://stackoverflow.com/questions/12069457/how-to-change-the-extension-of-each-file-in-a-list-with-multiple-extensions-in-g#12071918\">https://stackoverflow.com/questions/12069457/how-to-change-the-extension-of-each-file-in-a-list-with-multiple-extensions-in-g#12071918</a></p>\n\n<h2>Use auto-variables</h2>\n\n<p>in this:</p>\n\n<pre><code>main : ${OBJS} main.o\n @echo Linking...\n ${CC} ${CCFLAGS} ${OBJS} main.o -o main\n</code></pre>\n\n<p>you can instead do</p>\n\n<pre><code>main: main.o ${OBJS}\n @echo Linking...\n ${CC} ${CCFLAGS} $^ -o $@\n</code></pre>\n\n<p>Refer to <a href=\"https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html\" rel=\"nofollow noreferrer\">https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html</a></p>\n\n<h2>Object compilation</h2>\n\n<p>For these rules:</p>\n\n<pre><code>Stack.o : Stack.c\n ${CC} ${CCFLAGS} -c Stack.c\n</code></pre>\n\n<p>In the typical case you shouldn't even need to define them; make has a built-in extension-based rule for this. If you insist on defining it yourself, then you should use a pattern rule covering all of your objects at once; refer to</p>\n\n<p><a href=\"https://www.gnu.org/software/make/manual/html_node/Pattern-Rules.html\" rel=\"nofollow noreferrer\">https://www.gnu.org/software/make/manual/html_node/Pattern-Rules.html</a></p>\n\n<h2>Memory span fragility</h2>\n\n<p>This:</p>\n\n<pre><code>if (dico->used == dico->size)\n{\n dico->size *= 2;\n</code></pre>\n\n<p>is slightly fragile in an edge case: what if <code>used</code> exceeds <code>size</code>? Even if this \"shouldn't usually happen\", it's better to write it as if it could:</p>\n\n<pre><code>if (dico->used >= dico->size)\n{\n dico->size = 2*dico->used;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T18:08:03.183",
"Id": "449400",
"Score": "0",
"body": "Thanks for these tips; I didn't know the tips about makefile either, it makes life easier.\nHowever, do you have any other ideas about my question on recursion about user-defined functions?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:38:39.267",
"Id": "230607",
"ParentId": "230595",
"Score": "3"
}
},
{
"body": "<h1>Use X-Macro to construct parallel enum and array</h1>\n\n<p>As the number of items increases, so does the effort required to keep the parallel constructions in sync.</p>\n\n<pre><code>enum Combinator\n { POP, DUP, SWAP\n , FLIP, ID, QUOTE\n , UNQUOTE, UNKNOWN };\n\nstatic const char Str_Combs[][8] =\n { \"pop\", \"dup\", \"swap\"\n , \"flip\", \"id\", \"quote\"\n , \"unquote\" };\n</code></pre>\n\n<p>Instead, you can make a single list as a parameterized macro.</p>\n\n<pre><code>#define COMBINATORS(macro) \\\n macro( POP, \"pop\" ), \\\n macro( DUP, \"dup\" ), \\\n macro( SWAP, \"swap\" ), \\\n macro( FLIP, \"flip\" ) /* etc */\n\n#define COMBINATOR_ENUM(a,b) a\nenum Combinator { COMBINATORS(COMBINATOR_ENUM) };\n\n#define COMBINATOR_STRING(a,b) b\nstatic const char Str_Combs[][8] = { COMBINATORS(COMBINATOR_STRING) };\n</code></pre>\n\n<p>When you add more items, the enum and the array will always remain in sync. If you don't mind having the two parts in the same case, you could also simplify the table and use stringify to produce the string.</p>\n\n<pre><code>#define COMBINATORS(macro) \\\n macro( POP ), \\\n macro( DUP ), \\\n macro( SWAP ), \\\n macro( FLIP ) /* etc */\n\n#define COMBINATOR_ENUM(a) a\nenum Combinator { COMBINATORS(COMBINATOR_ENUM) };\n\n#define COMBINATOR_STRING(a) #a\nstatic const char Str_Combs[][8] = { COMBINATORS(COMBINATOR_STRING) };\n</code></pre>\n\n<p>This makes the list even easier to maintain.</p>\n\n<h1>Loops and Recursion in the language</h1>\n\n<p>See <a href=\"https://stackoverflow.com/questions/6949434/how-to-implement-loop-in-a-forth-like-language-interpreter-written-in-c\">my answer on SO</a> for implementing user functions with a stack. To allow for infinite loops or recursion, the important part is using a tail-recursion optimization. For stack based languages, the easy thing to do is pop the array when you get to the last element so the empty \"tails\" are no longer on the stack while you execute the last element.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-12T19:34:19.083",
"Id": "232276",
"ParentId": "230595",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230607",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T12:56:52.963",
"Id": "230595",
"Score": "4",
"Tags": [
"performance",
"c",
"recursion",
"functional-programming",
"interpreter"
],
"Title": "User defined function call on a stack based interpreter for concatenative language"
}
|
230595
|
<p>I have a table called <code>sales</code> and it has below columns:</p>
<pre><code>'id'
'product_type'
'soldDate'
'text'
</code></pre>
<p><code>'product_type'</code> examples are: <code>Tshirt-XL</code>, <code>Tshirt-L</code>, <code>Tshirt-M</code>, <code>Trousers-XL</code>, <code>Trousers-L</code>, <code>Trousers-M</code> etc.</p>
<p>I have an array called <code>products</code> which is;</p>
<p><code>$products = array('Tshirt','Trausers');</code></p>
<p>My output is after executing below code:</p>
<p><strong>Tshirt</strong></p>
<p>Tshirt-L</p>
<ul>
<li>lorem impsum dolat</li>
</ul>
<p>Tshirt-XL</p>
<ul>
<li>lorem impsum.</li>
<li>another text. ball.</li>
</ul>
<p><strong>Trousers</strong></p>
<ul>
<li>Trousers-M</li>
</ul>
<p>text for this one.</p>
<p>And the code itself:</p>
<pre><code>$products = array('Tshirt','Trousers');
foreach ($products as $product) {
echo "<b>";
echo $product;
echo "</b><br>";
$q = "
SELECT *,
SUBSTRING_INDEX(product_type, '-', 1) AS product_typeMain
FROM sales
WHERE SUBSTRING_INDEX(product_type, '-', 1) = '".$product."'";
$statement = $db->prepare($q);
$results = $statement->execute();
$results = $statement->fetchAll();
$unique_product_types = array();
foreach($results as $filter_result){
if ( in_array($filter_result->product_type, $unique_product_types) ) {
continue;
}
$unique_product_types[] = $filter_result->product_type;
echo $filter_result->product_type;
echo "<br>";
$q = "
SELECT *
FROM sales
WHERE product_type = '".$filter_result->product_type."'
";
$statement = $db->prepare($q);
$results = $statement->execute();
$results = $statement->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $value) {
echo "<li>".$value->text."</li>";
}
}
}
</code></pre>
<p>I know there are so many foreach loops, so many queries. Also I have worries about performance (more than 100.000 rows, and more than 100 product_type.) Plus I will need to add another query in last foreach loop to make searches (multiple, not one).</p>
<p>I am looking forward to hear best practices to improve. Thanks in advance. </p>
|
[] |
[
{
"body": "<p>PDO has some rather handy fetching options. <code>FETCH_GROUP</code> is good for grouping the first level (product categories), but some extra handling is necessary to group the second level (product name-sizes). To perform this nested grouping, I'll show the implementation of a temporary variable to track whether or not the current iteration is processing a new group or the same group as the previous iteration.</p>\n\n<ul>\n<li>It is important to point out that you should not be making multiple trips to the database. Since this script can be sensibly executed with a single trip to the database, it should be.</li>\n<li>Prepared statements should be used for stability/security.</li>\n<li><code><li></code> tags must live inside <code><ul></code> tags for proper html markup.</li>\n</ul>\n\n<p>Tested Code:</p>\n\n<pre><code>$products = ['Tshirt', 'Trousers'];\n$placeholders = str_repeat('?,', count($products) - 1) . '?';\n\n$stmt = $conn->prepare(\"\n SELECT SUBSTRING_INDEX(product_type, '-', 1) AS product_group, product_type, text \n FROM sales\n WHERE SUBSTRING_INDEX(product_type, '-', 1) IN ($placeholders)\n ORDER BY product_type\n \");\n$stmt->execute($products);\n$results = $stmt->fetchAll(PDO::FETCH_GROUP);\nforeach ($results as $productGroup => $subarray) {\n echo \"<div>{$productGroup}</div>\";\n $typeGroup = null;\n foreach ($subarray as $row) {\n if ($row['product_type'] != $typeGroup) {\n if ($typeGroup) {\n echo \"</ul></ul>\";\n }\n echo \"<ul><li>{$row['product_type']}</li><ul>\";\n }\n echo \"<li>{$row['text']}</li>\";\n $typeGroup = $row['product_type'];\n }\n echo \"</ul></ul>\";\n}\n</code></pre>\n\n<p>Sample data / Rendered output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/t0kqy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/t0kqy.png\" alt=\"enter image description here\"></a></p>\n\n<p><sub>...yeah, didn't try very hard on the images.</sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T04:48:38.357",
"Id": "230628",
"ParentId": "230599",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230628",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T15:35:44.770",
"Id": "230599",
"Score": "1",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "Categorize & sub categorize from contents of one row and more execute even more queries in results"
}
|
230599
|
<p>I am trying to solve this problem</p>
<blockquote>
<p>You are given a list of non-negative integers, a1, a2, ..., an, and a
target, S. Now you have 2 symbols + and -. For each integer, you
should choose one from + and - as its new symbol.</p>
<p>Find out how many ways to assign symbols to make sum of integers equal
to target S.</p>
</blockquote>
<p>My working solution that times out:</p>
<pre><code>class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
ways = 0
def dfs(index, s):
nonlocal ways
if index == len(nums):
if s == 0:
ways +=1
else:
dfs(index+1, s-nums[index])
dfs(index+1, s+nums[index])
dfs(0, S)
return ways
</code></pre>
<p>How to optimize this in terms of time complexity?</p>
<p>Please refrain from commenting that the method can exist as a function on its own; this is the template that leetcode uses and can't be changed.</p>
<p><a href="https://leetcode.com/problems/target-sum/" rel="nofollow noreferrer">https://leetcode.com/problems/target-sum/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T15:49:12.280",
"Id": "449380",
"Score": "0",
"body": "*“Please refrain from commenting that the method can exist as a function on its own”* – The policy on this site is that an answer can review any aspect of the posted code. Related on meta: https://codereview.meta.stackexchange.com/q/9345/35991."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:24:15.113",
"Id": "449381",
"Score": "0",
"body": "Consider it leetcode's mistake for encouraging bad coding practices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:50:34.137",
"Id": "449386",
"Score": "1",
"body": "When I run that code with the input from the assignment,it doesn't time out. What inputs did you use that broke it ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T02:19:17.160",
"Id": "449542",
"Score": "0",
"body": "you need to keep the information of already calculated steps for saving time aka memoization"
}
] |
[
{
"body": "<p>Python has a recursion limit. By default, this is only about 1000 stack levels deep, and depending on your input, that cap might be reached by your recursion. </p>\n\n<p>If you used the same input as the assignment did, then I have a rather hard time believing you timed out. Your function would be called only 1+2^4 = 17 times. </p>\n\n<p>I ran it with the assignment inputs and it finished straight away.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:47:08.997",
"Id": "449385",
"Score": "4",
"body": "This should essentially exist as a comment, not an answer - it's a prompt for more detail"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:51:22.363",
"Id": "449387",
"Score": "0",
"body": "Edited it. Now it describes the most probably cause for timing out like he did, and removed the info prompt part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T17:17:19.050",
"Id": "449390",
"Score": "0",
"body": "@Gloweye did it pass all test cases? If so, please post the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T17:24:49.293",
"Id": "449394",
"Score": "0",
"body": "@Gloweye: The array can have up to 20 elements, that makes 2^20 = 1048576 function calls, and that *might* be a reason for the timeout."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T18:47:21.147",
"Id": "449403",
"Score": "0",
"body": "I must have missed that bit in the explanation on that other side, then. @nz_21, please do edit those testcases into your question."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:38:45.327",
"Id": "230608",
"ParentId": "230600",
"Score": "1"
}
},
{
"body": "<p>Your solution computes <em>all</em> possible target sums that are obtained by distributing the signs <span class=\"math-container\">\\$+1\\$</span> and <span class=\"math-container\">\\$-1\\$</span> to the numbers. For an array with <span class=\"math-container\">\\$n\\$</span> numbers that are <span class=\"math-container\">\\$2^n\\$</span> combinations.</p>\n\n<p>This is a typical case where <a href=\"https://en.wikipedia.org/wiki/Dynamic_programming\" rel=\"nofollow noreferrer\">dynamic programming</a> is of advantage. Instead of searching for all combinations which lead to the target sum <span class=\"math-container\">\\$S\\$</span>, one computes the number of combinations leading to <em>any</em> target sum in a range.</p>\n\n<p>The crucial hint here is</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>The sum of elements in the given array will not exceed 1000.</li>\n </ol>\n</blockquote>\n\n<p>which means that only target sums between <span class=\"math-container\">\\$-1000\\$</span> and <span class=\"math-container\">\\$1000\\$</span> can be obtained by distributing the signs <span class=\"math-container\">\\$+1\\$</span> and <span class=\"math-container\">\\$-1\\$</span> to the numbers, that are “only” <span class=\"math-container\">\\$2001\\$</span> possible target sums.</p>\n\n<p>So the idea is to maintain a list <code>L</code> of length <span class=\"math-container\">\\$2001\\$</span>, corresponding to the possible target sums <span class=\"math-container\">\\$-1000 \\ldots 1000\\$</span>. At each point in the following iteration <code>L[i + 1000]</code> is the number of ways to obtain the target sum <code>i</code> with the numbers encountered so far.</p>\n\n<p>Initially, <code>L[1000] = 0</code> and all other entries are zero, because <code>0</code> is the only target sum that can be obtained using none of the numbers.</p>\n\n<p>Then you iterate over the given array of numbers and update the list <code>L</code>.</p>\n\n<p>Ultimately, <code>L[S + 1000]</code> is the wanted number of ways to obtain the target sum <code>S</code> using all the given numbers.</p>\n\n<p>This approach has <span class=\"math-container\">\\$ O(n) \\$</span> time complexity, which is asymptotially much better than <span class=\"math-container\">\\$O(2^n)\\$</span> of your original approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T17:04:52.240",
"Id": "449389",
"Score": "0",
"body": "And I don't want to deprive you from the satisfaction to implement that successfully, therefore I don't post any code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T02:18:10.457",
"Id": "449541",
"Score": "0",
"body": "Space complexity : O(n). The depth of recursion tree can go upto n - It should be O(l*n)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T04:44:39.157",
"Id": "449550",
"Score": "1",
"body": "@prashantrana: Yes, but what I meant is the *time* complexity, and that is O(2^n) for the original algorithm."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T17:03:24.360",
"Id": "230609",
"ParentId": "230600",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230609",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T15:38:22.107",
"Id": "230600",
"Score": "4",
"Tags": [
"python",
"algorithm",
"time-limit-exceeded"
],
"Title": "Target Sum leetcode"
}
|
230600
|
<p>I implemented a Column-based FLAT parser and generator, where the information is loaded from a base class, which contains the attributes that tell the column size and type.
For each line of the flat file, a new instance of this class is generated which in turn is loaded with the file line data.</p>
<p>My question is, what can be improved in the code to make it more efficient?</p>
<p>Some kind of optimization in the reflection of the attributes maybe?</p>
<p>The source code:</p>
<p><strong>DataType.cs</strong></p>
<pre><code>namespace FlatParser
{
public enum DataType
{
NUMERIC,
ALPHANUMERIC,
DATETIME,
IGNORE_FIELD
}
}
</code></pre>
<p><strong>FileReader.cs</strong></p>
<pre><code>using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlatParser
{
public class FileReader : IDisposable
{
private StreamReader Reader { get; set; }
public int CurrentLineNumber { get; private set; }
public string CurrentLine { get; private set; }
public bool EOF { get; private set; } = false;
public FileReader(string path)
: this(path, Encoding.GetEncoding(1252))
{
}
public FileReader(string path, Encoding encoding)
{
Reader = new StreamReader(path, encoding);
}
public void Dispose()
{
Reader.Dispose();
}
public virtual bool ReadLine()
{
while(true)
{
CurrentLine = Reader.ReadLine();
if(CurrentLine == null)
{
Reader.Close();
CurrentLine = String.Empty;
EOF = true;
return false;
}
CurrentLineNumber++;
if (CurrentLine.Length > 0)
break;
}
return true;
}
}
}
</code></pre>
<p><strong>LayoutAttribute.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlatParser
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class LayoutAttribute : Attribute
{
public int LineSize { get; private set; }
public LayoutAttribute(int lineSize)
{
LineSize = lineSize;
}
}
}
</code></pre>
<p><strong>LayoutDetailsAttribute.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FlatParser.Exceptions;
namespace FlatParser
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class LayoutDetailsAttribute : Attribute
{
public int StartPosition { get; private set; }
public int EndPosition { get; private set; }
public DataType _DataType { get; private set; }
public string FormatoDateTime { get; private set; }
public string DefaultValue { get; private set; }
public LayoutDetailsAttribute(int startPosition, int endPosition, DataType datatype, string defaultValue = null)
: this(startPosition, endPosition, datatype, null, defaultValue)
{
}
public LayoutDetailsAttribute(int startPosition, int endPosition, DataType datatype, string dateTimeFormat, string defaultValue = null)
{
if (startPosition >= 0 && endPosition >= startPosition)
{
StartPosition = startPosition;
EndPosition = endPosition;
_DataType = datatype;
if (datatype == DataType.DATETIME && (dateTimeFormat == null || dateTimeFormat.Trim().Length == 0))
throw new FlatParserException("Deve ser informado o formato da data quando utilizado datetime para o tipo do layout");
else
FormatoDateTime = dateTimeFormat;
DefaultValue = defaultValue;
}
else
throw new FlatParserException("Posicao inicial deve ser maior ou igual a posicao final");
}
}
}
</code></pre>
<p><strong>LayoutUtility.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using FlatParser.Exceptions;
namespace FlatParser
{
public abstract class LayoutUtility
{
public void Parse(string input)
{
if (!String.IsNullOrEmpty(input))
{
// Get the class attributes...
{
var classAttribute = GetType().GetCustomAttribute<LayoutAttribute>();
if (input.Length != classAttribute.LineSize)
throw new DefaultFieldException("Tamanho da linha invalido");
}
foreach (PropertyInfo property in GetType().GetProperties())
{
Attribute attribute = null;
// para propriedades da classe sem atributos ou type IGNORED_FIELD (campo que não refletem posição do arquivo lido)
try
{
attribute = (Attribute)property.GetCustomAttributes(true).First();
var typeAttributeTest = attribute as LayoutDetailsAttribute;
if (typeAttributeTest._DataType == DataType.IGNORE_FIELD)
continue;
}
catch (Exception)
{
continue;
}
LayoutDetailsAttribute layoutAttribute = attribute as LayoutDetailsAttribute;
if (null != layoutAttribute)
{
string tmp = string.Empty;
if (layoutAttribute.StartPosition <= input.Length - 1)
{
tmp = input.Substring(layoutAttribute.StartPosition, Math.Min((layoutAttribute.EndPosition - layoutAttribute.StartPosition + 1), input.Length - layoutAttribute.StartPosition));
}
switch (layoutAttribute._DataType)
{
case DataType.ALPHANUMERIC:
tmp = tmp.TrimEnd();
break;
}
if (layoutAttribute.DefaultValue != null && layoutAttribute.DefaultValue.Trim().Length > 0)
{
string dfTmp = tmp;
if (dfTmp.Length < layoutAttribute.DefaultValue.Length)
{
if (layoutAttribute._DataType == DataType.ALPHANUMERIC)
dfTmp = dfTmp.PadRight(layoutAttribute.EndPosition - layoutAttribute.StartPosition + 1, ' ');
else if (layoutAttribute._DataType == DataType.NUMERIC)
dfTmp = dfTmp.PadLeft(layoutAttribute.EndPosition - layoutAttribute.StartPosition + 1, '0');
}
if (dfTmp != layoutAttribute.DefaultValue)
{
throw new DefaultFieldException(String.Format("O campo {0} não contem o valor \"{1}\"", property.Name, layoutAttribute.DefaultValue));
}
}
if (layoutAttribute._DataType != DataType.DATETIME)
property.SetValue(this, tmp, null);
else
{
try
{
DateTime dt;
if (DateTime.TryParseExact(tmp, layoutAttribute.FormatoDateTime, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
property.SetValue(this, dt, null);
else
property.SetValue(this, null, null);
}
catch (Exception)
{
throw new DefaultFieldException(String.Format("O campo {0} não é válido para data", property.Name));
}
}
}
}
}
}
public override string ToString()
{
var classAttribute = GetType().GetCustomAttribute<LayoutAttribute>();
StringBuilder result = new StringBuilder(String.Empty.PadLeft(classAttribute.LineSize, ' '));
foreach (PropertyInfo property in GetType().GetProperties())
{
foreach (Attribute attribute in property.GetCustomAttributes(false))
{
var typeAttributeTest = attribute as LayoutDetailsAttribute;
if (typeAttributeTest._DataType == DataType.IGNORE_FIELD)
continue;
LayoutDetailsAttribute layoutAttribute = attribute as LayoutDetailsAttribute;
if (null != layoutAttribute)
{
string propertyValue = String.Empty;
if (layoutAttribute._DataType == DataType.ALPHANUMERIC || layoutAttribute._DataType == DataType.NUMERIC)
{
var prop = property.GetValue(this, null);
if (prop != null)
propertyValue = (string)property.GetValue(this, null);
}
else
{
var prop = (DateTime?)property.GetValue(this, null);
if (prop == null)
{
propertyValue = (String.Empty).PadLeft(layoutAttribute.FormatoDateTime.Length, '0');
}
else if (prop.Value.Day == 1 && prop.Value.Month == 1 && prop.Value.Year == 1)
{
propertyValue = (String.Empty).PadLeft(layoutAttribute.FormatoDateTime.Length, '0');
//propertyValue = DateTime.Today.ToString(layoutAttribute.FormatoDateTime);
}
else
propertyValue = ((DateTime)prop).ToString(layoutAttribute.FormatoDateTime);
}
// Tem valor default
if (layoutAttribute.DefaultValue != null && layoutAttribute.DefaultValue.Trim().Length > 0)
propertyValue = layoutAttribute.DefaultValue;
switch (layoutAttribute._DataType)
{
case DataType.ALPHANUMERIC:
propertyValue = propertyValue.PadRight((layoutAttribute.EndPosition - layoutAttribute.StartPosition) + 1, ' ');
break;
case DataType.NUMERIC:
propertyValue = propertyValue.PadLeft((layoutAttribute.EndPosition - layoutAttribute.StartPosition) + 1, '0');
break;
}
for (int i = 0, j = layoutAttribute.StartPosition; i < propertyValue.Length; i++, j++)
result[j] = propertyValue[i];
}
break;
}
}
return result.ToString().ToUpper();
}
public abstract bool IsValid();
}
}
</code></pre>
<p>Test source file:</p>
<p><strong>Header.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FlatParser;
namespace FlatFileTest
{
[Layout(lineSize: 1200)]
public class Header : LayoutUtility
{
[LayoutDetails(0, 0, DataType.ALPHANUMERIC)]
public string TIPO_DE_REGISTRO { get; set; }
//[LayoutDetails(1, 16, DataType.ALPHANUMERIC)]
//public string FILLER0 { get; set; }
[LayoutDetails(17, 27, DataType.ALPHANUMERIC)]
public string NOME_DO_ARQUIVO { get; set; }
[LayoutDetails(28, 35, DataType.DATETIME, dateTimeFormat: "yyyyMMdd")]
public DateTime DATA_DE_GRAVACAO { get; set; }
[LayoutDetails(36, 43, DataType.NUMERIC)]
public string NUMERO_DA_REMESSA { get; set; }
//[LayoutDetails(44, 1198, DataType.ALPHANUMERIC)]
//public string FILLER1 { get; set; }
[LayoutDetails(1199, 1199, DataType.ALPHANUMERIC)]
public string FIM { get; set; }
public override bool IsValid()
{
throw new NotImplementedException();
}
}
}
</code></pre>
<p><strong>main.cs</strong></p>
<pre><code>static void Teste()
{
using (FileReader fr = new FileReader("file.txt", Encoding.GetEncoding(1252)))
{
var header = new Header();
header.Parse(fr.CurrentLine);
Console.WriteLine(header.DATA_DE_GRAVACAO.ToString("dd/MM/yyyy"));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T20:40:48.253",
"Id": "449414",
"Score": "0",
"body": "What is a flat parser, a parser of real estate?"
}
] |
[
{
"body": "<p>Let’s capture parsing/formatting logic in the attributes to simplify extensibility. You would need to inherit the following base attribute class to define new column types:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Property)]\npublic abstract class FieldAttribute : Attribute\n{\n protected FieldAttribute(int length, int order) => \n Length = length;\n\n public int Length { get; }\n public int AbsLength => Math.Abs(Length);\n public int Order { get; }\n protected abstract string Format(object value);\n protected abstract object Parse(string text);\n\n public string this[PropertyInfo property, object record]\n {\n get => Clip(Align(Format(property.GetValue(record)))); \n set => property.SetValue(record, \n Convert.ChangeType(\n Parse(value.Trim()), property.PropertyType));\n }\n\n string Align(string text) =>\n Length > 0 ? text.PadRight(AbsLength) : text.PadLeft(AbsLength);\n\n string Clip(string text) => \n text.Substring(0, AbsLength);\n}\n</code></pre>\n\n<p>As you can see the negative <code>Length</code> value right-aligns the content.</p>\n\n<p>Now some concrete field type specializations:</p>\n\n<pre><code>public class TextAttribute : FieldAttribute\n{\n public TextAttribute(int length, [CallerLineNumber] int order = 0)\n : base(length, order)\n {\n }\n\n protected override string Format(object value) => $\"{value}\";\n protected override object Parse(string text) => text;\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>public class NumberAttribute : FieldAttribute\n{\n public NumberAttribute(int length, [CallerLineNumber] int order = 0)\n : base(length, order)\n {\n }\n\n protected override string Format(object value) => $\"{value}\";\n protected override object Parse(string text) => decimal.Parse(text);\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>public class DateAttribute : FieldAttribute\n{\n public DateAttribute(int length, [CallerLineNumber] int order = 0) \n : base(length, order)\n {\n }\n\n protected override string Format(object value) => $\"{value:yyyyMMdd}\";\n protected override object Parse(string text) => \n DateTime.ParseExact(text, \"yyyyMMdd\", CultureInfo.InvariantCulture);\n}\n</code></pre>\n\n<p>The next step would be to create a serializer which caches the schema provided by reflection:</p>\n\n<pre><code>public class Serializer<T> where T : new()\n{\n static IEnumerable<(PropertyInfo Property, FieldAttribute Attribute)> Schema { get; } =\n typeof(T).GetProperties()\n .SelectMany(p => from a in p.GetCustomAttributes(true).OfType<FieldAttribute>()\n orderby a.Order ascending\n select (p, a))\n .ToArray();\n\n public static T Parse(string line)\n {\n var record = new T();\n var start = 0;\n foreach (var (property, attribute) in Schema)\n {\n attribute[property, record] = line.Substring(start, attribute.AbsLength);\n start += attribute.AbsLength;\n }\n\n return record;\n }\n\n public static string Format(T record) =>\n string.Join(\"\", from f in Schema\n select f.Attribute[f.Property, record]);\n}\n</code></pre>\n\n<p>Now let’s define loading/saving:</p>\n\n<pre><code>public class File<THeader, TRecord> \n where THeader: new()\n where TRecord: new()\n{\n public static File<THeader, TRecord> Parse(string text) =>\n Load(new StringReader(text));\n\n public static File<THeader, TRecord> Load(string path) =>\n Load(new StreamReader(path));\n\n public static File<THeader, TRecord> Load(TextReader reader)\n {\n using (reader)\n return new File<THeader, TRecord>(\n Serializer<THeader>.Parse(reader.ReadLine()),\n Enumerable.Range(0, int.MaxValue)\n .Select(i => reader.ReadLine())\n .TakeWhile(s => s != null)\n .Select(s => Serializer<TRecord>.Parse(s)));\n }\n\n public File()\n : this(new THeader(), new TRecord[0])\n {\n }\n\n File(THeader header, IEnumerable<TRecord> records) =>\n (Header, Records) = (header, records.ToList());\n\n public THeader Header { get; } \n public IList<TRecord> Records { get; }\n\n public override string ToString() => \n string.Join(Environment.NewLine,\n Records.Select(Serializer<TRecord>.Format)\n .Prepend(Serializer<THeader>.Format(Header)));\n\n public void Save(string path) =>\n Save(new StreamWriter(path));\n\n public void Save(TextWriter writer)\n {\n using (writer)\n writer.WriteLine(ToString());\n }\n}\n</code></pre>\n\n<p>We are ready to test (note the localization support):</p>\n\n<pre><code>[TestClass]\npublic class File_Should\n{\n [TestMethod]\n public void Serialize()\n {\n var file = new File<FileHeader, FileRecord>();\n file.Records.Add(new FileRecord\n {\n Name = \"Thomas Jefferson\",\n Born = new DateTime(1743, 04, 13),\n Age = 83\n });\n\n var s = file.ToString();\n var copy = File<FileHeader, FileRecord>.Parse(s);\n\n Assert.AreEqual(\"Имя\", copy.Header.Name);\n Assert.AreEqual(\"ДР\", copy.Header.Born);\n Assert.AreEqual(\"Возраст\", copy.Header.Age);\n Assert.AreEqual(\"Thomas Jefferson\", copy.Records[0].Name);\n Assert.AreEqual(new DateTime(1743, 04, 13), copy.Records[0].Born);\n Assert.AreEqual(83, copy.Records[0].Age);\n }\n}\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>class FileHeader\n{\n [Text(20)] public string Name { get; set; } = \"Имя\";\n [Text(10)] public string Born { get; set; } = \"ДР\";\n [Text(10)] public string Age { get; set; } = \"Возраст\";\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>class FileRecord\n{\n [Text(20)] public string Name { get; set; }\n [Date(-10)] public DateTime Born { get; set; }\n [Number(-10)] public int Age { get; set; }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:10:07.083",
"Id": "449613",
"Score": "0",
"body": "thanks! you are awesome!!! I have some questions, let's suppose I have a file in the following format: (header: 0AAAANNN .....), (Record ( type 1 ): 1NNNNNDDD ...), (Record ( type 2 ): 2AAAAAAAA ....), (N records of type 1 and 2), (Trailler: 9SSSSSSS), how can this be implemented in your logic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T04:21:26.607",
"Id": "449724",
"Score": "0",
"body": "@Alexandre Please see my new answer :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:38:40.503",
"Id": "230658",
"ParentId": "230602",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>let's suppose I have a file in the following format: (header: 0AAAANNN .....), (Record ( type 1 ): 1NNNNNDDD ...), (Record ( type 2 ): 2AAAAAAAA ....), (N records of type 1 and 2), (Trailler: 9SSSSSSS), how can this be implemented in your logic?</p>\n</blockquote>\n\n<p>You could use an extension method to parse:</p>\n\n<pre><code>static class RecordReader\n{\n public static Record ReadRecord(this TextReader reader)\n {\n Record Parse<TRecord>(string s) where TRecord : Record, new() =>\n Serializer<TRecord>.Parse(s);\n\n switch (reader.ReadLine())\n {\n case string s when s.StartsWith(\"0\"):\n return Parse<Record0>(s);\n case string s when s.StartsWith(\"1\"):\n return Parse<Record1>(s);\n case string s when s.StartsWith(\"2\"):\n return Parse<Record2>(s);\n case string s when s.StartsWith(\"9\"):\n return Parse<Record9>(s);\n default:\n return null;\n }\n }\n}\n</code></pre>\n\n<p>Where you have formats defined like:</p>\n\n<pre><code>abstract class Record { }\nclass Record0 : Record { ... }\nclass Record1 : Record { ... }\nclass Record2 : Record { ... }\nclass Record9 : Record { ... }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T04:20:19.400",
"Id": "230734",
"ParentId": "230602",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230658",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T15:59:19.323",
"Id": "230602",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Flat file column based parser"
}
|
230602
|
<p>This code review request follows my previous request <a href="https://codereview.stackexchange.com/questions/226835/computational-verification-of-collatz-conjecture">Computational verification of Collatz conjecture</a>.
Unlike the previous program (which was designed for the CPU), this code should run on modern GPUs.
For this purpose, I chose OpenCL as a programming language.</p>
<h2>Prerequisites</h2>
<p>Since the verification program needs to deal with 128-bit arithmetic, the first thing I was forced to solve is the availability of 128-bit integer type.
So far, I rely on the <code>__int128</code> compiler extension:</p>
<pre><code>typedef unsigned __int128 uint128_t;
</code></pre>
<p>At this point my first question arises:
How efficient (in terms of performance) is this solution?
I also guess it may not be very portable, right?</p>
<p>For completeness, the</p>
<pre><code>#define UINT128_MAX (~(uint128_t)0)
</code></pre>
<p>is maximum value for an object of type <code>uint128_t</code>.</p>
<p>I also needed to calculate the number of trailing zeros (ctz), which I solved as follows:</p>
<pre><code>size_t ctzl(unsigned long n)
{
return 63 - clz(n & -n);
}
size_t ctzu128(uint128_t n)
{
size_t a = ctzl(n);
if (a == ~0UL) {
return 64 + ctzl(n>>64);
}
return a;
}
</code></pre>
<p>My concern here is that this could be implemented more simply.</p>
<p>The last building block I need is the <code>n</code>-th power of three:</p>
<pre><code>uint128_t pow3(size_t n)
{
uint128_t r = 1;
uint128_t b = 3;
while (n) {
if (n & 1) {
r *= b;
}
b *= b;
n >>= 1;
}
return r;
}
</code></pre>
<p>All <span class="math-container">\$ 3^n \$</span> for <span class="math-container">\$ n < 81 \$</span> fit the <code>uint128_t</code> type.
Therefore I have the follow macro defined.</p>
<pre><code>#define LUT_SIZE128 81
</code></pre>
<h2>Code</h2>
<p>My code verifies the convergence of the <a href="https://en.wikipedia.org/wiki/Collatz_conjecture" rel="nofollow noreferrer">Collatz problem</a> using <a href="https://math.stackexchange.com/questions/3330085/computational-verification-of-collatz-problem">this algorithm</a>.
The range of the size <code>2^task_size</code> numbers starting at <code>task_id * 2^task_size</code> is evenly divided among threads.
The threads do not communicate with each other.
When the calculation is complete, each thread stores their results (partial checksum, number of <code>uint128_t</code> overflows) into global memory.
My current solution is as follows:</p>
<pre><code>__kernel void worker(
__global unsigned long *overflow_counter,
__global unsigned long *checksum_alpha,
unsigned long task_id,
unsigned long task_size,
unsigned long task_units)
{
unsigned long private_overflow_counter = 0;
unsigned long private_checksum_alpha = 0;
size_t id = get_global_id(0);
uint128_t lut[LUT_SIZE128];
unsigned long i;
for (i = 0; i < LUT_SIZE128; ++i) {
lut[i] = pow3(i);
}
uint128_t n_ = ((uint128_t)task_id << task_size) + ((uint128_t)(id + 0) << (task_size - task_units)) + 3;
uint128_t n_sup_ = ((uint128_t)task_id << task_size) + ((uint128_t)(id + 1) << (task_size - task_units)) + 3;
for (; n_ < n_sup_; n_ += 4) {
uint128_t n = n_, n0 = n_;
do {
n++;
size_t alpha = ctzu128(n);
private_checksum_alpha += alpha;
n >>= alpha;
if (n > UINT128_MAX >> 2*alpha || alpha >= LUT_SIZE128) {
private_overflow_counter++;
break;
}
n *= lut[alpha];
n--;
n >>= ctzu128(n);
if (n < n0) {
break;
}
} while (1);
}
overflow_counter[id] = private_overflow_counter;
checksum_alpha[id] = private_checksum_alpha;
}
</code></pre>
<p>I see an acceleration of more than two orders of magnitude compared to the CPU implementation.
My main concern (about the performance) here is that the adjacent threads do not go the same code path (the control flow is not coherent for the threads of a processor).
However, I am not sure how big this problem actually is.</p>
|
[] |
[
{
"body": "<ul>\n<li><p>The lookup table <code>lut</code> should be hard-coded in the source code and defined outside the kernel function as a <code>__constant</code> space global variable. As it is now, every thread would have to recalculate the entire table. Also they take too much space for thread's private memory space. Alternately, maybe pre-calculate it on the host and pass it to the kernel in a <code>__constant</code> space argument.</p></li>\n<li><p>The outer <code>for</code> loop should be reformulated so that every thread has the same values for the counter variables, and the number of iterations is a compile-time constant. Then applying <code>#pragma unroll</code> may accelerate it.</p></li>\n<li><p>When code diverges (on NVIDIA), it can become as slow as if the diverging section (i.e. the inner <code>do</code> loop) on threads within each warp (= 32 adjacent threads) were executed sequentially. Maybe somehow change it so that there is no divergence inside warps.</p></li>\n</ul>\n\n<p><strong>Edit:</strong></p>\n\n<ul>\n<li><p>Maybe hardcoding the LUT and putting it into <code>__global</code> memory instead. The GPU would put it into global memory anyways because it is too large for the per-thread private memory. And like that the values don't have to be calculated inside the kernel.</p></li>\n<li><p>It that does not accelerate it, maybe make a copy of it in <code>__local</code> memory (per work group). And copy it from global to local inside the kernel. Then use the shared <code>lut</code>.</p></li>\n<li><p>Do this copy in a <em>coalesced</em> manner, using multiple work items. For example on NVIDIA, each n'th work item of 32 must access the n'th item of 32 from the global memory table.</p></li>\n<li><p>Take the first (always-executed) iteration of the inner <code>do</code> loop outside the loop, and make it execute the next iterations (in a loop), only if it is needed for at least one work item the subgroup, using the <a href=\"https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/cl_khr_subgroups.html\" rel=\"nofollow noreferrer\">subgroup functions</a>.</p></li>\n<li><p>Use an OpenCL profiler (one exists for AMD) to see where the performance losses are. Or port it to CUDA, and use the NVidia Visual Profiler (from the CUDA SDK).</p></li>\n<li><p>Pre-calculate if 128 bit integers are needed for each work item, or if 64 bit (or 32 bit) are sufficient. Then only use 128 bit integers when any work item in the subgroup needs it.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T07:31:36.120",
"Id": "449835",
"Score": "0",
"body": "Thank you for the answer. This is exactly what I needed! Unfortunately, neither of these points led to acceleration (all resulted either in a small or significant slowdown). Probably it is important to note that the most inner do-while loop is executed only once in most cases, in less cases twice, in even less case three times, etc. So the diverge after the first iteration is probably (?) quite quickly resolved. Also rewriting the code so that the for-loop is controlled by exactly same values for the counter does not help. A particular value probably doesn't matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T07:34:39.440",
"Id": "449836",
"Score": "0",
"body": "The __constant space leads to the most significant slowdown. This is probably because all threads access the cache hierarchy at the same time. Leaving the LUT in on-chip memory is much faster. Maybe there's something else I could try?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:21:53.193",
"Id": "449848",
"Score": "0",
"body": "@DaBler updated the answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:40:27.907",
"Id": "450146",
"Score": "0",
"body": "Placing the LUT into `__local` memory really helps a bit. The acceleration is about 3% at Tesla K20Xm and about 1% at GeForce GTX 1050 Ti. It is not much, but after a long time finally something that helped. However, initializing the LUT from global `__constant` memory slows the program down significantly. I guess that calculating the `pow3` is much faster than accessing global memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:49:00.353",
"Id": "450152",
"Score": "0",
"body": "I also guess that the kernel always access the global memory in a coalesced manner. The access pattern is like `array[get_global_id(0)]`. Is that right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T18:49:01.550",
"Id": "450188",
"Score": "0",
"body": "Yes but not sure if GPUs still coalesce the access for 128bit values. Maybe separate it into 2 64bit arrays for the hi and lo part. Or replace the LUT by a function with a large `switch` statement with cases for all 81 values. But it would surely be good to use a profiler (such as AMD CodeXL, or with CUDA the NVVP)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-19T14:40:18.067",
"Id": "450226",
"Score": "0",
"body": "Profiling is surely a good idea. Does also __local memory access require coalescing? Note that the __global memory is only accessed using unsigned long integers, having the access pattern I mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:14:30.343",
"Id": "450880",
"Score": "0",
"body": "I rewrote the multiplication from 128×128 to 128×64 and 128×32, and it really helped a bit again. On my GeForce GTX 1050 Ti, the speedup is about 6 % (comparing the 64-bit implementation to 128-bit) and 31 % (32-bit to 128-bit). On the other hand, on my older machine with GeForce GT 730, the spedup is about 33% (64-bit to 128-bit) and 43 % (32-bit to 128-bit)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:14:37.477",
"Id": "450881",
"Score": "0",
"body": "I believe I can get a much bigger acceleration if I rewrite the whole program only to use only 32×32 multiplication (as the GPUs are 32-bit machines). However, this would not be useful in practice, as such small numbers have been verified for a long time. So working with the 128-bit type cannot be avoided here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:16:34.457",
"Id": "450882",
"Score": "0",
"body": "Either way, this answer helped me a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T07:30:16.443",
"Id": "450884",
"Score": "0",
"body": "GPUs may have instructions for 64bit operations (even if they operate on two registers). Maybe also change the kernel so that 2 work items (or 4) are used for each task, processing the lo and hi parts of the 128bit integer, and using subgroup operations to carry over data."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:12:59.813",
"Id": "230707",
"ParentId": "230606",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230707",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T16:29:34.750",
"Id": "230606",
"Score": "4",
"Tags": [
"c",
"mathematics",
"integer",
"collatz-sequence",
"opencl"
],
"Title": "Computational verification of Collatz conjecture using OpenCL"
}
|
230606
|
<p><strong>EDIT</strong></p>
<p>The random number generator in this code is a blackbox for a similar algorithm that isn't publishable for privacy concern. The algorithm works in similar way, in that it takes in a seed value and generates number.</p>
<p><strong>Simplifying the question</strong></p>
<p>The corrupted references are from a text file, there are thousands of those reference numbers. I'm tasked to create a program that will take in one reference from the text file, then brute force the algorithm through to find the seed that generated the number.</p>
<p>The generated numbers are in reversed, so just brute forcing will not get you the right number, you will have to reverse the brute number and check if it matches with the reference number, if yes then print the seed number and get the next reference number.</p>
<p>Since the seeds value are from 100 million to 999 million, we have to brute force through those to find the right seed value. it takes 4 minute to brute force a single reference number and I have hundreds of thousands of the numbers to go through. How can I make it super fast? </p>
<p>I tried putting the references in arraylist on first load since it's just 900 million list of reference and then use indexOF, but it gives me outofmemory error. </p>
<p>Product Version: Apache NetBeans IDE 9.0 (Build incubator-netbeans-release-334-on-20180708)</p>
<p>Java: 11.0.1; Java HotSpot(TM) 64-Bit Server VM 11.0.1+13-LTS</p>
<p>Runtime: Java(TM) SE Runtime Environment 11.0.1+13-LTS</p>
<p>System: Mac OS X version 10.13.6 running on x86_64; UTF-8; en_GB (nb)</p>
<pre><code>import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.ArrayList;
/**
*
* @author HJoe
*/
public class idResolver {
/**
* @param args
* @throws java.io.FileNotFoundException
* @throws java.io.UnsupportedEncodingException
*/
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
ArrayList corruptedReferences = new ArrayList();
Stream<String> lines = Files.lines(Paths.get("/Users/kingamada/Documents/Corrupted References.txt"));
lines.forEach(l -> {
corruptedReferences.add(l);
});
StringBuilder sb = new StringBuilder();
int max = 1000000000;
int min = 100000000;
long nano_startTime = System.nanoTime();
long millis_startTime = System.currentTimeMillis();
for (int i = 0; i < corruptedReferences.size(); i++) {
long corruptIDNumbers =corruptedReferences.get(i);
for (int n = min; n < max; n++) {
Random rand = new Random(n);
long findID = rand.nextLong();
sb.append(findID);
//String reverseID = reverse(String.valueOf(findID));
findID = Long.valueOf(sb.reverse().toString().substring(0, 9));
if (findID == corruptIDNumbers) {
//System.out.println("Found the ID: "+n);
break;
}
sb.setLength(0);
}
long nano_endTime = System.nanoTime();
long millis_endTime = System.currentTimeMillis();
System.out.println("Time taken in nano seconds: "
+ (nano_endTime - nano_startTime));
System.out.println("Time taken in milli seconds: "
+ (millis_endTime - millis_startTime));
}
}
public static String reverse(String input) {
char[] in = input.toCharArray();
int begin = 0;
int end = in.length - 1;
char temp;
while (end > begin) {
temp = in[begin];
in[begin] = in[end];
in[end] = temp;
end--;
begin++;
}
return new String(in);
}
public static long reverseID(Long idNumber) {
String s = String.valueOf(idNumber);
StringBuilder sb = new StringBuilder();
for (int n = 0; n < s.length(); n++) {
sb.append(s.charAt((s.length() - n) - 1));
}
s = sb.toString();
long reversedNumber = Long.valueOf(s);
return reversedNumber;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T21:10:45.047",
"Id": "449416",
"Score": "0",
"body": "The Java major version is somewhat relevant here, but the other versions basically aren't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T22:47:04.337",
"Id": "449426",
"Score": "0",
"body": "I have.. a lot of questions, and they'll balloon the comments section. Let's please discuss in https://chat.stackexchange.com/rooms/99828/fast-way-to-iterate-through-billions-of-numbers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T23:15:27.673",
"Id": "449430",
"Score": "0",
"body": "Given what I've learned in chat, it's important that you edit this question to include: the estimated number of corrupted IDs (certainly not 11); the fact that random is actually a black-box function that isn't publishable over privacy concerns; and some parsing code showing how you'll be getting the IDs from a text file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T00:15:20.823",
"Id": "449434",
"Score": "0",
"body": "I realize that you can't show *us* the RNG, but can *you* look at it? Are you able to at least narrow down the initial seeds by calculating the first one or two random numbers exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T00:31:42.970",
"Id": "449436",
"Score": "0",
"body": "@markspace The random number uses seed, so it's always going to give you the same when you use the right seed. Which means since the min seed is 100million and the second seed is 101million etc, calculating those is easy but when the seed is like 876million it takes time to reach that via brute forcing. Is that what you mean by calculating the first one or two random numbers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T00:35:23.770",
"Id": "449437",
"Score": "1",
"body": "I'm not sure. Basically what I'm saying is that if you know what the first value you want out of an RNG is, you should be able to tell pretty quickly which seed will give you that number. It should cut down on the search, maybe by a factor of 200 or so. Second idea just occurred to me now: I think a \"rainbow table\" is a table of all possible values for a hash, so you can do a reverse look-up to crack a password hash. Can you calculate all 100 million seeds **once** and then just look them up? Again the idea is to reduce the number of possible values you have to search."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T00:50:04.183",
"Id": "449439",
"Score": "0",
"body": "First time hearing of rainbow table, it seems promising. But isn't it the same it HashSet,HashMap,HashTable?. From your second idea, I'm assuming I should add 100 million seed into a list, or the rainbow table then search it and if it's not in, get the ext batch 200million?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T01:36:19.013",
"Id": "449440",
"Score": "0",
"body": "I can only guess, since I haven't tried this myself. You have 900 million odd seeds to check. How many corrupted references do you have, can you narrow the number you have more than \"thousands?\" How many thousand, exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T02:23:24.800",
"Id": "449442",
"Score": "0",
"body": "@markspace 200,000 per file. and I have about 7 files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T14:41:24.137",
"Id": "449489",
"Score": "0",
"body": "Can you give us the time it takes to run perhaps 1000 iterations of your black-box function? That will allow me to gauge how long the parallel implementation should take."
}
] |
[
{
"body": "<p>The first and easiest option is to turn your loops inside-out. In your inner loop, you reverse the corrupt numbers. That shouldn't even be done in your main loop - just do it once, making a <code>reversedIDs</code> after initializing your <code>corruptIDNumbers</code>.</p>\n\n<p>Your <code>for (int i = 0; i < 1; i++)</code> doesn't make a lot of sense, and is probably just you manually truncating the program due to the runtime. But it should go away completely. Instead, make a <code>HashSet</code> containing your <code>reversedIDs</code>, and do not iterate over this set. On every randomly generated number, test to see if the generated number is a member of the set.</p>\n\n<p>Another important thing to do, since your brute-force approach is CPU-bound and highly parallelizable, is to multi-thread. Here is a suggested multi-threaded brute-force approach that completes for me in 5 seconds.</p>\n\n<p>You'll of course want to change the number of workers to suit your CPU.</p>\n\n<pre><code>import java.io.FileInputStream;\nimport java.io.IOException;\nimport java.util.HashSet;\nimport java.util.NoSuchElementException;\nimport java.util.Random;\nimport java.util.Scanner;\nimport java.util.Set;\n\n\npublic class IDResolver implements AutoCloseable {\n // This class is intended to be instantiated. main() is a thin entry point.\n\n // The set of all IDs as read from the file. Modern RAM capacity will easily\n // fit hundreds of thousands of IDs at once.\n private final Set<Long> ids = new HashSet<>();\n\n // The number of threads to run. Do not increase this beyond the hyperthread\n // capacity of your CPU or you will see steeply diminishing returns.\n private final int nworkers = 8;\n\n // The array of all Thread worker objects.\n private final Worker[] workers = new Worker[nworkers];\n\n // The upper and lower bound of the seed search space.\n private final long seedMin = 100_000_000,\n seedMax = 1_000_000_000;\n\n // The constructor; accepts the name of the file containing IDs, one per\n // line.\n public IDResolver(String filename) throws IOException {\n populate(filename);\n\n // The start of each worker's seed search space; computed incrementally.\n long start = seedMin;\n\n System.out.println(\"Workers:\");\n\n // Loop to create each worker and print its summary.\n for (int w = 0; w < nworkers; w++) {\n long end;\n if (w == nworkers-1)\n end = seedMax;\n else\n end = (seedMax - seedMin)*(w + 1)/nworkers + seedMin;\n\n workers[w] = new Worker(w, w==nworkers-1, start, end);\n System.out.println(workers[w]);\n start = end;\n }\n System.out.println();\n }\n\n // Populate the ID set from the ID file. Each ID is string-reversed before\n // being added to the set.\n private void populate(String filename) throws IOException {\n try (var stream = new FileInputStream(filename);\n var scanner = new Scanner(stream)) {\n var sb = new StringBuilder();\n\n while (true) {\n String line;\n try {\n line = scanner.nextLine();\n } catch (NoSuchElementException e) {\n break;\n }\n sb.append(line);\n long id = Long.valueOf(sb.reverse().toString());\n ids.add(id);\n sb.setLength(0);\n }\n }\n }\n\n // Entry point for the program. This program accepts one argument, the ID\n // file name.\n public static void main(String[] args) throws Exception {\n try (var resolver = new IDResolver(args[0])) {\n resolver.resolve();\n resolver.join();\n }\n }\n\n // Resolve all IDs by starting the worker threads.\n public void resolve() {\n for (Worker w: workers)\n w.start();\n }\n\n // Wait until all of the worker threads are done.\n public void join() throws InterruptedException {\n for (Worker w: workers)\n w.join();\n }\n\n // When this class is used as an AutoCloseable within a try-with-resources,\n // and close() is called, cancel the worker threads.\n public void close() throws InterruptedException {\n for (Worker w: workers) {\n w.cancel();\n w.join();\n }\n }\n\n // This is the \"black box\" function that needs to be replaced with your own.\n // It accepts a seed and returns an ID.\n private static long transform(long seed) {\n // todo: replace me\n var rand = new Random(seed);\n return rand.nextLong();\n }\n\n // The worker thread class. This supports all of the methods of Thread,\n // notably start().\n private class Worker extends Thread {\n // This is used to control the frequency of progress updates. Change the\n // 24, increasing it for slower updates.\n final long updateMask = (1L << 24) - 1;\n\n final int worker; // The worker's ID\n final long start; // The start of this worker's seed range\n long end; // The (exclusive) end of this worker's seed range\n final boolean last; // Whether this is the last worker\n\n public Worker(int worker, boolean last, long start, long end) {\n this.worker = worker;\n this.last = last;\n this.start = start;\n this.end = end;\n }\n\n // Used to show a summary of this worker\n @Override\n public String toString() {\n return String.format(\"ID=%d range %10d - %10d\", worker, start, end);\n }\n\n // Show progress - only used on the last worker\n private void tick(long seed) {\n if (last) {\n System.out.print(String.format(\n \"seed=%,d/%,d %.2f%%\\r\", seed, end,\n (seed - start)*100. / (end - start)\n ));\n }\n }\n\n // The worker thread routine.\n public void run() {\n // Loop through all seeds for this worker.\n for (long seed = start; seed < end; seed++) {\n // The candidate ID, as transformed from the current seed.\n long id = transform(seed);\n // Does this candidate ID exist in the set of all known IDs from\n // the file?\n if (ids.contains(id))\n // If so, print the seed and the ID that it produced.\n System.out.println(String.format(\n \"seed=%d id=%d\", seed, id));\n // Show progress.\n if ((seed&updateMask) == 0)\n tick(seed);\n }\n\n tick(end);\n if (last)\n System.out.println();\n }\n\n // Cancel this worker by setting its seed range end to zero.\n public void cancel() {\n end = 0;\n }\n }\n}\n</code></pre>\n\n<p>Invocation and output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ javac IDResolver.java && time java IDResolver corrupted.txt \nWorkers:\nID=0 range 100000000 - 212500000\nID=1 range 212500000 - 325000000\nID=2 range 325000000 - 437500000\nID=3 range 437500000 - 550000000\nID=4 range 550000000 - 662500000\nID=5 range 662500000 - 775000000\nID=6 range 775000000 - 887500000\nID=7 range 887500000 - 1000000000\n\nseed=1,000,000,000/1,000,000,000 100.00%\n\nreal 0m4.784s\nuser 0m36.266s\nsys 0m0.308s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T22:24:47.887",
"Id": "449421",
"Score": "0",
"body": "Thanks for your feedback and recommendations, I think the best way is to have ti make the reverse IDs as you have mentioned, but can a HashSet hold over 900million references?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T22:33:36.840",
"Id": "449423",
"Score": "0",
"body": "Currently you only show 11 corrupt IDs. Is it that list that's expected to increase to 900 million?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T22:42:52.403",
"Id": "449425",
"Score": "0",
"body": "Yes, it's intended to reach hundreds of thousands, but the indexes(nth value used s seed) is expected to reach up to 900 million."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T14:25:19.080",
"Id": "449488",
"Score": "0",
"body": "@HitherJoe Please refer to edit. As long as your \"black box\" isn't massively more complex than `random`, this will complete quickly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T06:30:53.867",
"Id": "449560",
"Score": "0",
"body": "Thanks for the code, it has increase the performance significantly, but it's still slow. I'm new to multi threading, I assume by increasing number of workers, the speed should increase right? I increased workers to 1000 but the speed still remain almost the same. Using the BlackBox algorithm it took 7minutes to process 10 IDs, my former code takes 4minute per ID. Even using the random function it still takes time. It would be great if you will comment the the use of functions/methods in your code, it will help me understand it well to edit it to fit my need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T06:56:53.657",
"Id": "449566",
"Score": "0",
"body": "Multi-threading seems really promising. Since I'm new to multi threading, I think making each worker loop million times by 900 worker, one of the worker should be able to get the seed in less than a second. If we get the seed, we move to the next ID, if ID already process print seed and move to the next ID. But it seems your code searches for all possible seeds, which might be one of the reason it's slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:43:43.820",
"Id": "449625",
"Score": "0",
"body": "@HitherJoe You do not need to \"move to the next ID\" at all, because _all_ of the IDs are tested at once using the set. I'll comment the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:50:30.680",
"Id": "449638",
"Score": "0",
"body": "@ Reinderien Thank you, this really helped me a lot, I had a quick read through the comments, and have fair understanding. Do you have any idea why it's slow even after increasing the workers, or how it can be improved upon? The slowness has nothing to do with the blackbox algorithm, as I have tried it with the Random generator and it's slow but surely better than my first approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T15:21:06.383",
"Id": "449643",
"Score": "0",
"body": "_why it's slow even after increasing the workers_ - because you don't have an infinite number of CPU cores. _The slowness has nothing to do with the blackbox algorithm_ - this claim is unfortunately impossible for you to make unless you show us the code."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T21:40:20.407",
"Id": "230622",
"ParentId": "230610",
"Score": "4"
}
},
{
"body": "<p>A couple of things that might help:</p>\n\n<p>To reverse a number, it is more efficient to use math instead of converting the number to a string first. Something like this should work:</p>\n\n<pre><code>public static long reverseID(Long idNumber){\n Long retVal = 0l;\n while(idNumber > 0){\n retVal = (retVal * 10) + (idNumber % 10);\n input /= 10;\n }\n return retVal;\n}\n</code></pre>\n\n<p>Also you can simplify, and possibly make more efficient, the <code>reverse</code> method by using the <code>StringBuilder.reverse()</code> method:</p>\n\n<pre><code>public static String revString(String input){\n return new StringBuilder(input).reverse().toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T11:25:58.467",
"Id": "449481",
"Score": "0",
"body": "Thanks for your suggestion, but if you look through the code, I used the StringBuilder.reverse method already."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T06:52:34.417",
"Id": "230631",
"ParentId": "230610",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230622",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T18:00:12.977",
"Id": "230610",
"Score": "2",
"Tags": [
"java",
"performance",
"algorithm",
"array",
"linked-list"
],
"Title": "Brute-force ID reversal search"
}
|
230610
|
<p>While learning Go I decided to implement a simple REST API to get to know the language and since I am inexperienced in Go I would appreciate <strong>any feedback</strong> on <a href="https://github.com/Shpota/go-angular" rel="nofollow noreferrer">the code</a>.</p>
<p>Please post <em>any thoughts</em> you have. They don't have to be constructive, but if you have some constructive feedback that will be great.</p>
<p><strong>Q:</strong> In particular, I would like to ask the next questions: Are there any bad patterns? Is there something you would do another way? What could be improved? Do I violate any code style rules (say, type names, variables)? Is it ok to place all this code in one file?</p>
<p>Note: I used <a href="https://github.com/gorilla/mux" rel="nofollow noreferrer">gorilla/mux</a> and <a href="https://github.com/jinzhu/gorm" rel="nofollow noreferrer">gorm</a> here.</p>
<pre><code>type student struct {
ID string `gorm:"primary_key" json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
type App struct {
DB *gorm.DB
}
func (a *App) start() {
db, err := gorm.Open(
"postgres",
"user=go password=go dbname=go sslmode=disable")
if err != nil {
panic(err.Error())
}
a.DB = db
db.AutoMigrate(&student{})
r := mux.NewRouter()
r.HandleFunc("/students", a.getAllStudents).Methods("GET")
r.HandleFunc("/students", a.addStudent).Methods("POST")
r.HandleFunc("/students/{id}", a.updateStudent).Methods("PUT")
r.HandleFunc("/students/{id}", a.deleteStudent).Methods("DELETE")
http.ListenAndServe(":8080", r)
}
func (a *App) getAllStudents(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var all []student
err := a.DB.Find(&all).Error
if err != nil {
sendErr(w, http.StatusInternalServerError, err.Error())
} else {
json.NewEncoder(w).Encode(all)
}
}
func (a *App) addStudent(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
s := student{}
err := json.NewDecoder(r.Body).Decode(&s)
if err != nil {
sendErr(w, http.StatusBadRequest, err.Error())
} else {
err = a.DB.Save(&s).Error
if err != nil {
sendErr(w, http.StatusInternalServerError, err.Error())
} else {
w.WriteHeader(http.StatusCreated)
}
}
}
func (a *App) updateStudent(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
s := student{}
err := json.NewDecoder(r.Body).Decode(&s)
if err != nil {
sendErr(w, http.StatusBadRequest, err.Error())
} else {
s.ID = mux.Vars(r)["id"]
err = a.DB.Save(&s).Error
if err != nil {
sendErr(w, http.StatusInternalServerError, err.Error())
}
}
}
func (a *App) deleteStudent(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
s := student{}
a.DB.First(&s, mux.Vars(r)["id"])
err := a.DB.Delete(s).Error
if err != nil {
sendErr(w, http.StatusInternalServerError, err.Error())
}
}
func sendErr(w http.ResponseWriter, code int, message string) {
response, _ := json.Marshal(map[string]string{"error": message})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
func main() {
app := App{}
app.start()
}
</code></pre>
<p><strong>Update:</strong> I've got some great feedback and I have an additional question related to that. In both the answers you suggest me to get rid of <code>else</code> blocks / use an early return. Is it a common practice in Go? Is it because of error handling in Go which makes you create more if/else blocks? I am asking because in other languages (such as Java) it is considered a bad practice. The main reason is that it hides complexity. Every time you create a return inside an if block you make a the code more flat hiding the real complexity.</p>
|
[] |
[
{
"body": "<ul>\n<li><p><code>ID</code> as a <code>string</code> is weird. I expect to see an <code>int</code> here to benefit of the auto increment feature.</p></li>\n<li><p>your <code>delete</code> handler is weak. Suppose the GET <code>ID</code> parameter is set to a non existing <code>ID</code> value, the read operation will fail but the value of the <code>ID</code> property of the <code>student</code> variable will be an empty string. The next <code>delete</code> statement will delete the row with <code>ID==\"\"</code>, which might exists and be a valid. The problem also exists for an <code>integer</code> <code>PK</code> where <code>ID=0</code>. You must check <strong>all</strong> errors.</p></li>\n<li><p>the <code>update</code> handler has a similar problem, and it is not acceptable for as long as the api provides both <code>add</code> and <code>update</code> as different operations. Usually an <code>update</code> operation requires to check against a couple <code>PK+LastUpdateDate</code> to ensure acid transactions from <code>UI</code> POV. So, you might try to load the entity from the db, at the cost of an extra read. Or update with clauses. The latter might be done automatically by the db framework, this is unclear without a better knowledge of its internal.</p></li>\n<li><p>the <code>getAllStudents</code> handler is a ddos. Obviously that always depends of the db size, but for a production system there must not exist any handler that loads the entire db in memory. So add <code>Limit/Offset</code> parameters, check they are valid and apply them to the query.</p></li>\n<li><p>overall your code has too many level of indentations. You should practice the <code>early return</code> pattern to improve its clarity.</p></li>\n</ul>\n\n<p>Here is an updated version of the code, so the reader can evaluate the <code>return early</code> pattern and appreciate various modifications as explained before.</p>\n\n<ul>\n<li>Care was taken to demonstrate a proper startup/shutdown sequence to prevent connections misshandling.</li>\n<li><code>http.Server</code> is moved out so the handler is mountable onto alternatives http server implementation (httptest.*)</li>\n<li>the db engine is switched to sqlite for demonstration</li>\n<li>OP was missing the pgsql driver blank import</li>\n</ul>\n\n<p>here is the code (it is still missing proper test suite!)</p>\n\n<pre><code>package main\n\nimport (\n \"context\"\n \"encoding/json\"\n \"errors\"\n \"fmt\"\n \"log\"\n \"net/http\"\n \"os\"\n \"os/signal\"\n \"strconv\"\n \"time\"\n\n \"github.com/gorilla/mux\"\n \"github.com/jinzhu/gorm\"\n _ \"github.com/jinzhu/gorm/dialects/sqlite\"\n)\n\ntype student struct {\n ID string `gorm:\"primary_key\" json:\"id\"`\n Name string `json:\"name\"`\n Age int `json:\"age\"`\n\n // http://gorm.io/docs/conventions.html\n // gorm.Model is a basic GoLang struct which includes the following fields: ID, CreatedAt, UpdatedAt, DeletedAt.\n CreatedAt time.Time\n UpdatedAt time.Time\n DeletedAt *time.Time\n}\n\ntype App struct {\n DB *gorm.DB\n}\n\nfunc (a *App) Handler() http.Handler {\n r := mux.NewRouter()\n r.HandleFunc(\"/students\", a.getAllStudents).Methods(\"GET\")\n r.HandleFunc(\"/students\", a.addStudent).Methods(\"POST\")\n r.HandleFunc(\"/students/{id}\", a.updateStudent).Methods(\"PUT\")\n r.HandleFunc(\"/students/{id}\", a.deleteStudent).Methods(\"DELETE\")\n return r\n}\n\nfunc (a *App) Open() error {\n db, err := gorm.Open(\"sqlite3\", \":memory:\")\n if err != nil {\n return err\n }\n a.DB = db\n return db.AutoMigrate(&student{}).Error\n}\n\nfunc (a *App) Close() error {\n return a.DB.Close()\n}\n\nfunc (a *App) getAllStudents(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n // see also a struct decoder to transform get params as struct.\n // https://github.com/gorilla/schema\n var offset, limit int\n {\n y := r.URL.Query().Get(\"Limit\")\n if y != \"\" {\n x, err := strconv.Atoi(y)\n if err != nil {\n sendErr(w, fmt.Errorf(\"Limit argument, %v\", err), http.StatusBadRequest)\n return\n }\n limit = x\n }\n y = r.URL.Query().Get(\"Offset\")\n if y != \"\" {\n x, err := strconv.Atoi(y)\n if err != nil {\n sendErr(w, fmt.Errorf(\"Offset argument, %v\", err), http.StatusBadRequest)\n return\n }\n offset = x\n }\n }\n if limit < 0 || limit > 30 {\n limit = 30\n }\n var all []student\n err := a.DB.Find(&all).Limit(limit).Offset(offset).Error\n if err != nil {\n sendErr(w, err, http.StatusInternalServerError)\n return\n }\n json.NewEncoder(w).Encode(all)\n}\n\nfunc (a *App) addStudent(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n s := student{}\n err := json.NewDecoder(r.Body).Decode(&s)\n if err != nil {\n sendErr(w, err, http.StatusBadRequest)\n return\n }\n err = a.DB.Create(&s).Error\n if err != nil {\n sendErr(w, err, http.StatusInternalServerError)\n return\n }\n w.WriteHeader(http.StatusCreated)\n}\n\nfunc (a *App) updateStudent(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n s := student{}\n err := json.NewDecoder(r.Body).Decode(&s)\n if err != nil {\n sendErr(w, err, http.StatusBadRequest)\n return\n }\n id := mux.Vars(r)[\"id\"]\n if s.ID != id {\n sendErr(w, errors.New(\"invalid ID\"), http.StatusBadRequest)\n return\n }\n s.ID = id // Why not read it from Body directly ?\n err = a.DB.Save(&s).Error //gorm does a proper job http://gorm.io/docs/update.html\n sendErr(w, err, http.StatusInternalServerError)\n}\n\nfunc (a *App) deleteStudent(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n id := mux.Vars(r)[\"id\"]\n s := student{}\n err := a.DB.First(&s, id).Error\n if err != nil {\n sendErr(w, err)\n return\n }\n err = a.DB.Delete(s).Error\n sendErr(w, err)\n}\n\nfunc sendErr(w http.ResponseWriter, err error, codes ...int) {\n if err == nil {\n return\n }\n if len(codes) < 1 {\n codes = append(codes, http.StatusInternalServerError)\n }\n response, _ := json.Marshal(map[string]string{\"error\": err.Error()})\n w.Header().Set(\"Content-Type\", \"application/json\")\n http.Error(w, string(response), codes[0])\n}\n\nfunc main() {\n app := App{}\n if err := app.Open(); err != nil {\n log.Fatal(\"open failed\", err)\n }\n defer app.Close()\n\n srv := &http.Server{\n Addr: \":8080\",\n Handler: app.Handler(),\n }\n\n err := make(chan error)\n go func() {\n err <- srv.ListenAndServe()\n }()\n\n select {\n case e := <-err:\n log.Fatal(\"listen failed\", e)\n case <-time.After(time.Millisecond * 200):\n log.Println(\"app started at \", srv.Addr)\n }\n\n sigint := make(chan os.Signal, 1)\n signal.Notify(sigint, os.Interrupt)\n <-sigint\n log.Println(\"got signal\")\n\n if err := srv.Shutdown(context.Background()); err != nil {\n // Error from closing listeners, or context timeout:\n log.Printf(\"HTTP server Shutdown: %v\", err)\n }\n log.Println(\"properly shutdown\")\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T07:44:37.943",
"Id": "450387",
"Score": "0",
"body": "Thank you for the answer (+1). Could you please take a look on my update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T08:01:04.927",
"Id": "450393",
"Score": "0",
"body": "i like this answer https://stackoverflow.com/a/884446/4466350"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-20T18:52:05.950",
"Id": "231052",
"ParentId": "230613",
"Score": "5"
}
},
{
"body": "<p>OK to place it in one file. Variable naming is fine.</p>\n\n<pre><code>type student struct {\n ID string `gorm:\"primary_key\" json:\"id\"`\n Name string `json:\"name\"`\n Age int `json:\"age\"`\n}\n</code></pre>\n\n<p>Probably useful to export it, so <code>Student</code></p>\n\n<pre><code>type App struct {\n DB *gorm.DB\n}\n</code></pre>\n\n<p>YAGNI. Just a global variable <code>db</code> is fine. Definitely you won't import <code>App</code> in another program, not under this name.</p>\n\n<pre><code>func (a *App) start() {\n db, err := gorm.Open(\n \"postgres\",\n \"user=go password=go dbname=go sslmode=disable\")\n</code></pre>\n\n<p>Lack of secret injection.</p>\n\n<pre><code> r.HandleFunc(\"/students\", a.getAllStudents).Methods(\"GET\")\n</code></pre>\n\n<p>I prefer singular, so <code>/student</code></p>\n\n<pre><code> if err != nil {\n sendErr(w, http.StatusBadRequest, err.Error())\n } else {\n</code></pre>\n\n<p>Maybe instead:</p>\n\n<pre><code> if err != nil {\n sendErr(w, http.StatusBadRequest, err.Error())\n return\n }\n</code></pre>\n\n<p>The less <code>else</code>s the more readable the code.</p>\n\n<pre><code>func (a *App) deleteStudent(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n s := student{}\n a.DB.First(&s, mux.Vars(r)[\"id\"])\n err := a.DB.Delete(s).Error\n</code></pre>\n\n<p>Weird. I think this would work: <code>s.ID, ok := mux.Vars(r)[\"id\"]</code>\nThen <code>if !ok</code> to be more defensive. (This place is far away from <code>/student/{id}</code> so they can get easily out of sync. You never used this <code>v, ok := m[key]</code> idiom, so be advised you're ignoring the key-not-found situations.)</p>\n\n<p>Then <code>Delete(s)</code> which should only use the primary key, ignoring all the other fields.</p>\n\n<p>Overall the program looks nice, assuming it's one of your first Go programs, I'd say impressive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T07:44:52.737",
"Id": "450388",
"Score": "0",
"body": "Thank you for the answer (+1). Could you please take a look on my update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T07:54:06.477",
"Id": "450390",
"Score": "0",
"body": "*use an early return. Is it a common practice in Go?* Yes, I'd say it's standard. Same with `break` or `continue`. I keep the main flow fairly unindented - that's more readable. Why should a first-time reader guess which leg of the `if/else` is more important, if I can make it visually obvious? @SashaShpota"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-20T19:06:31.740",
"Id": "231053",
"ParentId": "230613",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231052",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T18:23:13.893",
"Id": "230613",
"Score": "6",
"Tags": [
"go"
],
"Title": "Implementing a REST API in Go using gorilla/mux and Gorm"
}
|
230613
|
<p>I am in the process of learning basic C++ and one of the practice questions I came across was to write a function to open a file in C++.</p>
<p>I did understand how to use the streams but I think I went overboard a little bit by making sure that it works. I would appreciate any feedback on my code. The objective was also to keep prompting the user to open a file if it doesn't work in the first go.</p>
<p>Code:</p>
<pre><code>void OpenFile(std::ifstream& inputFileStream) {
while(true) {
inputFileStream.clear();
std::stringstream fileNameStream;
std::string fileName;
std::cout << "Enter the file name to open: ";
if(!getline(std::cin, fileName)) {
std::cout << "Please enter a valid name." << std::endl;
} else {
fileNameStream << fileName;
std::string fileToOpen;
std::string remaining;
if(fileNameStream >> fileToOpen) {
if(fileNameStream >> remaining) {
std::cout << "Unexpected character: " << remaining << std::endl;
} else {
inputFileStream.open(fileToOpen.c_str());
if (!inputFileStream.is_open()) {
std::cout << "File could not be opened. Please try again.";
std::cout << std::endl;
} else {
break;
}
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>Prefer returning a result instead of passing it via a reference</h1>\n\n<p>The result of your function is a <code>std::ifstream</code> object, so make that explicit:</p>\n\n<pre><code>std::ifstream OpenFile() {\n while(true) {\n // read filename\n\n std::ifstream file(fileName);\n\n if (file.is_open())\n return file;\n else\n // handle error\n }\n}\n</code></pre>\n\n<p>The advantage is that instead of having to write:</p>\n\n<pre><code>std::ifstream file;\nOpenFile(file);\n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code>std::ifstream file = OpenFile();\n</code></pre>\n\n<p>Or even:</p>\n\n<pre><code>auto file = OpenFile();\n</code></pre>\n\n<h1>Avoid using <code>std::stringstream</code> if it's not necessary</h1>\n\n<p>It might seem convenient, but it's rather inefficient, and often there are other ways to accomplish what you want. It seems from your code that you want to forbid filenames with whitespace characters in them. Consider using <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/find_first_of\" rel=\"nofollow noreferrer\"><code>std::find_first_of()</code></a> to check if there are certain characters in a string.</p>\n\n<p>Apart from that, many filesystems, including those on mainstream operating systems such as Linux, Windows and macOS, allow spaces in their filenames. And surely, when you call <code>open()</code>, the operating system will return an error if you pass it an invalid filename, so you don't have to do this error checking yourself.</p>\n\n<h1>Avoid casting <code>std::string</code> to C-strings</h1>\n\n<p>Since C++11 you can pass a <code>std::string</code> directly to a <code>std::ifstream</code>'s constructor or to its <code>open()</code> function.</p>\n\n<h1>Use <code>'\\n'</code> instead of <code>std::endl</code></h1>\n\n<p>Avoid using <code>std::endl</code>. It is equivalent to <code>'\\n'</code> plus a call to <code>flush()</code>. The flush is usually unnecessary and might hurt performance. So for example, instead of:</p>\n\n<pre><code>std::cout << \"File could not be opened. Please try again.\";\nstd::cout << std::endl;\n</code></pre>\n\n<p>Write:</p>\n\n<pre><code>std::cout << \"File could not be opened. Please try again.\\n\";\n</code></pre>\n\n<h1>Pass along the error message from the operating system</h1>\n\n<p>There are many reasons why opening a file might fail. It will benefit the user to learn the exact reason why it failed. For example, it could be that the file doesn't exist, or that it's permissions don't allow it being opened by the user. To do this, call <code>strerror(errno)</code>, like so:</p>\n\n<pre><code>std::cout << \"File could not be opened: \" << strerror(errno) << \"\\nPlease try again.\\n\";\n</code></pre>\n\n<h1>Add a way for the user to cancel opening a file</h1>\n\n<p>The function loops forever until a file has succesfully been opened. What if the user decides that it doesn't want any file to be opened at this time, but wants the application to cancel this operation but do something else? If you don't allow a way out of this function, the only option available to the user is closing the application and restarting it.</p>\n\n<h1>Consider making the function more generic</h1>\n\n<p>While you shouldn't add bells and whistles to a function like this if you are not going to use them, you might want to consider whether you want to make this function a bit more widely applicable. For example, you could have it open a file either for reading, writing or both, or have a way to give a custom prompt. For example:</p>\n\n<pre><code>std::fstream OpenFile(ios_base::openmode mode = ios_base::in, const std::string &prompt = \"Enter a file name: \") {\n while(true) {\n std::cout << prompt;\n // read filename\n\n std::fstream file(filename, mode);\n\n if (file.is_open())\n return file;\n else\n // handle error\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T21:59:14.427",
"Id": "230623",
"ParentId": "230616",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230623",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T20:03:53.930",
"Id": "230616",
"Score": "2",
"Tags": [
"c++",
"stream"
],
"Title": "OpenFile function in C++"
}
|
230616
|
<p>I created this wrapper to use together with <code>HttpClient</code> streams and <code>ZipArchive</code>. <code>ZipArchive</code> reads <code>.zip</code> index once from the end of the archive, so this wrapper caches last 4MiB of the stream. Also the wrapper avoids pointless seeks until the first read.</p>
<p>I am interested if there any issues with this approach, and whether this can be improved.</p>
<pre><code>namespace Playground
{
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
public class SeekableHttpStream : Stream
{
private long _position;
private long _underlyingStreamOffset;
private Stream _underlyingStream;
private bool _forceRequest;
internal SeekableHttpStream(
HttpClient client,
HttpResponseMessage response,
HttpRequestMessage request)
{
Client = client;
Response = response;
Request = request;
var headers = response.Headers;
var acceptRanges = headers?.AcceptRanges;
if (acceptRanges == null || !acceptRanges.Contains("bytes"))
{
throw new ArgumentException("server does not support HTTP range requests", nameof(request));
}
var contentHeaders = response.Content?.Headers;
if (contentHeaders.ContentLength != null)
{
Length = contentHeaders.ContentLength.Value;
}
else if (contentHeaders.ContentRange != null)
{
if (contentHeaders.ContentRange.Length == null)
{
throw new ArgumentException("missing Content-Range length", nameof(request));
}
Length = contentHeaders.ContentRange.Length.Value;
}
else
{
throw new ArgumentException("failed to determine stream length", nameof(request));
}
}
public HttpClient Client { get; }
public HttpResponseMessage Response { get; }
public HttpRequestMessage Request { get; }
public override bool CanRead => _position < Length;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length { get; }
public override long Position
{
get => _position;
set => Seek(value, SeekOrigin.Begin);
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
EnsureStreamOpen().GetAwaiter().GetResult();
int read = _underlyingStream.Read(buffer, offset, count);
_position += read;
return read;
}
public override int Read(Span<byte> buffer)
{
EnsureStreamOpen().GetAwaiter().GetResult();
int read = _underlyingStream.Read(buffer);
_position += read;
return read;
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await EnsureStreamOpen(cancellationToken).ConfigureAwait(false);
int read = await _underlyingStream.ReadAsync(buffer, offset, count, cancellationToken)
.ConfigureAwait(false);
_position += read;
return read;
}
public override int ReadByte()
{
EnsureStreamOpen().GetAwaiter().GetResult();
var value = _underlyingStream.ReadByte();
++_position;
return value;
}
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await EnsureStreamOpen(cancellationToken).ConfigureAwait(false);
int read = await _underlyingStream.ReadAsync(buffer, cancellationToken)
.ConfigureAwait(false);
_position += read;
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
return SeekAsync(offset, origin).GetAwaiter().GetResult();
}
private ValueTask EnsureStreamOpen(CancellationToken cancellationToken = default)
{
if (_underlyingStream == null)
{
_forceRequest = true;
return new ValueTask(SeekAsync(0, SeekOrigin.Current, cancellationToken));
}
return default;
}
public async Task<long> SeekAsync(long offset, SeekOrigin origin, CancellationToken cancellationToken = default)
{
const long SeekThreshold = 1024 * 1024;
long newPosition = origin switch
{
SeekOrigin.Begin => offset,
SeekOrigin.Current => _position + offset,
SeekOrigin.End => Length + offset,
_ => throw new ArgumentOutOfRangeException(nameof(origin)),
};
if (newPosition < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (newPosition > Length)
{
throw new NotSupportedException("seeking beyond the length of the stream is not supported");
}
long delta = newPosition - _position;
if (_underlyingStream == null)
{
if (_forceRequest)
{
await OpenUnderlyingStream(newPosition, cancellationToken)
.ConfigureAwait(false);
}
_position = newPosition;
}
else if (_underlyingStream.CanSeek && newPosition >= _underlyingStreamOffset && newPosition <= _underlyingStreamOffset + _underlyingStream.Length)
{
_underlyingStream.Position = newPosition - _underlyingStreamOffset;
_position = newPosition;
}
else if (delta < 0 || delta > SeekThreshold)
{
await OpenUnderlyingStream(newPosition, cancellationToken)
.ConfigureAwait(false);
}
else if (delta > 0)
{
var buffer = new byte[delta];
await ReadAsync(buffer, 0, (int)delta, cancellationToken);
}
return _position;
}
private async Task<HttpRequestMessage> CopyHttpRequest()
{
var clone = new HttpRequestMessage(Request.Method, Request.RequestUri);
if (Request.Content != null)
{
var bytes = await Request.Content.ReadAsByteArrayAsync()
.ConfigureAwait(false);
clone.Content = new ByteArrayContent(bytes);
if (Request.Content.Headers != null)
foreach (var h in Request.Content.Headers)
clone.Content.Headers.Add(h.Key, h.Value);
}
clone.Version = Request.Version;
foreach (var prop in Request.Properties)
{
clone.Properties.Add(prop);
}
foreach (var header in Request.Headers)
{
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return clone;
}
private async Task OpenUnderlyingStream(long position, CancellationToken cancellationToken = default)
{
const long UseBufferedStreamThreshold = 4 * 1024 * 1024;
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
using var newRequest = await CopyHttpRequest()
.ConfigureAwait(false);
if (position > 0)
{
var responseHeaders = Response.Headers;
var contentHeaders = Response.Content.Headers;
if (responseHeaders.ETag != null)
{
newRequest.Headers.IfRange = new RangeConditionHeaderValue(responseHeaders.ETag);
}
else if (contentHeaders.LastModified != null)
{
newRequest.Headers.IfRange = new RangeConditionHeaderValue(contentHeaders.LastModified.Value);
}
newRequest.Headers.Range = new RangeHeaderValue(position, null);
}
long remainingLength = Length - position;
var response = await Client.SendAsync(
newRequest,
remainingLength <= UseBufferedStreamThreshold ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
cancellationToken
).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
response.EnsureSuccessStatusCode();
}
else if (position > 0 && response.StatusCode != HttpStatusCode.PartialContent)
{
response.Dispose();
throw new InvalidOperationException("range request not supported or content has changed since last request");
}
else
{
try
{
var stream = await response.Content.ReadAsStreamAsync()
.ConfigureAwait(false);
if (_underlyingStream != null)
{
await _underlyingStream.DisposeAsync()
.ConfigureAwait(false);
}
_underlyingStream = stream;
_underlyingStreamOffset = position;
_forceRequest = false;
_position = position;
}
catch
{
response.Dispose();
throw;
}
}
}
protected override void Dispose(bool disposing)
{
_underlyingStream?.Dispose();
Response.Dispose();
Request.Dispose();
base.Dispose(disposing);
}
#region Unsupported write methods
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
public override void EndWrite(IAsyncResult asyncResult) => throw new NotSupportedException();
public override void Write(ReadOnlySpan<byte> buffer) => throw new NotSupportedException();
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
throw new NotSupportedException();
}
public override void WriteByte(byte value)
{
throw new NotSupportedException();
}
public override int WriteTimeout
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
#endregion Unsupported write methods
}
public static class HttpClientExtensions
{
public static async Task<SeekableHttpStream> GetSeekableStreamAsync(this HttpClient client, string requestUri)
{
using var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
return await SendSeekableStreamAsync(client, request)
.ConfigureAwait(false);
}
public static async Task<SeekableHttpStream> GetSeekableStreamAsync(this HttpClient client, Uri requestUri)
{
using var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
return await SendSeekableStreamAsync(client, request)
.ConfigureAwait(false);
}
public static async Task<SeekableHttpStream> SendSeekableStreamAsync(this HttpClient client, HttpRequestMessage request)
{
HttpMethod method = request.Method;
try
{
request.Method = HttpMethod.Head;
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
try
{
return new SeekableHttpStream(client, response, request);
}
catch
{
response.Dispose();
throw;
}
}
finally
{
request.Method = method;
}
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T21:13:37.023",
"Id": "230621",
"Score": "2",
"Tags": [
"c#",
".net",
"asynchronous",
"http",
"stream"
],
"Title": "Seekable HTTP response stream wrapper"
}
|
230621
|
<p>This program</p>
<ol>
<li><p>Detects application uniqueness, if the application is a unique/primary instance, it launches a server, otherwise a client over a Unix domain socket.</p></li>
<li><p>Client will send a message that will trigger the server to invoke a time-heavy task.</p></li>
<li><p>When the task is running, the server will ignore all the incoming messages. This is currently worked-around by making the client send the current time to the server. Server keeps track of the heavy task and when it finishes. I'd like a way to actually drop the socket before the task starts but I can't find a way to re-activate the socket.</p></li>
</ol>
<pre class="lang-rust prettyprint-override"><code>///// Begin imports
use {
nix::{
errno::Errno::EADDRINUSE,
sys::socket::{
bind, connect, recv, send, socket, AddressFamily, MsgFlags, SockAddr, SockFlag,
SockType, UnixAddr,
},
unistd::close,
Error::Sys,
}, // "0.15.0"
std::{error::Error, os::unix::io::RawFd},
};
///// End imports
</code></pre>
<pre class="lang-rust prettyprint-override"><code>///// Begin constsnts
static SOCK_ADDR: &'static str = "com.localserver.myapp.sock";
// message capacity is the size
// of the bytes that represent a u64
// can't create static size array
const MESSAGE_CAPACITY: usize = 64 / 8;
//// End constants
//// Begin macros
macro_rules! Expected {
() => {
Result<(), Box<dyn Error>>
};
($t:ty) => {
Result<$t, Box<dyn Error>>
}
}
//// End Macros
//// Begin helper functions
fn heavy_task() -> Expected!() {
println!("Performing heavy task");
std::thread::sleep(std::time::Duration::from_secs(5));
println!("Task finished.");
Ok(())
}
/// Return the current timestamp in nanosecond precision
fn get_time() -> Expected!(u64) {
Ok(std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.as_nanos() as u64)
}
//// End helper functions
</code></pre>
<pre class="lang-rust prettyprint-override"><code>fn server(msgsock: RawFd) -> Expected!() {
let mut earliest_non_busy_time = get_time()?;
loop {
println!("Listening...");
loop {
let mut buf = [0u8; MESSAGE_CAPACITY];
let rval = recv(msgsock, &mut buf[..], MsgFlags::empty())?;
if rval != MESSAGE_CAPACITY {
break;
} else {
let incoming_time = u64::from_be_bytes(buf);
if incoming_time > earliest_non_busy_time {
heavy_task()?;
earliest_non_busy_time = get_time()?;
} else {
println!("Task request rejected since the task had already been running");
}
}
}
}
// Ok(()) // unreachable
}
</code></pre>
<pre class="lang-rust prettyprint-override"><code>fn client(sock: RawFd, addr: &SockAddr) -> Expected!() {
match connect(sock, addr) {
Ok(_) => {
let current_time = get_time()?;
let msg = current_time.to_be_bytes();
if send(sock, &msg, MsgFlags::empty())? != MESSAGE_CAPACITY {
close(sock)?;
panic!("Message could not be sent");
}
close(sock)?;
Ok(())
}
Err(e) => {
close(sock)?;
panic!("Error connecting to socket: {}", e);
}
}
}
</code></pre>
<pre class="lang-rust prettyprint-override"><code>fn main() -> Expected!() {
let sock: RawFd = socket(
AddressFamily::Unix,
SockType::Datagram,
SockFlag::empty(),
None, // Protocol
)?;
let addr = SockAddr::Unix(UnixAddr::new_abstract(SOCK_ADDR.as_bytes())?);
match bind(sock, &addr) {
Err(e) => match e {
Sys(EADDRINUSE) => {
println!("Secondary instance detected, launching client.");
match client(sock, &addr) {
Ok(_) => println!("Message sent."),
Err(_) => println!("Message sending failed."),
}
println!("Exiting...");
}
_ => {
panic!("Socket binding failed due to: {:?}", e);
}
},
Ok(_) => {
println!("Primary instance detected, launching server.");
server(sock)?;
}
}
Ok(())
}
</code></pre>
<p>Further explained here: <a href="https://gitlab.com/snippets/1903637" rel="nofollow noreferrer">https://gitlab.com/snippets/1903637</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T22:49:42.750",
"Id": "230625",
"Score": "3",
"Tags": [
"rust",
"socket",
"unix",
"ipc"
],
"Title": "Application uniqueness and unilateral IPC on Unix"
}
|
230625
|
<p>I am working on an information retrieval project, where I have to process a ~1.5 GB text data and create a Dictionary (words, document frequency) and posting list (document id, term frequency). According to the professor, it should take around 10-15 minutes. But my code is running for more than 8 hours now! I tried a smaller dataset (~35 MB) and it took 5 hours to process.</p>
<p>I am a newbie in python and I think it is taking so long because i have created many python dictionaries and lists in my code. I tried to use generator, but I am not sure how to work around with it.</p>
<pre><code>file = open(filename, 'rt')
text = file.read()
file.close()
p = r'<P ID=\d+>.*?</P>'
tag = RegexpTokenizer(p)
passage = tag.tokenize(text)
doc_re = re.compile(r"<P ID=(\d+)>")
def process_data(docu):
tokens = RegexpTokenizer(r'\w+')
lower_tokens = [word.lower() for word in tokens.tokenize(docu)] #convert to lower case
table = str.maketrans('','', string.punctuation)
stripped = [w.translate(table) for w in lower_tokens] #remove punctuation
alpha = [word for word in stripped if word.isalpha()] #remove tokens that are not alphabetic
stopwordlist = stopwords.words('english')
stopped = [w for w in alpha if not w in stopwordlist] #remove stopwords
return stopped
data = {} #dictionary: key = Doc ID, value: word/term
for doc in passage:
group_docID = doc_re.match(doc)
docID = group_docID.group(1)
tokens = process_data(doc)
data[docID] = list(set(tokens))
vocab = [item for i in data.values() for item in i] #all words in the dataset
total_vocab = list(set(vocab)) #unique word/vocbulary for the whole dataset
total_vocab.sort()
print('Document Size = ', len(data)) #no. of documents
print('Collection Size = ', len(vocab)) #no. of words
print('Vocabulary Size= ', len(total_vocab)) #no. of unique words
inv_index = {} #dictionary: key =word/term, value: [docid, termfrequency]
for x in total_vocab:
for y, z in data.items():
if x in z:
wordfreq = z.count(x)
inv_index.setdefault(x, []).append((int(y), wordfreq))
flattend = [item for tag in inv_index.values() for item in tag] #[(docid, tf)]
posting = [item for tag in flattend for item in tag ] #[docid, tf]
#document frequency for each vocabulary/words
doc_freq=[]
for k,v in inv_index.items():
freq1=len([item for item in v if item])
doc_freq.append((freq1))
#offset value of each vocabulary/words
offset = []
offset1=0
for i in range(len(doc_freq)):
if i>0:
offset1 =offset1 + (doc_freq[i-1]*2)
offset.append((offset1))
#create dcitionary of words, document frequency and offset
dictionary = {}
for i in range(len(total_vocab)):
dictionary[total_vocab[i]]=(doc_freq[i],offset[i])
#dictionary of word, inverse document frequency
idf = {}
for i in range(len(dictionary)):
a = np.log2(len(data)/doc_freq[i])
idf[total_vocab[i]] = a
with open('dictionary.json', 'w') as f:
json.dump(dictionary,f)
with open('idf.json', 'w') as f:
json.dump(idf, f)
binary_file = open('binary_file.txt', 'wb')
for i in range(0, len(posting)):
binary_int = (posting[i]).to_bytes(4, byteorder = 'big')
#print(binary_int)
binary_file.write(binary_int)
binary_file.close()
</code></pre>
<p>Could someone please help me to rewrite this code so that it becomes more computationally and time efficient?</p>
<p>There are around 57982 documents like that.
Input File: </p>
<pre><code><P ID=2630932>
Background
Adrenal cortex oncocytic carcinoma (AOC) represents an exceptional
pathological entity, since only 22 cases have been documented in the
literature so far.
Case presentation
Our case concerns a 54-year-old man with past medical history of right
adrenal excision with partial hepatectomy, due to an adrenocortical
carcinoma. The patient was admitted in our hospital to undergo surgical
resection of a left lung mass newly detected on chest Computed Tomography
scan. The histological and immunohistochemical study revealed a metastatic
AOC. Although the patient was given mitotane orally in adjuvant basis, he
experienced relapse with multiple metastases in the thorax twice.....
<\P>
</code></pre>
<p>I am trying to tokenize each document by word and store document frequency of each word in a dictionary. Trying to save it in json file.
Dictionary</p>
<pre><code>word document_frequency offset
medical 2500 3414
research 320 4200
</code></pre>
<p>Also, generating a index where each word has a posting list of document ID and term frequency</p>
<pre><code>medical (2630932, 20), (2795320, 2), (26350421, 31)....
research (2783546, 243), (28517364, 310)....
</code></pre>
<p>and then save this postings in a binary file:</p>
<pre><code>2630932 20 2795320 2 2635041 31....
</code></pre>
<p>with an offset value for each word. SO that when i load the posting list from disk, i could use seek function to get the posting for each corresponding word.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T23:45:16.800",
"Id": "449432",
"Score": "3",
"body": "Please provide a sample of the data, fill in the missing import statements and provide examples of input and output to help reviewers understand what you want to achieve with this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T00:27:02.050",
"Id": "449435",
"Score": "0",
"body": "I have edited my question with proper input output format"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T10:27:11.050",
"Id": "449478",
"Score": "1",
"body": "Your imports are still missing. What is `RegexpTokenizer`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T14:23:16.960",
"Id": "449487",
"Score": "2",
"body": "There are [profiling utilities](https://docs.python.org/3/library/profile.html) available with Python, as part of the standard distribution. However, they report their results by the *function* the lines are in. As a first step towards profiling, I suggest you break your code into a series of functions. One per paragraph would do -- just take the comment at the top of the paragraph as the function name, and call them in order."
}
] |
[
{
"body": "<p>One way to probably speed this up a bit is to use generator expressions. Currently your <code>process_data</code> function has many list comprehensions after another. Each of them results in a list in memory, but you only care about the end result. In addition, you call <code>set</code> on it directly afterwards, so include that in the function itself. I also extracted some constants from the function, no need to always redefine them, and made the stopwords a <code>set</code> so <code>in</code> is <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> instead of <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>.</p>\n\n<pre><code>STOPWORDS = set(stopwords.words('english'))\nTOKENIZER = RegexpTokenizer(r'\\w+')\nTABLE = str.maketrans('', '', string.punctuation)\n\ndef process_data(docu):\n # convert to lower case \n lower_tokens = (word.lower() for word in tokens.TOKENIZER(docu))\n #remove punctuation\n stripped = (w.translate(TABLE) for w in lower_tokens)\n #remove tokens that are not alphabetic \n alpha = (word for word in stripped if word.isalpha())\n # remove stopwords\n stopped = (w for w in alpha if w not in STOPWORDS)\n return set(stopped)\n</code></pre>\n\n<p>I would also keep <code>data[docID]</code> a <code>set</code>, because you later check for <code>in</code> there as well.</p>\n\n<p>Similarly, you can directly build a <code>set</code> using a set comprehension, instead of creating a list, and then putting it into a set. This way you can turn</p>\n\n<pre><code>vocab = [item for i in data.values() for item in i] #all words in the dataset\ntotal_vocab = list(set(vocab)) #unique word/vocbulary for the whole dataset\ntotal_vocab.sort()\n</code></pre>\n\n<p>into</p>\n\n<pre><code>total_vocab = sorted({item for i in data.values() for item in i})\n</code></pre>\n\n<p>Incidentally, <code>wordfreq = z.count(x)</code> should always give you <code>1</code>, because you made sure before that <code>z</code> only has unique words.</p>\n\n<p>Instead of <code>inv_index</code> being a normal dictionary and having to use <code>inv_index.setdefault(x, []).append((int(y), wordfreq))</code>, just make it a <a href=\"https://docs.python.org/2/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict(list)</code></a>, so you can just do <code>inv_index.append((int(y), wordfreq))</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T14:21:08.807",
"Id": "449486",
"Score": "1",
"body": "Assuming that RegexpTokenizer does what it claims to do, a lot of that function could be discarded just by using a different regexp."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:32:19.773",
"Id": "449505",
"Score": "0",
"body": "Any example for using a different regexp? I am a newbie in python!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T18:06:41.850",
"Id": "449517",
"Score": "1",
"body": "Thank you! converting lists to set really saved some time!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T10:26:33.283",
"Id": "230639",
"ParentId": "230626",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230639",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T23:08:37.300",
"Id": "230626",
"Score": "4",
"Tags": [
"python",
"beginner",
"time-limit-exceeded",
"generator"
],
"Title": "Creating an inverted index from text documents"
}
|
230626
|
<p>I am trying to solve the <a href="https://www.hackerrank.com/challenges/crush/problem" rel="nofollow noreferrer">HackerRank: Array Manipulation</a> problem using Java.</p>
<p>The problem that I am facing is that the program is running for half of the test cases, while for the other half it is showing "Execution couldn't be completed because of Timeout". It seems like there is a more efficient way to do the problem such that the program is executed within the given time frame. If anybody could guide me regarding the issue, it would be of great help.</p>
<p><strong><a href="https://www.hackerrank.com/challenges/crush/problem" rel="nofollow noreferrer">Problem description</a></strong></p>
<blockquote>
<p>Starting with a 1-indexed array of zeros and a list of operations, for
each operation add a value to each of the array element between two
given indices, inclusive. Once all operations have been performed,
return the maximum value in your array.</p>
<p>For example, the length of your array of zeros n=10. Your list of
queries is as follows:</p>
<pre><code>a b k
1 5 3
4 8 7
6 9 1
</code></pre>
<p>Add the values of between the indices and inclusive:</p>
<pre><code>index-> 1 2 3 4 5 6 7 8 9 10
[0,0,0, 0, 0,0,0,0,0, 0]
[3,3,3, 3, 3,0,0,0,0, 0]
[3,3,3,10,10,7,7,7,0, 0]
[3,3,3,10,10,8,8,8,1, 0]
</code></pre>
<p>The largest value is 10 after all operations are performed.</p>
<p><strong>Function Description</strong></p>
<p>Complete the function arrayManipulation in the editor below. It must
return an integer, the maximum value in the resulting array.</p>
<p>arrayManipulation has the following parameters:</p>
<ul>
<li>n - the number of elements in your array</li>
<li>queries - a two dimensional array of queries where each queries[i] contains three integers, a, b, and k.</li>
</ul>
<p><strong>Input Format</strong></p>
<p>The first line contains two space-separated integers <span class="math-container">\$n\$</span> and <span class="math-container">\$m\$</span>,
the size of the array and the number of operations. </p>
<p>Each of the next <span class="math-container">\$m\$</span> lines contains three space-separated integers
<span class="math-container">\$a\$</span>,<span class="math-container">\$b\$</span> and <span class="math-container">\$k\$</span>, the left index, right index and summand.</p>
<p><strong>Constraints</strong></p>
<ul>
<li><span class="math-container">\$ 3 \le n \le 10^7 \$</span></li>
<li><span class="math-container">\$ 1 \le m \le 2 \cdot 10^5 \$</span></li>
<li><span class="math-container">\$ 1 \le a \le b \le n \$</span></li>
<li><span class="math-container">\$ 0 \le k \le 10^9 \$</span></li>
</ul>
<p><strong>Output Format</strong></p>
<p>Return the integer maximum value in the finished array.</p>
</blockquote>
<p><strong>My Solution:</strong></p>
<pre><code>import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the arrayManipulation function below.
static long arrayManipulation(int n, int[][] queries) {
int queryLength = queries.length;
System.out.println(queryLength);
long[] p = new long[n];
int a = 0 , b = 0 , k = 0;
long max=0;
// initialize p
for(int i = 0 ; i < n ; i++)
{
p[i] = 0 ;
}
for(int i = 0 ; i < queryLength ; i++ )
{
a = queries[i][0];
b = queries[i][1];
k = queries[i][2];
for(int j = (a-1) ; j <= (b-1) ; j++)
{
p[j] = p[j] + k ;
}
}
for(int i = 0 ; i < n ; i++)
{
if(p[i]>max)
{
max = p[i];
}
}
return max;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nm = scanner.nextLine().split(" ");
int n = Integer.parseInt(nm[0]);
int m = Integer.parseInt(nm[1]);
int[][] queries = new int[m][3];
for (int i = 0; i < m; i++) {
String[] queriesRowItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int j = 0; j < 3; j++) {
int queriesItem = Integer.parseInt(queriesRowItems[j]);
queries[i][j] = queriesItem;
}
}
long result = arrayManipulation(n, queries);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T08:45:41.657",
"Id": "449470",
"Score": "0",
"body": "You need a better algorithm. You might want to look at other questions about the same challenge, such as https://codereview.stackexchange.com/q/185320/35991, https://codereview.stackexchange.com/q/154144/35991, https://codereview.stackexchange.com/q/95755/35991. The languages are different, but the ideas apply here as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T08:53:51.610",
"Id": "449472",
"Score": "0",
"body": "@MartinR Went through those questions. Not able to comprehend what they have mentioned as the language used for coding is different. If someone could guide what algorithmic changes should I make, maybe I can write the program on my own. Thanks."
}
] |
[
{
"body": "<p>Some general remarks:</p>\n\n<blockquote>\n<pre><code>System.out.println(queryLength);\n</code></pre>\n</blockquote>\n\n<p>The function should only return the result, but not print anything.</p>\n\n<blockquote>\n<pre><code>int a = 0 , b = 0 , k = 0;\n</code></pre>\n</blockquote>\n\n<p>The initial values are not used, and variables should be declared at the narrowest scope, in this case, inside the loop:</p>\n\n<pre><code>for(int i = 0 ; i < queryLength ; i++ )\n{\n int a = queries[i][0];\n int b = queries[i][1];\n int k = queries[i][2];\n // ...\n}\n</code></pre>\n\n<p>Iterating over all queries can also be done with an “enhanced for loop”:</p>\n\n<pre><code>for (int[] query: queries)\n{\n int a = query[0];\n int b = query[1];\n int k = query[2];\n // ...\n}\n</code></pre>\n\n<p>Here</p>\n\n<blockquote>\n<pre><code>for(int j = (a-1) ; j <= (b-1) ; j++)\n</code></pre>\n</blockquote>\n\n<p>the parentheses are not needed, and this</p>\n\n<blockquote>\n<pre><code> p[j] = p[j] + k ;\n</code></pre>\n</blockquote>\n\n<p>can be shortened to </p>\n\n<pre><code>p[j] += k ;\n</code></pre>\n\n<p>The initialization</p>\n\n<blockquote>\n<pre><code>// initialize p\nfor(int i = 0 ; i < n ; i++)\n{\n p[i] = 0 ;\n}\n</code></pre>\n</blockquote>\n\n<p>is not needed because all elements are initialised to 0 by default.</p>\n\n<p>It might be a matter of personal preference, but I would always put horizontal space around operators and keywords, e.g. in</p>\n\n<blockquote>\n<pre><code>if(p[i]>max)\n</code></pre>\n</blockquote>\n\n<p>There are also some unneeded import statements, but those are given by the submission template.</p>\n\n<hr>\n\n<p>But your real problem is that the algorithm is too slow. The inner loop runs up to <span class=\"math-container\">\\$ 10^{7} \\$</span> times, for each of the up to <span class=\"math-container\">\\$ 2 \\cdot 10^{5} \\$</span> queries.</p>\n\n<p>The main idea to improve the performance is to represent the data differently. Instead of storing and updating the array with the actual numbers, one can store and update an array which holds the <em>differences</em> between successive numbers.</p>\n\n<p>Initially, all differences are zero.</p>\n\n<p>Then for each query <span class=\"math-container\">\\$ (a, b, k) \\$</span> you only have to update two entries in the differences array: One difference increases by <span class=\"math-container\">\\$ k\\$</span>, and one difference decreases by <span class=\"math-container\">\\$ k \\$</span>.</p>\n\n<p>Finally you compute the actual numbers by accumulating the differences, and determine the maximum value. </p>\n\n<p>This should be much faster, because the inner loop has been eliminated.</p>\n\n<hr>\n\n<p>Let's take the given example with <span class=\"math-container\">\\$n = 10\\$</span> and the queries</p>\n\n<pre><code>a b k\n1 5 3\n4 8 7\n6 9 1\n</code></pre>\n\n<p>Instead of maintaining an array of the <span class=\"math-container\">\\$ n \\$</span> numbers</p>\n\n<pre>\nindex: 1 2 3 4 5 6 7 8 9 10\ninitial array: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nafter (1, 5, 3): [3, 3, 3, 3, 3, 0, 0, 0, 0, 0]\nafter (4, 8, 7): [3, 3, 3,10,10, 7, 7, 7, 0, 0]\nafter (6, 9, 1): [3, 3, 3,10,10, 8, 8, 8, 1, 0]\n</pre>\n\n<p>we maintain an array of <span class=\"math-container\">\\$ n+1 \\$</span> differences, where each entry <span class=\"math-container\">\\$ d[i] \\$</span> holds the difference <span class=\"math-container\">\\$a[i+1] - a[i] \\$</span>:</p>\n\n<pre>\nindex: 0, 1 2 3 4 5 6 7 8 9 10\ninitial diffs: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nafter (1, 5, 3): [3, 0, 0, 0, 0,-3, 0, 0, 0, 0, 0]\nafter (4, 8, 7): [3, 0, 0, 7, 0,-3, 0, 0,-7, 0, 0]\nafter (6, 9, 1): [3, 0, 0, 7, 0,-2, 0, 0,-7,-1, 0]\nfinal array: [3, 3, 3,10,10, 8, 8, 8, 1, 0]\n</pre>\n\n<p>Do you see that only two entries are updated for each query? Can you figure out the pattern? </p>\n\n<p>The final array is reconstructed by accumulating the final entries in the differences array. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T09:33:39.503",
"Id": "449473",
"Score": "0",
"body": "And I don't want to deprive you from the satisfaction to implement that successfully, therefore I don't post the code for the new algorithm :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T09:53:24.263",
"Id": "449475",
"Score": "0",
"body": "Thank you sir for your insights. But I didn't quite understand the difference portion. Sir, it would be of great help if you would elaborate this a little more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T10:15:41.617",
"Id": "449477",
"Score": "0",
"body": "@Soumee: I have added an example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:25:24.933",
"Id": "449501",
"Score": "0",
"body": "Thank you, Martin. I wrote the code and ran it. It runs perfectly fine. I couldn't have come up with the logic on my own. Now I have to figure out why this \"shorthand\" algorithm mathematically leads to the \"mechanism\" of this program. How can someone figure out the shorthand logic behind codes such as these?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:35:27.987",
"Id": "449506",
"Score": "0",
"body": "@Soumee: I am afraid that “how can someone figure out ...” goes beyond the scope of a code review :) It is often in these challenges that one has to come up with a “suitable” representation of the data in order to solve the problem in time, and there is no general mechanism how to do that. – In this particular case, if you wonder *why* it works: If `d[i] = a[i+1]-a[i]` is the list of differences, then `a[i] = d[0]+d[1]+...+d[i-1]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:53:53.313",
"Id": "449508",
"Score": "0",
"body": "Alright. I get it :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T09:31:32.523",
"Id": "230637",
"ParentId": "230633",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230637",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T08:16:21.653",
"Id": "230633",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Add a value to each of the array element between two given indices successively"
}
|
230633
|
<p>C# lacks a common off-the-shelf encryption and decryption interface for dependency injection. Nearly every codebase I've ever opened has a couple of extension methods for hashing strings and so on. This is always frustrating because it makes it difficult to change the cryptography in one hit. It seems blindingly obvious that there should be a simple interface for encrypting and decrypting strings. So here's one. It can be used for dependency injection.</p>
<pre><code>public interface IOneWayEncryptionService
{
string Encrypt(string text);
}
public interface ICryptographyService : IOneWayEncryptionService
{
string Decrypt(string text);
}
</code></pre>
<p><a href="https://github.com/MelbourneDeveloper/Samples/blob/ab4fce3fd15d633b2e76a41f0cd08d91ee584b29/EncryptionDecryption/EncryptionDecryption/IOneWayEncryptionService.cs#L1" rel="nofollow noreferrer">Code Reference</a></p>
<p><a href="https://github.com/MelbourneDeveloper/Samples/tree/ab4fce3fd15d633b2e76a41f0cd08d91ee584b29/EncryptionDecryption" rel="nofollow noreferrer">Full codebase with unit tests</a></p>
<p>Here are a couple of implementations</p>
<pre><code>public class MD5CryptographyService : IOneWayEncryptionService
{
#region Implementation
public string Encrypt(string text)
{
var md5CryptoServiceProvider = new MD5CryptoServiceProvider();
md5CryptoServiceProvider.ComputeHash(Encoding.UTF8.GetBytes(text));
return md5CryptoServiceProvider.Hash.ToHexStringFromByteArray();
}
#endregion
}
</code></pre>
<p><a href="https://github.com/MelbourneDeveloper/Samples/blob/ab4fce3fd15d633b2e76a41f0cd08d91ee584b29/EncryptionDecryption/EncryptionDecryption/MD5CryptographyService.cs#L1" rel="nofollow noreferrer">Code Reference</a></p>
<pre><code>public class SymmetricAlgorithmCryptographyService : ICryptographyService, IDisposable
{
#region Public Properties
public SymmetricAlgorithm SymmetricAlgorithm { get; }
#endregion
#region Constructors
public SymmetricAlgorithmCryptographyService(SymmetricAlgorithm symmetricAlgorithm)
{
SymmetricAlgorithm = symmetricAlgorithm ?? throw new ArgumentNullException(nameof(SymmetricAlgorithm));
if (symmetricAlgorithm.Key == null || symmetricAlgorithm.Key.Length <= 0)
throw new ArgumentNullException(nameof(SymmetricAlgorithm.Key));
SymmetricAlgorithm = symmetricAlgorithm;
}
#endregion
#region Implementation
public string Decrypt(string text)
{
var cipherTextData = text.ToByteArrayFromHex();
var hex = DecryptStringFromBytes(cipherTextData);
return hex;
}
public string Encrypt(string text)
{
return EncryptStringToBytes(text).ToHexStringFromByteArray();
}
public void Dispose()
{
SymmetricAlgorithm.Dispose();
}
#endregion
#region Private Methods
private IEnumerable<byte> EncryptStringToBytes(string plainText)
{
if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException(nameof(plainText));
var cryptoTransform = SymmetricAlgorithm.CreateEncryptor(SymmetricAlgorithm.Key, SymmetricAlgorithm.IV);
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, cryptoTransform, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
return msEncrypt.ToArray();
}
}
}
private string DecryptStringFromBytes(byte[] cipherTextData)
{
if (cipherTextData == null || cipherTextData.Length <= 0) throw new ArgumentNullException(nameof(cipherTextData));
var cryptoTransform = SymmetricAlgorithm.CreateDecryptor(SymmetricAlgorithm.Key, SymmetricAlgorithm.IV);
using (var msDecrypt = new MemoryStream(cipherTextData))
{
using (var csDecrypt = new CryptoStream(msDecrypt, cryptoTransform, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
#endregion
}
</code></pre>
<p><a href="https://github.com/MelbourneDeveloper/Samples/blob/ab4fce3fd15d633b2e76a41f0cd08d91ee584b29/EncryptionDecryption/EncryptionDecryption/SymmetricAlgorithmCryptographyService.cs#L12" rel="nofollow noreferrer">Code Reference</a></p>
<p>Here is an example usage:</p>
<pre><code>public class EncryptedPersister
{
#region Fields
private readonly ICryptographyService _cryptographyService;
private readonly IIOService _ioService;
#endregion
#region Constructor
public EncryptedPersister(ICryptographyService cryptographyService, IIOService ioService)
{
_cryptographyService = cryptographyService;
_ioService = ioService;
}
#endregion
#region Public Methods
public async Task SaveAsync<T>(string filename, T model)
{
var json = JsonConvert.SerializeObject(model);
var encryptedJson = _cryptographyService.Encrypt(json);
await _ioService.SaveAsync(filename, encryptedJson);
}
public async Task<T> LoadAsync<T>(string filename)
{
var encryptedJson = await _ioService.LoadAsync(filename);
var plainTextJson = _cryptographyService.Decrypt(encryptedJson);
var model = JsonConvert.DeserializeObject<T>(plainTextJson);
return model;
}
#endregion
}
</code></pre>
<p><a href="https://github.com/MelbourneDeveloper/Samples/blob/ab4fce3fd15d633b2e76a41f0cd08d91ee584b29/EncryptionDecryption/EncryptionDecryptionConsole/EncryptedPersister.cs#L7" rel="nofollow noreferrer">Code Reference</a></p>
<pre><code>private static async Task SaveAndLoadCredentials()
{
const string filename = "Credentials.txt";
var encryptedPersister = new EncryptedPersister(CryptographyService, new FileIOService());
await encryptedPersister.SaveAsync(filename, new Credentials { Username = "Bob", Password = "Password123" });
var credentials = await encryptedPersister.LoadAsync<Credentials>(filename);
Console.WriteLine($"AES Decrypted Credentials Username: {credentials.Username} Password: {credentials.Password}");
}
</code></pre>
<p>This leads to nice unit testing:</p>
<pre><code>public class EncryptedPersisterTests : AESEncryptionTestsBase
{
#region Fields
private const string filename = "test";
private const string Username = "Bob";
private const string Password = "Password123";
private const string EncryptedText = "f4e9a35aa90ba645474e53271ee6cff4e0cb1379f10ae6a784eb5f00ce6666d06d9c0562dabb3758975006fd8aa7b7e3";
#endregion
#region Tests
[Test]
public async Task TestSaveAsync()
{
var ioServiceMock = new Mock<IIOService>();
var encryptedPersister = new EncryptedPersister(_symmetricAlgorithmCryptographyService, ioServiceMock.Object);
await encryptedPersister.SaveAsync(filename, new Credentials { Username = Username, Password = Password });
ioServiceMock.Verify(s => s.SaveAsync(filename, EncryptedText), Times.Once);
ioServiceMock.VerifyNoOtherCalls();
}
[Test]
public async Task TestLoadAsync()
{
var ioServiceMock = new Mock<IIOService>();
ioServiceMock.Setup(s => s.LoadAsync(filename)).Returns(Task.FromResult(EncryptedText));
var encryptedPersister = new EncryptedPersister(_symmetricAlgorithmCryptographyService, ioServiceMock.Object);
var credentials = await encryptedPersister.LoadAsync<Credentials>(filename);
ioServiceMock.Verify(s => s.LoadAsync(filename), Times.Once);
ioServiceMock.VerifyNoOtherCalls();
Assert.AreEqual(Username, credentials.Username);
Assert.AreEqual(Password, credentials.Password);
}
#endregion
}
</code></pre>
<p><a href="https://github.com/MelbourneDeveloper/Samples/blob/ab4fce3fd15d633b2e76a41f0cd08d91ee584b29/EncryptionDecryption/EncryptionDecryptionTests/EncryptedPersisterTests.cs#L8" rel="nofollow noreferrer">Code Reference</a></p>
<p><strong><em>Are there any holes in this? What have I not thought of?</em></strong></p>
|
[] |
[
{
"body": "<p>People usually pay not much attention to that, but redundant <code>*Manager</code>, <code>*Processor</code>, <code>*Service</code> suffixes are just some form of signal noise. It is also questionable that two way is really needed the same time at the same place on the consuming side. I would go with:</p>\n\n<pre><code>interface IEncryptor \n{\n byte[] Encrypt(byte array);\n}\n\npublic static class Encryptor\n{\n public static string Encrypt(this IEncryptor encryptor, string text) =>\n (Hex)encryptor.Encrypt((UTF8)text); \n} \n</code></pre>\n\n<p>And:</p>\n\n<pre><code>interface IDecryptor \n{\n byte[] Decrypt (byte array);\n}\n\npublic static class Decryptor\n{\n public static string Decrypt(this IDecryptor encryptor, string text) =>\n (UTF8)encryptor.Decrypt((Hex)text); \n} \n</code></pre>\n\n<p>The helper would be:</p>\n\n<pre><code>class Hex\n{\n public static explicit operator Hex(string hex) => ...\n public static explicit operator Hex(byte[] bytes) => ...\n\n public static implicit operator string(Hex hex) => ...\n public static implicit operator byte[](Hex hex) => ...\n}\n</code></pre>\n\n<p>And: </p>\n\n<pre><code>class UTF8\n{\n public static explicit operator UTF8(string hex) => ...\n public static explicit operator UTF8(byte[] bytes) => ...\n\n public static implicit operator string(UTF8 utf) => ...\n public static implicit operator byte[](UTF8 utf) => ...\n}\n</code></pre>\n\n<p>Now we will have:</p>\n\n<pre><code>public interface IMD5CSP : IEncryptor { … }\n\npublic class MD5CSP : IMD5CSP, IDisposable { … }\n</code></pre>\n\n<p>And I would consume it allowing to be precise in ctor, but having no concrete dependencies later in the code:</p>\n\n<pre><code>class MyService \n{ \n public MyService(IMD5CSP csp) => Encryptor = csp;\n IEncryptor Encryptor { get; }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T20:46:19.363",
"Id": "230667",
"ParentId": "230634",
"Score": "5"
}
},
{
"body": "<blockquote>\n<pre><code>public interface IOneWayEncryptionService\n{\n string Encrypt(string text);\n}\n\npublic interface ICryptographyService : IOneWayEncryptionService\n{\n string Decrypt(string text);\n}\n</code></pre>\n</blockquote>\n\n<p>These seem to be crippled. The basic operations on which almost everything else can be built are</p>\n\n<pre><code>byte[] Encrypt(byte[] plaintext, byte[] key, byte[] iv)\nbyte[] Decrypt(byte[] ciphertext, byte[] key, byte[] iv)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>byte[] Encrypt(byte[] plaintext, byte[] key)\nbyte[] Decrypt(byte[] ciphertext, byte[] key)\n</code></pre>\n\n<p>if the implementations are designed to generate a random IV and to include it as a prefix of the ciphertext.</p>\n\n<p>However, if you want to use the full power of modern cipher modes (e.g. Galois Counter Mode) you get something like</p>\n\n<pre><code>byte[] Encrypt(byte[] plaintext, byte[] authenticated_data, byte[] key, byte[] iv)\n(byte[] plaintext, byte[] authenticated_data) Decrypt(byte[] ciphertext, byte[] key, byte[] iv)\n</code></pre>\n\n<p>and need to document clearly that the output of <code>Encrypt</code> doesn't include the <code>authenticated_data</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public class MD5CryptographyService : IOneWayEncryptionService\n</code></pre>\n</blockquote>\n\n<p><strong>No, no, no!!!</strong> Hashing is <strong>not</strong> encryption. I know Microsoft's <code>System.Security.Cryptography</code> sets a bad example with <code>ICryptoTransform</code>, but they do at least distinguish <code>HashAlgorithm</code> from <code>SymmetricAlgorithm</code>. If you want to write maintainable code, you should do everything in your power to prevent the two concepts from being confused with each other.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:09:22.630",
"Id": "449579",
"Score": "0",
"body": "Why would you pass the extra parameters in to the methods when that data could be injected in to the classes via the constructor? By passing those values as parameters the interfaces become less flexible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:13:40.387",
"Id": "449580",
"Score": "0",
"body": "It can only be injected via the constructor if it's known at that point in time and guaranteed to be immutable. In general, I don't think that either of those are true. If they're true in your particular use case, the point still stands that using `string` rather than `byte[]` cripples the API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:22:19.310",
"Id": "449583",
"Score": "0",
"body": "I'm not sure I agree. The majority of the time that encryption is necessary, it is to encrypt a string. If the encoding is not done as part of the process, it just becomes an extra line of code outside the API that litters the codebase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:26:49.320",
"Id": "449586",
"Score": "0",
"body": "(1) You can turn an arbitrary string into a sequence of bytes efficiently using `UTF8Encoder`. But turning an arbitrary sequence of bytes into a string efficiently is messier. (2) The implementations themselves are all defined in terms of bytes. (Conclusion) The best way to do it is to define the interface in terms of bytes and have extension methods which package together the string encoding/decoding and the encryption."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:13:16.907",
"Id": "449593",
"Score": "0",
"body": "You're right in a sense, but that's the way the Microsoft classes were originally designed, and what you find is coders patching over them left right and centre everywhere. This answer doesn't solve the issues that what I put together tried to solve. It would however have been a good design for the original c# encryption classes."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:04:49.690",
"Id": "230689",
"ParentId": "230634",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T08:42:30.000",
"Id": "230634",
"Score": "4",
"Tags": [
"c#",
"cryptography",
"dependency-injection",
"aes"
],
"Title": "C# Cryptography Interface"
}
|
230634
|
<p>I wrote a small program for hyperskill/jetbrains academy to encrypt the message "we found a treasure!" and print only the ciphertext (in lower case) by replacing each letter with the letter that is in the corresponding position from the end of the English alphabet (a→z, b→y, c→x, ... x→c, y →b, z→a) and without replace spaces or the exclamation mark. </p>
<p>I would like code review comments in terms of correct use of java.</p>
<pre><code>package encryptdecrypt;
public class Main {
final static int lower_case_a = 'a';
final static int lower_case_z = 'z';
public static void main(String[] args) {
String s = "we found a treasure!";
StringBuffer reverse = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((int)c >= lower_case_a && (int)c <= lower_case_z)
reverse.append((char)(lower_case_z - c + lower_case_a));
else
reverse.append((char) c);
}
System.out.println(reverse.toString());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T00:05:41.187",
"Id": "449539",
"Score": "6",
"body": "FWIW, what you've implemented is commonly known as the [Atbash](https://en.wikipedia.org/wiki/Atbash) cipher (using the 26-letter English alphabet), in case anyone wants to Google for it."
}
] |
[
{
"body": "<p>Some my suggestions about your code: instead of iterating over the string <code>s</code> because you are not using the <code>i</code> index inside your loop you could iterate over the char array from s like below:</p>\n\n<pre><code>char[] arr = s.toCharArray();\nfor (char c : arr) { //here the body }\n</code></pre>\n\n<p><strike>Inside the loop you can use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isLowerCase-char-\" rel=\"nofollow noreferrer\">Character.isLowerCase</a> method and you can use a ternary operator to append your character to the <code>StringBuffer</code> evaluating if it is a lowercase character or not:</p>\n\n<pre><code>String s = \"we found a treasure!\";\nchar[] arr = s.toCharArray();\nStringBuffer reverse = new StringBuffer();\n\nfor (char c : arr) {\n char ch = Character.isLowerCase(c) ? (char)(219 - c) : c; //<-- 219 = int('a') + int('z')\n reverse.append(ch);\n}\n</code></pre>\n\n<p>Inside the loop I put 219 because it is a const value so it is not useful recalculate it for every iteration of the loop.\n</strike></p>\n\n<p>Note: due to the right observations I decided to strike part of my code solution, so it remains just the code mentioned in other answers. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T19:51:41.397",
"Id": "449528",
"Score": "3",
"body": "I'm pretty sure the compiler is smart enough to realize that additions of constants can be replaced by an actual constant. The loss in readability is not worth it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T20:31:20.180",
"Id": "449531",
"Score": "0",
"body": "@njzk2 I'm agree, I put a comment to explain why I'm using directly a number but probably it would have been better create a local variable as sum of `a` and `z` and use the variable in the loop. The optimal idea would be create a method that returns the expected string as you thought in your answer to make easier the tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:19:04.960",
"Id": "449697",
"Score": "0",
"body": "@downvoter, please explain the reason for downvote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:13:50.267",
"Id": "449763",
"Score": "0",
"body": "The previous comment already explained it I thought: a) this is the mother of all premature optimization and b) the compiler is more than capable of hoisting the computation out of the loop so it's not even an optimization. There simply is no reason whatsoever to ever do this here. Even if you had a compiler from the 70s that couldn't do this, the performance hit would be completely unmeasurable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:21:08.690",
"Id": "449765",
"Score": "1",
"body": "(There's also the additional problem that the code introduces an error contrary to the original code, since `Character.isLowerCase` handles Unicode but the rest of the code assumes just simple ASCII)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T06:00:08.783",
"Id": "449833",
"Score": "0",
"body": "@Voo You are right."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T11:11:40.943",
"Id": "230640",
"ParentId": "230636",
"Score": "2"
}
},
{
"body": "<p>With</p>\n\n<pre><code>final static int lower_case_a = 'a';\nfinal static int lower_case_z = 'z';\n</code></pre>\n\n<p>While it's arguably good that you have <code>'a'</code> and <code>'z'</code> stored as variables and not floating around, I don't think they're named well. <code>lower_case_a</code> tells you exactly as much as <code>'a'</code> itself, so you aren't really gaining much. The <em>purpose</em> of the variable would make for a better name. Also, since those are constants, <a href=\"https://www.oracle.com/technetwork/articles/javaee/codeconventions-135099.html\" rel=\"nofollow noreferrer\">they should be upper case, and underscore-separated</a>. I'd change those lines to:</p>\n\n<pre><code>final static int ALPHABET_LOWER_BOUND = 'a';\nfinal static int ALPHABET_UPPER_BOUND = 'z';\n</code></pre>\n\n<p>Also, as mentioned in the above link, Java uses camelCase, not snake_case.</p>\n\n<hr>\n\n<pre><code>if ((int)c >= lower_case_a && (int)c <= lower_case_z)\n reverse.append((char)(lower_case_z - c + lower_case_a));\nelse\n reverse.append((char) c);\n</code></pre>\n\n<p>This has a few notable things:</p>\n\n<ul>\n<li><p>Do not omit braces here. I won't go as far as to say that they should <em>never</em> be omitted, but the cases where it's appropriate to not use them are pretty slim. If you ever make changes to those lines and don't notice that you didn't use braces, at best you'll need to deal with syntax errors, and at worst you'll get weird behavior that you'll need to debug. Just use them. It costs next to nothing and prevents a range of errors.</p></li>\n<li><p>Instead of writing <code>(int)c</code> in a few places, I'd probably instead save that in a variable.</p></li>\n<li><p><code>(char) c</code> isn't necessary. <code>c</code> is already a <code>char</code>.</p></li>\n<li><p>You could use a ternary since each branch is just giving its data to <code>append</code>.</p></li>\n</ul>\n\n<p>Something closer to:</p>\n\n<pre><code>int code = c;\nchar newChar = (code >= ALPHABET_LOWER_BOUND && code <= ALPHABET_UPPER_BOUND)\n ? (ALPHABET_UPPER_BOUND - c + ALPHABET_LOWER_BOUND) : c;\n\nreverse.append(newChar);\n</code></pre>\n\n<p>Although whether you'd want to use a ternary here is subjective. That line is a little long.</p>\n\n<p>I also agree with @dariosicily though. You never use <code>i</code> for anything other than indexing, so you might as well just use a foreach loop and iterate the string directly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T09:25:03.897",
"Id": "449576",
"Score": "4",
"body": "Nit: you have \"lower bound\" and \"upper bound\" the wrong way around; `code > ALPHABET_UPPER_BOUND` would mean \"`code` is above the upper bound, i.e. outside the accepted range\". What we want to say is \"`code` is equal to or higher than the lowest allowed value\", so `code >= ALPHABET_LOWER_BOUND`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:35:10.643",
"Id": "449624",
"Score": "0",
"body": "Also you didn't replace `lower_case_[a/z]` here: `(lower_case_z - c + lower_case_a)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T16:04:01.897",
"Id": "449645",
"Score": "0",
"body": "Fixed both. Thanks guys."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:52:52.293",
"Id": "230653",
"ParentId": "230636",
"Score": "7"
}
},
{
"body": "<p>A few points:</p>\n\n<ul>\n<li>Constants are always written in uppercase in Java</li>\n<li>If you are not using those constants anywhere else, make them <code>private</code></li>\n<li>Create a method to do your reversal (e.g. <code>public String applyCipher(String input) {...}</code>). This way, you can write unit tests for it, confirming all corner cases of your algorithm (like leaving alone the letters not in that range, capital letters, digits, punctuation) and proving that your code works</li>\n<li>Use <code>for (char c: input.toCharArray()) {...}</code>, as you don't need the index of the character</li>\n<li>Never use if blocks without brackets. (see <a href=\"https://stackoverflow.com/a/2125078/671543\">https://stackoverflow.com/a/2125078/671543</a>)</li>\n<li><s><code>Character</code> class has a <code>getType</code>, which can tell you that a char is a lowercase letter. <code>Character.getType(c) == Character.LOWERCASE_LETTER</code></s> LOWERCASE_LETTER contains way more than the English alphabet, so don't do that</li>\n<li>To avoid char arithmetic, you can do something like this:</li>\n</ul>\n\n<pre><code>String alphabet = \"abcdefghijklmnopqrstuvwxyz\";\nString reversed = new StringBuilder(alphabet).reverse().toString();\nMap<Character, Character> table = IntStream\n .range(0, alphabet.size())\n .boxed()\n .collect(Collectors.toMap(alphabet::charAt, reversed::charAt));\n</code></pre>\n\n<p>and use the table to map your characters directly</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:31:14.657",
"Id": "449767",
"Score": "1",
"body": "The last point is a really bad idea, since `Character.LOWERCASE_LETTER` is something very different to [a-z]. If you wanted to handle unicode that would require a whole lot more than simply using that character class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T01:36:31.213",
"Id": "449824",
"Score": "0",
"body": "@Voo good point, the OP specifies \"english alphabet\". I don't like the idea of treating chars as numbers, though, so I'll suggest something else"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T20:02:47.017",
"Id": "230664",
"ParentId": "230636",
"Score": "4"
}
},
{
"body": "<blockquote>\n<pre><code> StringBuffer reverse = new StringBuffer();\n</code></pre>\n</blockquote>\n\n<p>A <code>StringBuffer</code> is only needed if you are going to access the same variable from multiple threads. Your program is single-threaded, so you're not doing that. (Even in multi-threaded programs, you may not use the variable across threads. But here you are simply singled-threaded.) Just use a <code>StringBuilder</code> instead. </p>\n\n<pre><code> StringBuilder ciphered = new StringBuilder(s.length());\n</code></pre>\n\n<p>The <code>StringBuilder</code> has the same interface as the <code>StringBuffer</code>, but it is more efficient. It doesn't waste time synchronizing the accesses. </p>\n\n<p>I don't like the name <code>reverse</code>, as to me it implies changing the <em>order</em> of the characters rather than their place in the alphabet. </p>\n\n<p>Since you know the length of the string that you are building, you might as well tell the constructor at initialization. That way it can allocate the correct amount of memory once rather than going through repeated resizing operations. </p>\n\n<h3>Java 8 Streams</h3>\n\n<p>If you are using Java 8 or later, you could do this with a <code>Stream</code> instead. Something like </p>\n\n<pre><code>String ciphered = s.codePoints()\n .map(c -> (c >= 'a' && c <= 'z') ? 'a' + 'z' - c : c)\n .collect(StringBuilder::new,\n StringBuilder::appendCodePoint,\n StringBuilder::append)\n .toString();\n</code></pre>\n\n<p>I removed the named constants as they actively harm readability. And renamed I'm not sure about the functionality, as this only works for contiguous alphabets. In my opinion, this works better as being strictly limited to the Latin1 alphabet. For the same reason, I don't use <code>Character.isLowerCase</code>. That will attempt to apply the Latin1 transformation to letters from other alphabets, which simply won't work. </p>\n\n<h3>See also</h3>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/49543782/6660678\">Java Stream .map capitalize first letter only</a></li>\n<li><a href=\"https://stackoverflow.com/q/20266422/6660678\">Simplest way to print an <code>IntStream</code> as a <code>String</code></a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T05:53:18.990",
"Id": "230679",
"ParentId": "230636",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T09:24:00.550",
"Id": "230636",
"Score": "8",
"Tags": [
"java"
],
"Title": "Replacing each letter with the letter that is in the corresponding position from the end of the English alphabet"
}
|
230636
|
<p>I am working on <strong>state space search</strong> (8 Puzzle) in Python and when I run my program with <code>python3 -m profile</code>, I find out that most of time program performs a few functions. I would like to optimize functions bellow (if it's possible).</p>
<p>I am using dictionary <code>node</code>, whose structure is:</p>
<pre><code>{
'id': string, # Unique ID of node, e. g. '123456708'.
'state': array, # Numpy array 3x3 with unique numbers 1-8 and 0, e. g. [[1 2 3] [4 5 6] [7 0 8]].
'pos': tuple, # Current position of 0 in node's state, e. g. (2, 1).
}
</code></pre>
<h2>swap</h2>
<p>Function accepts 2D <code>array</code>, <code>pos1</code> and <code>pos2</code> and returns new array with swapped elements on positions.</p>
<pre><code># [1 2 3] [0 2 3]
# [4 5 6] -> swap((2, 1), (0, 0)) -> [4 5 6]
# [7 0 8] [7 1 8]
def swap(array, pos1, pos2):
result = numpy.copy(array)
result[pos1], result[pos2] = result[pos2], result[pos1]
return result
</code></pre>
<h2>create</h2>
<p>Function that accepts <code>state</code> and <code>pos</code> of <code>0</code> in state and returns node with this state.</p>
<pre><code>def create(state, pos):
return { 'id': hash(state.tostring()), 'state': state, 'pos': pos }
</code></pre>
<h2>move</h2>
<p>Function, that accepts <code>node</code> and vector <code>change</code> and returns new node with changed state. New state is created when <code>0</code> in state is moved by vector (changeY, changeX) <code>change</code>. If new state has invalid index, return <code>None</code> instead.</p>
<pre><code># [1 2 3] [1 2 3]
# [4 5 6] -> move(-1, 0) -> [4 0 6]
# [7 0 8] [7 5 8]
def move(node, change):
newPos = (node['pos'][0] + change[0], node['pos'][1] + change[1]) # numpy.add(node['pos'], change) is slower.
if 0 <= newPos[0] <= 2 and 0 <= newPos[1] <= 2: # Valid index
newState = swap(node['state'], node['pos'], newPos)
return create(newState, newPos)
return None # Invalid index.
</code></pre>
<h2>getSuccessors</h2>
<p>Function that accepts <code>node</code> in state and returns all nodes which state is about -1 or 1 different vertically or horizontally (not both):</p>
<pre><code># [1 2 3] [1 2 3] [1 2 3] [1 2 3]
# [4 5 6] -> getSuccessors() -> [4 0 6] [4 5 6] [4 5 6]
# [7 0 8] [7 5 8] [0 7 8] [7 8 0]
def getSuccessors(node):
moves = [
move(node, (-1, 0)),
move(node, (1, 0)),
move(node, (0, -1)),
move(node, (0, 1)),
]
return list(filter(lambda node: node is not None, moves))
</code></pre>
<h2>findPath</h2>
<p>Function accepts numpy 3x3 arrays <code>init</code> and <code>goal</code> and search successors of <code>init</code> until one of successors will be <code>goal</code>.</p>
<pre><code>def findPath(init, goal):
explored = {} # Already explored nodes.
pos = numpy.where(init == 0)
unexplored = [create(init, (pos[0][0], pos[1][0]))] # Unexplored nodes.
while True:
if not unexplored: # If there is no node to explore, puzzle has no solution.
return None
node = unexplored.pop(0) # Bfs algorithm is slow, but for testing purposes.
if numpy.array_equal(node['state'], goal):
return 'Success' # Should be path, but for now is not important.
explored[node['id']] = node
for successor in getSuccessors(node): # Add successors to unexplored nodes.
if successor['id'] not in explored:
unexplored.append(successor)
</code></pre>
<p>When I run this program <code>python3 puzzle.py</code>, it takes 13.36 seconds:</p>
<pre><code>import time
import numpy
start = time.time()
init = numpy.array([[7, 2, 4], [5, 0, 6], [8, 3, 1]])
goal = numpy.array([[1, 3, 0], [5, 2, 6], [4, 7, 8]])
print(findPath(init, goal)) # 'Success'
end = time.time()
print(end - start) # 13.36 s
</code></pre>
<p>With <code>python3 -m profile puzzle.py | grep "puzzle.py"</code>:</p>
<pre><code> ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 52.771 52.771 profile:0(<code object <module> at 0x7fa52c125300, file "puzzle.py", line 1>)
1 0.131 0.131 52.752 52.752 puzzle.py:1(<module>)
1638628 6.305 0.000 25.991 0.000 puzzle.py:12(move)
409657 4.410 0.000 31.730 0.000 puzzle.py:21(getSuccessors)
1638628 1.330 0.000 1.330 0.000 puzzle.py:29(<lambda>)
1 3.066 3.066 52.195 52.195 puzzle.py:31(findPath)
1106988 3.519 0.000 14.525 0.000 puzzle.py:4(swap)
1106989 3.049 0.000 5.161 0.000 puzzle.py:9(create)
</code></pre>
<p>Most of the time was <code>move</code> executed (6.3 s), then <code>getSuccessors</code> (4.4 s), <code>swap</code>, <code>findPath</code> and <code>create</code>. Is there any way to optimize these functions? <a href="https://repl.it/repls/WigglyExtralargeAssembly" rel="nofollow noreferrer">Here</a> is the whole program (even slower than on my PC).</p>
|
[] |
[
{
"body": "<p>The initial approach definitely has a number of \"bottlenecks\" and space for optimizations.\nLet me present and explain the crucial points:</p>\n\n<ul>\n<li>starting with good naming: don't give Python identifiers/functions <em>camelCased</em> names. We'll have <code>find_path</code>, <code>get_successors</code> etc. </li>\n<li><code>explored</code> dict accumulates a great number of dictionaries (<code>nodes</code>) indexed by their <code>id</code> attribute (<em>\"hash\"</em>). But those dictionaries are not used, only keys are used to keep track of processing unique <code>id</code>s (<em>hashes</em>). Memory-free solution for this point is using <code>set</code> instead to keep unique hashes. <code>explored = set()</code></li>\n<li><code>unexplored</code> list. At the end of the processing I noticed it grown to size of <code>53003</code>. As the main operations on this list are appending to and popping out the 1st item - the optimized way would be to use a high-performance <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>deque</code></a> object (Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same <code>O(1)</code> performance in either direction)</li>\n<li>function <code>move</code> performs a lot of <em>falsy</em> calls (returning <code>None</code>). That makes the caller <code>get_successors</code> accumulate both valid and <em>falsy</em> movements (<code>moves</code> list) and perform filtration on each call. Instead, we'll make <code>get_successors</code> to work as generator function which yields only successfully moved nodes (after <em>valid</em> movements)</li>\n<li>looping over <code>for successor in getSuccessors(node):</code> performs a hundreds of redundant iterations testing <em>successors</em>(nodes) which hashes were already present in <code>explored</code> <em>hash</em> storage. To watch that happened you can add <code>else:</code> branch with debugging printing to <code>if successor['id'] not in explored: ...</code> condition within the loop. \nTo avoid that, in connection to the previous Optimization tip, we'll extend <code>get_successors</code> function more to get correctly moved nodes that aren't present in <code>explored</code> hash-set.</li>\n</ul>\n\n<hr>\n\n<p>From theory to practice:</p>\n\n<pre><code>import numpy as np\nimport time\nfrom collections import deque\n\n\ndef swap(array, pos1, pos2):\n result = np.copy(array)\n result[pos1], result[pos2] = result[pos2], result[pos1]\n return result\n\n\ndef create(state, pos):\n return {'id': hash(state.tostring()), 'state': state, 'pos': pos}\n\n\ndef move(node, change):\n new_pos = (node['pos'][0] + change[0], node['pos'][1] + change[1]) # np.add(node['pos'], change) is slower.\n\n if 0 <= new_pos[0] <= 2 and 0 <= new_pos[1] <= 2: # Valid index\n new_state = swap(node['state'], node['pos'], new_pos)\n return create(new_state, new_pos)\n\n\ndef get_successors(node, explored):\n for new_pos in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n changed_node = move(node, new_pos)\n if changed_node and changed_node['id'] not in explored:\n yield changed_node\n\n\ndef find_path(init, goal):\n explored = set() # Already explored nodes.\n pos = np.where(init == 0)\n unexplored = deque([create(init, (pos[0][0], pos[1][0]))]) # Unexplored nodes.\n\n while True:\n if not unexplored: # If there is no node to explore, puzzle has no solution.\n return None\n\n node = unexplored.popleft()\n\n if np.array_equal(node['state'], goal):\n return 'Success' # Should be path, but for now is not important.\n\n explored.add(node['id'])\n\n for successor in get_successors(node, explored): # Add successors to unexplored nodes.\n unexplored.append(successor)\n\n\nstart = time.time()\ninit = np.array([[7, 2, 4], [5, 0, 6], [8, 3, 1]])\ngoal = np.array([[1, 3, 0], [5, 2, 6], [4, 7, 8]])\n\nprint(find_path(init, goal))\nend = time.time()\nprint(end - start)\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>Success\n5.768321752548218\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:42:06.303",
"Id": "449598",
"Score": "1",
"body": "Thanks for useful hints and explanation. The program is now really 2 times faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T15:24:30.277",
"Id": "449644",
"Score": "0",
"body": "@Michal, you're welcome"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T18:38:25.650",
"Id": "230660",
"ParentId": "230643",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230660",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T12:42:14.060",
"Id": "230643",
"Score": "5",
"Tags": [
"python",
"performance",
"numpy",
"sliding-tile-puzzle"
],
"Title": "State space search for sliding tile puzzle"
}
|
230643
|
<p>Sometimes I save a file somewhere but can't find it after or I install something and want to see what files were added. For this reason, I created a winforms app which only displayes files created/changed/accessed in a certain timespan. Since the windows timestamps aren't reliable when it comes to folders (see <a href="https://stackoverflow.com/a/46428666/10883465">here</a>), I have to use my own filter for files and folders. This filter is first used to determine if a folder should be displayed (explorer-like tree-view) and will short-circuit if any file which matches the filter is found in any subdirectory of the folder. It's later on also used for each file to see if it should be displayed or not (explorer-like list-view).</p>
<p>I have an enum for the search categories.</p>
<pre><code>[Flags]
enum SearchCriteria
{
None = 0,
CreationTime = 1 << 0,
LastModified = 1 << 1,
LastAccess = 1 << 2
}
</code></pre>
<p>When a user decides to filter for creation time, it will stay like this every time the filter is applied for at least one folder. This means, I don't want to check the search criteria every time the filter runs because that would be wasted comparisons and this one is all about performance. I came up with a solution using a cache for folders and expression trees from which I compile a function which is as efficient as possible so the search critera are only checked once and the actual filter will be compiled dynamically. There is a similar case with <code>_considerFolderStamps</code> (see the comments) which should be improved but I don't know how without using expression trees for the whole filter (not just the time comparisons).<br>
Here's the code for that:</p>
<pre><code>private readonly Dictionary<string, bool> _matchesCache = new Dictionary<string, bool>();
private Predicate<FileSystemInfo> GetFilter(DateTime start, DateTime end, SearchCriteria searchCriteria)
{
if (searchCriteria == SearchCriteria.None)
{
// just include everything
return f => true;
}
else
{
Expression<Predicate<FileSystemInfo>> expression = null;
// add filter for creation time
if (searchCriteria.HasFlag(SearchCriteria.CreationTime))
{
Expression<Predicate<FileSystemInfo>> checkCreationTime = info => info.CreationTime.Between(start, end);
expression = checkCreationTime; // no need to check, expression is null
}
// add filter for modified time (|| existing if necessary)
if (searchCriteria.HasFlag(SearchCriteria.LastModified))
{
Expression<Predicate<FileSystemInfo>> checkLastModified = info => info.LastWriteTime.Between(start, end);
expression = expression.OrIfNotNull(checkLastModified);
}
// add filter for access time (|| existing if necessary)
if (searchCriteria.HasFlag(SearchCriteria.LastAccess))
{
Expression<Predicate<FileSystemInfo>> checkLastAccess = info => info.LastAccessTime.Between(start, end);
expression = expression.OrIfNotNull(checkLastAccess);
}
// compile to delegate
Predicate<FileSystemInfo> coreFilter = expression.Compile();
// return predicate which additionally uses cache for folders in combination with the core-filter
return f => ContainsAnyChange(f, coreFilter);
}
}
private bool ContainsAnyChange(FileSystemInfo info, Predicate<FileSystemInfo> coreFilter)
{
if (info is DirectoryInfo dir)
{
if (_matchesCache.TryGetValue(info.FullName, out bool matchesFromCache))
{
// log entry
return matchesFromCache;
}
// The user can decide if the timestamps of the folder itself should also be considered.
// Just like with the search criteria, this won't change and checking for _considerFolderStamps should only be done once.
// However, since it's not in the core-filter I would need to expand the expression stuff and build the whole filter using expressions.
if (_considerFolderStamps && coreFilter(info))
{
_matchesCache.Add(info.FullName, true);
return true;
}
try
{
// recursive call for the folder content
bool containsChange = dir.EnumerateFileSystemInfos()
.Any(f => ContainsAnyChange(f, coreFilter));
_matchesCache.Add(info.FullName, containsChange);
return containsChange;
}
catch (UnauthorizedAccessException)
{
// log entry
_matchesCache.Add(info.FullName, false);
return false;
}
catch (DirectoryNotFoundException) // this happens for symbolic links like Desktop
{
// log entry
_matchesCache.Add(info.FullName, false);
return false;
}
}
// it's just a file at this point
return coreFilter(info);
}
</code></pre>
<p>You also need these extensions along with a parameter-expression-visitor.</p>
<pre><code>internal class SubstParameterExpressionVisitor : ExpressionVisitor
{
private readonly Dictionary<Expression, Expression> _subst = new Dictionary<Expression, Expression>();
protected override Expression VisitParameter(ParameterExpression node)
{
if (_subst.TryGetValue(node, out Expression newValue))
{
return newValue;
}
return node;
}
public Expression this[Expression original]
{
get => _subst[original];
set => _subst[original] = value;
}
}
public static Expression<Predicate<T>> Or<T>(this Expression<Predicate<T>> a, Expression<Predicate<T>> b)
{
if (a == null)
throw new ArgumentNullException(nameof(a));
if (b == null)
throw new ArgumentNullException(nameof(b));
ParameterExpression parameter = a.Parameters[0];
SubstParameterExpressionVisitor visitor = new SubstParameterExpressionVisitor();
visitor[b.Parameters[0]] = parameter;
Expression combinedBody = Expression.OrElse(a.Body, visitor.Visit(b.Body));
return Expression.Lambda<Predicate<T>>(combinedBody, parameter);
}
public static Expression<Predicate<T>> OrIfNotNull<T>(this Expression<Predicate<T>> a, Expression<Predicate<T>> b) =>
a == null ? b : a.Or(b);
public static bool Between(this DateTime input, DateTime inclStart, DateTime exclEnd) =>
input >= inclStart && input < exclEnd;
</code></pre>
<p>Since this filter is applied to hundreds of folders and files (it's applied recursively), it has to be really performant. I know that there are other factors which can slow down the program especially when working with a <code>TreeView</code> and <code>ListView</code> but <strong>this question is solely about this filter</strong>. </p>
<p>Some things maybe worth mentioning:</p>
<ul>
<li><code>GetFilter</code> is called once to get a predicate which can decide if a file/folder should be included in the view.</li>
<li>The cache is a dictionary for fast access where filtered folders are saved. Files are not included in the cache since adding the full path for every file in your system to a dictionary uses a lot of memory.</li>
<li>The code for the full project can be found <a href="https://github.com/Joelius300/LastUpdatedExplorer" rel="nofollow noreferrer">here</a>.</li>
<li>I might ask another question later on about the other part (winforms etc) since performance is very important there too. In this question I'd only like feedback about the shown code though.</li>
<li>If it's not clear already, this question is all about performance but, as always, any constructive critisism is very welcome :)</li>
<li>The current speed is acceptable but when you choose a very small timespan which matches very few files in a big system.. you have quite a big waiting and it would be nice to reduce this a bit further.</li>
</ul>
<p>Also here are debug views of two examples core-filters (expression) built from the search criteria using expression tree manipulation. They are working correctly.</p>
<pre><code>.Lambda #Lambda1<System.Predicate`1[System.IO.FileSystemInfo]>(System.IO.FileSystemInfo $info) {
.Call LastUpdatedExplorer.DateTimeExtensions.Between(
$info.LastWriteTime,
(.Constant<LastUpdatedExplorer.HostView+<>c__DisplayClass9_1>(LastUpdatedExplorer.HostView+<>c__DisplayClass9_1).CS$<>8__locals1).start,
(.Constant<LastUpdatedExplorer.HostView+<>c__DisplayClass9_1>(LastUpdatedExplorer.HostView+<>c__DisplayClass9_1).CS$<>8__locals1).end)
}
.Lambda #Lambda1<System.Predicate`1[System.IO.FileSystemInfo]>(System.IO.FileSystemInfo $info) {
.Call LastUpdatedExplorer.DateTimeExtensions.Between(
$info.CreationTime,
(.Constant<LastUpdatedExplorer.HostView+<>c__DisplayClass9_1>(LastUpdatedExplorer.HostView+<>c__DisplayClass9_1).CS$<>8__locals1).start,
(.Constant<LastUpdatedExplorer.HostView+<>c__DisplayClass9_1>(LastUpdatedExplorer.HostView+<>c__DisplayClass9_1).CS$<>8__locals1).end)
|| .Call LastUpdatedExplorer.DateTimeExtensions.Between(
$info.LastWriteTime,
(.Constant<LastUpdatedExplorer.HostView+<>c__DisplayClass9_1>(LastUpdatedExplorer.HostView+<>c__DisplayClass9_1).CS$<>8__locals1).start,
(.Constant<LastUpdatedExplorer.HostView+<>c__DisplayClass9_1>(LastUpdatedExplorer.HostView+<>c__DisplayClass9_1).CS$<>8__locals1).end)
|| .Call LastUpdatedExplorer.DateTimeExtensions.Between(
$info.LastAccessTime,
(.Constant<LastUpdatedExplorer.HostView+<>c__DisplayClass9_1>(LastUpdatedExplorer.HostView+<>c__DisplayClass9_1).CS$<>8__locals1).start,
(.Constant<LastUpdatedExplorer.HostView+<>c__DisplayClass9_1>(LastUpdatedExplorer.HostView+<>c__DisplayClass9_1).CS$<>8__locals1).end)
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T15:45:20.743",
"Id": "230646",
"Score": "2",
"Tags": [
"c#",
"performance",
"recursion"
],
"Title": "File and folder filter for a \"last-updated explorer\""
}
|
230646
|
<p>I'm writing a bash script for my tablet laptop to flip the screen depending on a file in Manjaro Linux. My current script is the following:</p>
<pre><code>while true
do
state=$(cat /sys/devices/platform/thinkpad_acpi/hotkey_tablet_mode) #This file indicates if it's in tablet mode or not
if [[ $state == 0 && $oldState == 1 ]]
then
xrandr --output LVDS1 --rotate normal
xsetwacom --set "$a" Rotate none
xsetwacom --set "$b" Rotate none
xsetwacom --set "$c" Rotate none
oldState=0
elif [[ $state == 1 && $oldState == 0 ]]
then
xrandr --output LVDS1 --rotate inverted
xsetwacom --set "$a" Rotate half
xsetwacom --set "$b" Rotate half
xsetwacom --set "$c" Rotate half
oldState=1
/home/eto/scripts/backlight 0
fi
sleep 1s
done
</code></pre>
<p>The code in the if statements don't matter, but what I'm worried about is the entire logic of how it checks the tablet mode. Is there a better way to check the tablet mode indicator file rather than a while loop? I feel like this is a very inefficient way of doing so as it reads the disk quite frequently, but I don't see how else I could approach this. Any input is appreciated as I'm very much an amateur with coding.</p>
|
[] |
[
{
"body": "<h1>Good</h1>\n\n<p>I like most of what you've done so far as is:</p>\n\n<ul>\n<li>Using <code>[[</code> (double square brackets) for conditionals is a good practice.</li>\n<li>Using <code>$()</code> for command substitution instead of the classic backticks is also a good modern shell practice.</li>\n<li>Most of your variable substitutions are quoted. This is a good habit in case the variable contains spaces it won't get broken up by shell parsing.</li>\n</ul>\n\n<h1>Could be better</h1>\n\n<p>There are some minor things I'd improve:</p>\n\n<ul>\n<li>include the <code>#!</code> line at the top</li>\n<li>typically you see folks add their <code>then</code>s to the end of the previous line like <code>if [[ cond ]]; then</code>. Your outer loop could also be done as <code>while true; do</code>.</li>\n<li>the comment gets sort of lost out on the right. Why not put it on the line above?</li>\n</ul>\n\n<h1>Think about</h1>\n\n<p>The script is getting invoked every second and chewing up some amount of CPU. There's probably not much CPU being burned in this case, but one thing to consider is whether this sort of polling could be avoided. Linux includes inotify as a function to let processes known when a file has changed so they don't have to constantly check the file themselves. This is available in the shell through <a href=\"https://linux.die.net/man/1/inotifywait\" rel=\"nofollow noreferrer\"><code>inotifywait</code></a>. If the file you're checking works with <code>inotifywait</code> you could avoid the <code>sleep</code>.</p>\n\n<p>A bonus you get beyond conserving CPU from skipping <code>sleep</code> is that the script should run with lower latency. Instead of needing to wait for up to a second to detect the change your script would be invoked within a small fraction of a second.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T23:04:12.803",
"Id": "449536",
"Score": "0",
"body": "I was really only looking for you to recommend `inotifywait`, but thanks for the other suggestions!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T22:18:20.717",
"Id": "230669",
"ParentId": "230649",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:05:40.140",
"Id": "230649",
"Score": "4",
"Tags": [
"beginner",
"bash",
"linux"
],
"Title": "Bash script to reconfigure the screen orientation when entering or exiting tablet mode"
}
|
230649
|
<p>First question here on CodeReview. I was directed here from a question I asked on SO: <a href="https://stackoverflow.com/questions/58364613/swift-protocol-with-lazy-property-cannot-use-mutating-getter-on-immutable-valu/58364648">Swift protocol with lazy property - Cannot use mutating getter on immutable value: '$0' is immutable</a>.</p>
<p>Goal: Create a protocol that allows lazy computation of a property for structs that conform to the protocol. The computation is intensive and should only be executed once, hence the lazy requirement.</p>
<p>So, after lots of reading (eg <a href="https://stackoverflow.com/questions/28202834/swift-struct-with-lazy-private-property-conforming-to-protocol">Swift Struct with Lazy, private property conforming to Protocol</a>, where I based this code on) and trial and error, I came up with something that works:</p>
<pre><code>import Foundation
protocol Foo {
var footype: Double { mutating get }
func calculateFoo() -> Double
}
struct Bar: Foo {
private lazy var _footype: Double = {
let value = calculateFoo()
return value
}()
var footype: Double {
mutating get {
return _footype
}
}
func calculateFoo() -> Double {
print("calc")
return 3.453
}
}
</code></pre>
<p>Testing this in a Playground:</p>
<pre><code>var bar = Bar()
print(bar.footype)
print(bar.footype)
</code></pre>
<p>And the output is:</p>
<pre><code>calc
3.453
3.453
</code></pre>
<p>So it is working. But it feels like a hack using <code>_footype</code></p>
<p>Also in the comments, it was suggested that </p>
<blockquote>
<p>However, I would not put calculateFoo in the protocol because it sounds like an implementation detail.</p>
</blockquote>
<p>Appreciate any comments and/or improvements. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:19:01.957",
"Id": "449512",
"Score": "1",
"body": "Welcome to Code Review!"
}
] |
[
{
"body": "<p>You don't need the additional <code>_footype</code> variable and a computer “wrapper” property. The protocol requirement can be satisfied with a lazy stored property:</p>\n\n<pre><code>struct Bar: Foo {\n lazy var footype = calculateFoo()\n\n func calculateFoo() -> Double {\n print(\"calc\")\n return 3.453\n }\n}\n</code></pre>\n\n<p>Now <code>footype</code> is read-only for instances of type <code>Foo</code> </p>\n\n<pre><code>var foo: Foo = Bar()\nprint(foo.footype)\nfoo.footype = 12.3 // Error: Cannot assign to property: 'footype' is a get-only property\n</code></pre>\n\n<p>but as a property of <code>Bar</code> it is read-write:</p>\n\n<pre><code>var bar = Bar()\nprint(bar.footype)\nbar.footype = 12.3 // OK\n</code></pre>\n\n<p>If assigning to the <code>footype</code> property should be inhibited then you can mark it with a <code>private(set)</code> access modifier:</p>\n\n<pre><code>struct Bar: Foo {\n private(set) lazy var footype = calculateFoo()\n\n func calculateFoo() -> Double {\n print(\"calc\")\n return 3.453\n }\n}\n\nvar bar = Bar()\nprint(bar.footype)\nbar.footype = 12.3 // Cannot assign to property: 'footype' setter is inaccessible\n</code></pre>\n\n<p>With respect to</p>\n\n<blockquote>\n <p>However, I would not put calculateFoo in the protocol because it sounds like an implementation detail.</p>\n</blockquote>\n\n<p>Yes, in your current code it is an implementation detail of the <code>Bar</code> class. The only use would be that a caller can “enforce” the evaluation:</p>\n\n<pre><code>var foo: Foo = Bar()\nfoo.calculateFoo()\n</code></pre>\n\n<p>The situation would be different if there were a way to provide a default implementation in an extension method:</p>\n\n<pre><code>protocol Foo {\n var footype: Double { mutating get }\n\n func calculateFoo() -> Double\n}\n\nextension Foo {\n var footype: Double {\n // Call calculateFoo() on first call only ...\n }\n}\n</code></pre>\n\n<p>so that conforming to the protocol is sufficient, i.e. <code>Bar</code> only has to implement the <code>calculateFoo()</code> method, but not the <code>footype</code> property.</p>\n\n<p>But I am not aware of a way to do this <em>lazily</em> so that the function is called only once. The reason is that extensions cannot add stored properties to a type.</p>\n\n<p>For sub<em>classes</em> of <code>NSObject</code> you can come around this problem with “associated objects,” but not for structs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:09:41.077",
"Id": "449509",
"Score": "0",
"body": "Yes, `footype` is calculated only, never set. So, just to be sure, to be able to use the `lazy` property, I need to use `mutating` in `var footype: Double { mutating get }` in the protocol?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:15:56.710",
"Id": "449510",
"Score": "1",
"body": "@Koen: Yes (unless you make Foo a “class-only” protocol: `protocol Foo: class {...}` and `Bar` a class instead of a struct)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:19:58.687",
"Id": "449513",
"Score": "0",
"body": "yes, it has to be a struct, due to other parts of my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:39:47.713",
"Id": "449515",
"Score": "0",
"body": "And the implementation of `calculateFoo()` is different for the various structs that conform to `Foo`, so they must all implement it for their specific case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T00:48:04.563",
"Id": "451725",
"Score": "0",
"body": "There is no need to wrap `calculateFoo()` call into closure. You can write `lazy var footype: Double = calculateFoo()`, and it will work as expected, `calculateFoo` will be called just once, and only when the variable is accessed for the first time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T10:09:02.013",
"Id": "451759",
"Score": "0",
"body": "@EgorKomarov: You are completely right, thanks!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:01:29.940",
"Id": "230654",
"ParentId": "230651",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230654",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T16:17:03.450",
"Id": "230651",
"Score": "3",
"Tags": [
"swift",
"lazy",
"protocols"
],
"Title": "Swift protocol with lazy property requirement"
}
|
230651
|
<p>I am currently "gracefully" handling HTTP server <code>net/http</code> shutdown which works perfectly fine (<em>I am not asking you to review server shutdown</em>). As seen in the code below the <code>context</code> is created <strong>first time</strong> directly in server package when I run the application. What I've done afterwards is (<em>this is the one I would like you to review please</em>), I've created a <code>context.Background()</code> <strong>before</strong> calling the server and pass it to server. Is this acceptable/feasible practise in Golang?</p>
<p><em>Why I want to create a <code>context</code> beforehand while everything is already working fine?</em></p>
<ul>
<li>It is because I need a few key-value pair in <code>context</code> so that I can use them throughout the application.</li>
</ul>
<p><strong>CURRENT IMPLEMENTATION WITH CONTEXT IN SERVER</strong></p>
<p><strong>cmd/auth/main.go</strong></p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"github.com/BentCoder/auth/internal/http"
)
func main() {
srv := http.NewServer(":8011", 10)
srv.Start()
}
</code></pre>
<p><strong>internal/http/server.go</strong></p>
<pre class="lang-golang prettyprint-override"><code>package http
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type Server struct {
http *http.Server
timeout int64
}
func NewServer(adr string, tim int64) Server {
return Server{
http: &http.Server{
Addr: adr,
},
timeout: tim,
}
}
func (srv *Server) Start() {
log.Infof("starting HTTP server")
idle := make(chan struct{})
go shutdown(srv.http, idle, srv.timeout)
if err := srv.http.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("failed to start/close HTTP server [%v]", err)
}
<-idle
log.Info("shutdown HTTP server")
}
func shutdown(srv *http.Server, idle chan<- struct{}, tim int64) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
<-sig
log.Infof("shutting down HTTP server in '%d' sec", tim)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(tim)*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("failed to shutdown HTTP server [%v]", err)
}
close(idle)
}
</code></pre>
<p><strong>output</strong></p>
<pre class="lang-bsh prettyprint-override"><code>INFO[0000] starting HTTP server source="server.go:42"
^C
INFO[0004] shutting down HTTP server in '10' sec source="server.go:82"
INFO[0004] shutdown HTTP server source="server.go:54"
</code></pre>
<p><strong>THIS IS WHAT I DECIDED TO DO</strong></p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"context"
"github.com/BentCoder/auth/internal/http"
)
func main() {
ctx := context.WithValue(context.Background(), "SomeKey", "SomeVal")
srv := http.NewServer(":8011", 10)
srv.Start(ctx)
}
</code></pre>
<p>And update server package (the relevant bit) as seen below.</p>
<pre class="lang-golang prettyprint-override"><code>func shutdown(ctx context.Context, .....
...
ctx, cancel := context.WithTimeout(ctx, time.Duration(tim)*time.Second)
...
}
</code></pre>
|
[] |
[
{
"body": "<p>You've actually improved the design, because now unit tests can inject their own context and thus the <code>shutdown()</code> becomes testable. Pure gold.</p>\n\n<p>But your stated reasons make me wary. I'd pass a parameter (e.g. struct) to <code>Start()</code> or <code>NewServer()</code> There aren't many good uses of <code>WithValue</code> that make your code more readable and neater.</p>\n\n<p>Also docs for WithValue warn that \"The provided <code>key</code> must be comparable and should not be of type <code>string</code> or any other built-in type to avoid collisions between packages using context.\" So that's a big problem with your example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-20T18:13:28.583",
"Id": "231047",
"ParentId": "230655",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:07:51.543",
"Id": "230655",
"Score": "4",
"Tags": [
"go"
],
"Title": "Passing around context.Context in Golang"
}
|
230655
|
<p>I have implemented the A-Star path finding algorithm for a 2D grid. The function returns a list of positions of an acceptable path.</p>
<p>main.cpp :</p>
<pre><code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <boost/circular_buffer.hpp>
#include <cstdlib>
#include <ctime>
#include <motion_planner.h>
using namespace std;
//extern int max_step_number;
/* **********************************************************
* Test Input
* Enter max_step_number for the random planner: 25
* Enter start positon: e.g: 2 0
* 2 0
* Enter goal positon: e.g: 5 5
* 5 5
* Enter world size: e.g: 6 6
* 6 6
* 0 0 1 0 0 0
0 0 1 0 0 0
0 0 0 0 1 0
0 0 0 0 1 0
1 0 1 1 1 0
0 0 0 0 0 0
* *************************************************************/
int main(void)
{
motion_planner mp;
int x,y,gx,gy,r,c;
int val;
//string vals;
cout<<"Enter max_step_number for the random planner: ";
cin>> mp.max_step_number;
cout<<"\nEnter start positon: e.g: 2 1 \n";
cin>>x>>y;
cout<<"\nEnter goal positon: e.g: 5 4 \n";
cin>>gx>>gy;
cout<<"\nEnter world size: e.g: 6 6 \n";
cin>>r>>c;
pair<int,int> start = make_pair(x,y);
pair<int,int> goal = make_pair(gx,gy);
vector<vector<int> > world(r);
//vector<vector<Node> > grid(r);
for (int i = 0;i<r;i++)
{
for(int j = 0; j<c; j++)
{
cin>>val;
world[i].push_back(val);
}
}
//cout<< world[4][0]<<"haaaaa"<<endl;
//cout<< "Grid size"<< world.size()<<endl;
vector<pair<int,int> >resRan = mp.randPlan(world,start,goal);
//cout<<res.size()-1<<endl;
pair<int,int> out;
cout<< "Random Planner Path Traversed: (Showing position after start) "<<endl;
for(int i= 0; i< resRan.size(); i++)
{
pair<int,int> out = resRan[i];
cout<<out.first<<","<<out.second<<endl;
}
cout<< "\nOptimal Planner Path Traversed: (Showing position from start)"<<endl;
vector<pair<int,int> >resOpt = mp.optPlan(world,start,goal);
//pair<int,int> out;
for(int i=0; i < resOpt.size(); i++)
{
pair<int,int> out = resOpt[i];
cout<<out.first<<","<<out.second<<endl;
}
//cout<<world[4][5]<<endl;
//cout<<world.size();
return 0;
}
</code></pre>
<p>motion_planner.h ; there are two functions, one is a random path search and one for astar</p>
<pre><code>#ifndef MOTION_PLANNER_H
#define MOTION_PLANNER_H
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <boost/circular_buffer.hpp>
#include <cstdlib>
#include <ctime>
using namespace std;
class motion_planner{
public:
int max_step_number; //max steps after which random planner should stop
typedef boost::circular_buffer<pair<int,int> > circular_buffer;
/*
* Class for optimal planner (A* search). Each postion in the grid is a object of this class
* */
class Node
{
public:
int g= 0, h=0;
char val; //Char value in the grid
pair<int,int> pos;
Node *parent = 0;
Node(pair<int,int>nodePos,int value)
{
pos=nodePos;
val=value;
}
//Node() : parent( make_unique<Node>()) {}
int move_cost(Node other)
{
return 1;
}
pair<int,int> get_pos() const
{
return pos;
}
};
/*
* Custom Hasher for Class Node, to be used for Unordered_set.
* (Can even use priority_queues for storing the obejcts of class Node instead of hashset)
* */
struct NodeHasher
{
//template <typename T, typename U>
size_t
operator()( const Node &obj) const
{
pair<int,int> position;
position = obj.get_pos();
return 3* std::hash<int>()(position.first) + std::hash<int>()(position.second) ; //custom hasher key when we using pair
}
};
/*
* Custom Comparator for Class Node, to be used for Unordered_set
* */
struct NodeComparator
{
bool
operator()(const Node &obj1, const Node &obj2) const
{
if (obj1.get_pos() == obj2.get_pos())
return true;
return false;
}
};
/*
* Comparing the objects based on the f = h+g cost
* */
struct MinFValue
{
bool
operator() (const Node &obj1, const Node &obj2) const
{
return obj1.h+obj1.g < obj2.h+obj2.g;
}
}minObj;
/*
* Return type for the random planner (not using it currently)
* */
struct returnType
{
bool t;
vector<pair<int,int> > randPath;
};
vector<bool> foundInVisited (pair<int,int> nod, circular_buffer cb);
vector<pair<int,int> > adjRandom(pair<int,int> node, vector<vector<int > > &world, circular_buffer visited);
vector<pair<int,int> > randPlan(vector<vector<int> > &grid, pair<int,int> start, pair<int,int> goal);
int heuris(pair<int,int> goal, pair<int,int> node);
vector<pair<int,int> > adjAstar(pair<int,int> node, vector<vector<Node> > &world);
vector<Node> aStar(vector<vector<Node> > &grid, pair<int,int> start, pair<int,int> goal);
vector<pair<int,int> > optPlan(vector<vector<int> > &world, pair<int,int> start, pair<int,int> goal);
};
#endif
</code></pre>
<p>motion_planner.cpp</p>
<pre><code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <boost/circular_buffer.hpp>
#include <cstdlib>
#include <ctime>
#include <motion_planner.h>
using namespace std;
/* ***************************************************************************************************************************
* Function to check which of the 4 adjacent cells of the current cell are in the visited list
*
* @output: returns a boolean vector of size 4
* @input: current cell, buffer of visited nodes( size- square root of max_step_number)
* ***************************************************************************************************************************/
vector<bool> motion_planner::foundInVisited (pair<int,int> nod, circular_buffer cb)
{
vector<bool> boolAdj {true, true, true, true};
int x = nod.first;
int y = nod.second;
for (int i = 0 ; i< cb.size(); i++)
{
//int r = cb[i].first(), c = cb[i].second();
if(make_pair(x+1,y) == cb[i])
{
boolAdj[0] = false ;
}
if(make_pair(x,y+1) == cb[i])
{
boolAdj[1] = false;
}
if(make_pair(x-1,y) == cb[i])
{
boolAdj[2] = false;
}
if(make_pair(x,y-1) == cb[i])
{
boolAdj[3] = false;
}
}
return boolAdj;
}
/* ***************************************************************************************************************************
* Function to find which adjacent nodes of the current nodes are passable
*
* @output: vector of passable nodes
* @input: current node, the world state, buffer of visited nodes( size- square root of max_step_number)
* ***************************************************************************************************************************/
vector<pair<int,int> > motion_planner::adjRandom(pair<int,int> node, vector<vector<int > > &world, circular_buffer visited)
{
vector<pair<int,int> > resNodes;
//fromVisited = foundInVisited (node, visited);
int x = node.first, y = node.second;
bool t1 = false,t2=false,t3=false,t4 = false;
vector<bool> resAdj = foundInVisited(node, visited);
if ( (x+1) <= world.size()-1 && world[x+1][y] != 1 )
{
t1 = true;
if(resAdj[0])
resNodes.push_back(make_pair(x+1,y));
}
if ( (y+1) <= world[0].size()-1 && world[x][y+1] != 1 )
{
t2 = true;
if(resAdj[1])
resNodes.push_back(make_pair(x,y+1));
}
if ( (x-1) >= 0 && world[x-1][y] != 1 )
{
t3 = true;
if(resAdj[2])
resNodes.push_back(make_pair(x-1,y));
}
if ( (y-1) >= 0 && world[x][y-1] != 1 )
{
t4 = true;
if(resAdj[3])
resNodes.push_back(make_pair(x,y-1));
}
if(t1 == false && t2 ==t1 && t3 == t2 && t4 ==t1)
{
return resNodes;
}
else if (resNodes.size()==0)
{
vector<pair<int,int> > ts;
if(t1 == true) ts.push_back(make_pair(x+1,y));
if(t2 == true) ts.push_back(make_pair(x,y+1));
if(t3 == true) ts.push_back(make_pair(x-1,y));
if(t4 == true) ts.push_back(make_pair(x,y-1));
random_shuffle(ts.begin(),ts.end());
resNodes.push_back(*ts.begin());
return resNodes;
}
else
return resNodes;
}
/* *************************************************************************************************************************
* Function implements random planner logic, uses a circular buffer to store the last visited nodes, random_shuffle to select next node from the vector of adjacent passable nodes, random)shuffle has no bias as opposed to rand, and size of this vector is always less than or equal to 4, time efficient. For a bigger vector, a random generator should be created to get a random element.
*
* @output: vector of nodes traversed (size max_step_number or less)
* @input: world state, start state, goal state
* ************************************************************************************************************************/
vector<pair<int,int> > motion_planner::randPlan(vector<vector<int> > &grid, pair<int,int> start, pair<int,int> goal)
{
vector<pair<int,int> > path;
unsigned int squarert = abs(sqrt(max_step_number));
circular_buffer visited(squarert);
int sx=start.first, sy=start.second, gx=goal.first, gy=goal.second;
int minF = 10000;
pair<int,int> current = start;
//path.push_back(current);
visited.push_back(current);
vector<pair<int,int> > childNodes;
srand ( unsigned ( std::time(0) ) );
if (current == goal)
{
return {current};
}
while(max_step_number-- > 0)
{
if (current == goal)
{
cout<< "\n Path found with random planner!!!\n"<<endl;
return path;
}
childNodes = adjRandom(current,grid,visited);
random_shuffle(childNodes.begin(),childNodes.end());
current = *childNodes.begin();
visited.push_back(current);
path.push_back(current);
}
if(path[path.size()-1]!=goal) cout<<"\nGoal not reached using Random Planner(Max steps reached)!!!\n"<<endl;
return path;
}
/* *************************************************************************************************************************
* Function calculates heuristic of each node. Euclidean distance is used to calcualte the cost from current node to goal
*
* @output: integer value heuristic
* @input: goal state, current state
* ************************************************************************************************************************/
int motion_planner::heuris(pair<int,int> goal, pair<int,int> node)
{
int h = abs(goal.first-node.first) + abs(goal.second-node.second);
return h;
}
/* *************************************************************************************************************************
* Function returns the adjacent node positions of the current node that are passable for the A* search
*
* @output: vector of pairs(positions) of adjacent passable nodes
* @input: current position, world state
* ************************************************************************************************************************/
vector<pair<int,int> > motion_planner::adjAstar(pair<int,int> node, vector<vector<motion_planner::Node> > &world)
{
vector<pair<int,int> > adjNodes;
int x = node.first, y = node.second;
if ( (x+1) <= world.size()-1 && world[x+1][y].val != 1)
{
adjNodes.push_back(make_pair(x+1,y));
}
if ( (y+1) <= world[0].size()-1 && world[x][y+1].val != 1)
{
adjNodes.push_back(make_pair(x,y+1));
}
if ( (x-1) >= 0 && world[x-1][y].val != 1 )
{
adjNodes.push_back(make_pair(x-1,y));
}
if ( (y-1) >= 0 && world[x][y-1].val != 1 )
{
adjNodes.push_back(make_pair(x,y-1));
}
return adjNodes;
}
/* *************************************************************************************************************************
* Function implements A* search logic, returns a vector of Node objects that are traversed.
*
* @output: vector of nodes traversed
* @input: 2D list of Node objects, start state, goal state
* ************************************************************************************************************************/
vector<motion_planner::Node> motion_planner::aStar(vector<vector<motion_planner::Node> > &grid, pair<int,int> start, pair<int,int> goal)
{
int sx=start.first, sy=start.second, gx=goal.first, gy=goal.second;
int minF = 10000;
unordered_set<motion_planner::Node,motion_planner::NodeHasher,motion_planner::NodeComparator> openList, closedList;
//cout<< "grid size"<< grid[0].size()<<endl;
openList.insert(grid[sx][sy]);
//cout<<gx<<" "<<gy<<endl;
vector<motion_planner::Node > path;
int hihi=0;
int i =0;
while (!openList.empty())
{
i++;
//cout<<"its here"<<endl;
Node current = *min_element(openList.begin(), openList.end(), minObj);
/*cout<<i<<endl;
for (Node x : openList)
{
cout<<"h="<< x.h<< "g=" <<x.g << " "<< x.get_pos().first << "," << x.get_pos().second << "\t";
}
cout<< endl;
cout<< current.get_pos().first<<" "<<current.get_pos().second<<endl; */
int currX=current.get_pos().first, currY = current.get_pos().second;
if (current.get_pos() == goal)
{
//cout<<"here";
while(current.parent != NULL )
{
//cout<< current.get_pos().first<<" "<<current.get_pos().second<<endl;
path.push_back(current);
current = *current.parent;
}
path.push_back(current);
return path;
}
openList.erase(current);
closedList.insert(current);
//openList.erase(grid[currX][currY]);
for (pair<int,int> nod : adjAstar(current.pos,grid))
{
hihi++;
int r=nod.first, c = nod.second;
//auto searchCL = find(closedList.begin(),closedList.end(),nod);
auto searchCL = closedList.find(grid[r][c]);
if(searchCL!=closedList.end())
continue;
auto searchOL = openList.find(grid[r][c]);
if(searchOL!=openList.end())
{
//cout<<"hoorah"<<endl;
int n = current.g+current.move_cost(grid[r][c]);
if(grid[r][c].g>n)
{
grid[r][c].g=n;
int a = current.get_pos().first; int b = current.get_pos().second;
grid[r][c].parent = &grid[a][b];
}
}
else
{
grid[r][c].g = current.g + current.move_cost(grid[r][c]);
grid[r][c].h = heuris(goal,grid[r][c].pos);
//cout<<&current<<endl;
int a = current.get_pos().first; int b = current.get_pos().second;
//cout<<"a "<<grid[r][c].get_pos().first<<" b "<<grid[r][c].get_pos().second<<endl;
//cout<<"position of parent "<<grid[a][b].get_pos().first<<","<<grid[a][b].get_pos().second<<endl;
grid[r][c].parent = &grid[a][b];
openList.insert(grid[r][c]);
}
}
}
//cout<<hihi;
return path;
}
/* *************************************************************************************************************************
* Function to get the positions of the nodes returned by the function aStar.
*
* @output: vector of positions(pairs) of nodes traversed
* @input: world state, start state, goal state
* ************************************************************************************************************************/
vector<pair<int,int> > motion_planner::optPlan(vector<vector<int> > &world, pair<int,int> start, pair<int,int> goal)
{
vector<vector<motion_planner::Node> > grid(world.size());
vector<pair<int,int> > res;
vector<motion_planner::Node > path;
for (int i = 0; i<world.size() ; i++)
{
for(int j =0; j<world[0].size(); j++)
{
//Node* a = new Node(make_pair(i,j), world[i][j]);
motion_planner::Node a = motion_planner::Node(make_pair(i,j),world[i][j]);
grid[i].push_back(a);
}
}
path = motion_planner::aStar(grid,start,goal);
for(int i= path.size()-1; i>=0; i--)
{
res.push_back(path[i].get_pos());
}
return res;
}
</code></pre>
<p>I have a long way to go in learning C++ and there must be many areas in which this function could have been optimized, e.g. the data structures used, code practices, C++ tricks, memory management, etc. to name a few.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:26:00.840",
"Id": "449596",
"Score": "5",
"body": "I wonder how no-one addressed this in their answers: **do not use using namsepace std;** https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T12:01:16.877",
"Id": "449602",
"Score": "2",
"body": "Do not leave in commented code"
}
] |
[
{
"body": "<p>Just off the cuff, before I fully code review this, I would tell you:</p>\n\n<p>1) There are not enough comments. You add comments like this:</p>\n\n<pre><code>//string vals;\ncout<<\"Enter max_step_number for the random planner: \";\n</code></pre>\n\n<p>...these are obviously string vals, but what are these?</p>\n\n<pre><code>motion_planner mp;\nint x,y,gx,gy,r,c;\nint val;\n</code></pre>\n\n<p>2) You need to initialize your values.</p>\n\n<p>3) You need to have variable names that describe the function/purpose of the variable, i and j are fine for indexers, but outside of that one letter var names are a no-no.</p>\n\n<p>4) You are not checking the input of your std::cin and expecting the values to be convertible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T19:06:55.213",
"Id": "230661",
"ParentId": "230657",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>Euclidean distance is used to calcualte the cost from current node to goal</p>\n</blockquote>\n\n<p>The code implements Manhattan distance, so the comment is wrong, or perhaps the code is wrong, but in any case it doesn't match. You can use <a href=\"http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html\" rel=\"noreferrer\">this page</a> to review heuristics for grid worlds, I don't recommend Euclidean distance because it's either too optimistic (causing unnecessary node exploration) or even wrong (when the actual movement cost for a diagonal move is less than sqrt(2)).</p>\n\n<blockquote>\n <p><code>pair<int,int></code></p>\n</blockquote>\n\n<p>Not wrong but most of these are actually 2D coordinates, which has more meaning than just \"pair\", so you could make an alias or your own class.</p>\n\n<blockquote>\n <p><code>vector<pair<int,int> ></code></p>\n</blockquote>\n\n<p>The <code>>></code>-problem has been officially fixed since C++11 (compiler support predates the update of the standard) and you tagged this question C++14, so you don't need to do this. It's not wrong to continue doing it, just unnecessary.</p>\n\n<p><strong><code>unordered_set<..> openList</code>:</strong> <code>unordered_set</code> does not support finding the minimum element in a reasonable way. You can get it out anyway, but it will happen by brute force. It is a bit tricky to do this efficiently, because finding the minimum element and finding a given element (or finding the element based on coordinates) back in order to change its parent and G and F, both need to be supported.</p>\n\n<p>It can be done by maintaining a binary heap, and letting the nodes know their index in the heap, so that the node can be moved to its proper location in the heap after modifying its parent and G/F score. An unfortunate consequence of that construct is that it all needs to be manual, the standard library does have <code>pop_heap</code> and <code>push_heap</code> but those functions do not have any option to update some secondary data structure every time an element in the heap is moved to a different index.</p>\n\n<p>That's all a bit complicated, a sneaky alternative is keeping <em>only</em> a heap, and just re-inserting a node when its G and parent are changed, so that it will be popped off the heap <em>before</em> the other version of that node that is already in the heap. It can happen then that you pop a node off the Open List and that node has actually been already closed, just skip it. The downside is filling up the Open List with dead weight, also if you implement an other suggestion from further down (to limit the use of nodes to only the open list) then the additional coordinates-to-index-in-the-heap map needs to exist anyway, which defeats the point of this dirty trick.</p>\n\n<p>Repeatedly scanning the entire open list is a significant performance problem, easily leading to quadratic time complexity (in terms of number of nodes explored), though it depends on the actual exploration.</p>\n\n<p><strong><code>motion_planner::Node</code> everywhere:</strong> in so many places that multiple independent copies of the same node are in circulation, which is brittle - there are multiple places in the code where you had to take the coordinate of a node and then look it up back in the grid, to ensure you were referring to the \"right version\" of a node. Various things don't need to be a full <code>Node</code>. For example in the closed list, all you care about are the coordinates, but a <code>Node</code> is used. That then causes <code>Node</code> to have a comparison and hash written solely for the application of \"using <code>Node</code> in the closed list\", with odd semantics as a result. That could have been avoided, for example:</p>\n\n<ol>\n<li>Make the closed list be in terms of coordinates, or</li>\n<li>Put a boolean <code>closed</code> on the <code>Node</code> so you don't even need a closed list.</li>\n</ol>\n\n<p>But having a <code>vector<vector<motion_planner::Node> > grid</code> in the first place is a bit overkill. It meant you had to touch <em>every cell of the grid</em>, no matter how big the world or how small the area needed by the current query, so it does not scale well. That can be avoided:</p>\n\n<ul>\n<li>Let the node be a concept that only lives in the Open List.</li>\n<li>Create nodes on-demand, when generating the neighbours of the current node.</li>\n<li>Keep the parent-references in an <code>unordered_map<coordinate, coordinate></code>, allowing them to outlive the nodes.</li>\n<li>Rather than having nodes know their index-in-the-heap, maintain a separate map from coordinate to index-in-the-heap, which would be how a <code>Node</code> object is found back from a given coordinate.</li>\n</ul>\n\n<p><strong><code>vector<vector<..> ></code> for a grid:</strong> it gets the job done, but ideally there would be only one vector with everything in it, wrapped in a class that converts the indexing scheme. It's a bit of extra work compared to just letting nested vectors work it out, but you can save a level of indirection, and coalesce allocations, and also make the types more meaningful.</p>\n\n<p><strong>Credit where it's due:</strong> no list of neighbours in the node, that's good. A common mistake I see that typically goes hand in hand with making a grid of nodes, is turning that grid into a graph with explicit edges. That involves lots of set-up work, potentially-fragile pointer manipulation, and needlessly balloons the memory consumption, so it's good that you avoided that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:16:07.930",
"Id": "449615",
"Score": "0",
"body": "quick question - what was the `>>` problem you refer to? This is the first time I've come across it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:17:29.847",
"Id": "449616",
"Score": "0",
"body": "@Baldrickk back in the day, if you closed nested template instantiations with `>>`, it would be parsed as the right shift operator (and not as two separate closing angle brackets) and result in a parse error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:18:36.930",
"Id": "449618",
"Score": "0",
"body": "Oh, I was indeed aware of it. I just mentally parsed your comment as an issue with the `cin` statements... Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T20:14:29.150",
"Id": "230665",
"ParentId": "230657",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "230665",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T17:37:48.300",
"Id": "230657",
"Score": "8",
"Tags": [
"c++",
"algorithm",
"c++14",
"pathfinding",
"a-star"
],
"Title": "Implementation of A* algorithm in C++"
}
|
230657
|
<p><strong>Summary</strong>: This function generates a truth table for a boolean function of variable number of arguments. The name of the function passed and its arguments are deduced outside of the computable function scope. The returned value is a logical matrix with columns corresponding to function arguments and result.</p>
<pre><code>library(R.utils)
library(stringr)
truthTable <- function(func, valuesOnly = F) {
numArguments <- length(formals(func))
if(valuesOnly) {
values <- vector(length = 2^numArguments)
for (i in 1:(2^numArguments)) {
arguments <- rev(as.logical(intToBits(i-1)))[-(1:(32-numArguments))]
values[i] <- do.call(func, as.list(arguments))
}
return(values)
}
result <- matrix(nrow = 2^numArguments, ncol = numArguments + 1)
colnames(result) <- c(names(formals(func)), as.character(substitute(func)))
for (i in 1:(2^numArguments)) {
arguments <- rev(as.logical(intToBits(i-1)))[-(1:(32-numArguments))]
result[i, ] <- c(arguments, do.call(func, as.list(arguments)))
}
return(result)
}
</code></pre>
<p><strong>Example</strong>:</p>
<pre><code>majority <- function(a, b, c) {
return ((a & b) | (b & c) | (a & c))
}
truthTable(majority)
</code></pre>
<p><strong>Result</strong>:</p>
<pre><code> a b c majority
[1,] FALSE FALSE FALSE FALSE
[2,] FALSE FALSE TRUE FALSE
[3,] FALSE TRUE FALSE FALSE
[4,] FALSE TRUE TRUE TRUE
[5,] TRUE FALSE FALSE FALSE
[6,] TRUE FALSE TRUE TRUE
[7,] TRUE TRUE FALSE TRUE
[8,] TRUE TRUE TRUE TRUE
</code></pre>
<p><strong>Possible improvements</strong>:</p>
<ul>
<li>Faster conversion of numeric iterator to logical vector</li>
<li>Usage of <code>apply</code> instead of iterative computation</li>
</ul>
<p>What could be improved?</p>
<p>Any advice would be appreciated.</p>
|
[] |
[
{
"body": "<p>The main flaw that can be observed in your function is the presence of <strong>code duplication</strong>: expressions such as <code>2^numArguments</code> and <code>arguments <- rev(as.logical(intToBits(i-1)))[-(1:(32-numArguments))]</code> appear multiple times. Code duplication is generally bad, you could refactor so that each of them appears only one time.</p>\n\n<p>Other little things:</p>\n\n<ul>\n<li><code>R.utils</code> and <code>stringr</code> are loaded but never used.</li>\n<li>It's better to use <code>FALSE</code> instead of <code>F</code>.</li>\n</ul>\n\n<p>Here is an alternative solution using <code>expand.grid</code>:</p>\n\n<pre><code>truthTable2 <- function(func, valuesOnly = FALSE) {\n args <- formals(func)\n L <- setNames(rep(list(c(TRUE, FALSE)), length(args)), names(args))\n df <- expand.grid(L)\n result <- sapply(1:nrow(df), function(i) do.call(func, lapply(df, `[`, i)))\n # or result <- do.call(func, df) if func is vectorized\n if (valuesOnly) {\n unname(result)\n } else {\n df[[substitute(func)]] <- result\n as.matrix(df)\n }\n}\n\ntruthTable(majority)\n# a b c majority\n# [1,] TRUE TRUE TRUE TRUE\n# [2,] FALSE TRUE TRUE TRUE\n# [3,] TRUE FALSE TRUE TRUE\n# [4,] FALSE FALSE TRUE FALSE\n# [5,] TRUE TRUE FALSE TRUE\n# [6,] FALSE TRUE FALSE FALSE\n# [7,] TRUE FALSE FALSE FALSE\n# [8,] FALSE FALSE FALSE FALSE\n</code></pre>\n\n<hr>\n\n<p><strong>Benchmark:</strong></p>\n\n<pre><code>bench::mark(\n truthTable(majority),\n truthTable2(majority),\n check = FALSE\n)\n# # A tibble: 2 x 13\n# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time \n# <bch:expr> <bch:t> <bch:t> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <lis>\n# 1 truthTable(majority) 89.5us 97.4us 9634. 1.44KB 6.22 4650 3 483ms <lgl[~ <df[,~ <bch~\n# 2 truthTable2(majority) 189.6us 204.7us 4292. 0B 4.07 2110 2 492ms <lgl[~ <df[,~ <bch~\n# # ... with 1 more variable: gc <list>\n\n\nbigf <- function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q) TRUE\n\nbench::mark(\n truthTable(bigf),\n truthTable2(bigf),\n check = FALSE\n)\n# # A tibble: 2 x 13\n# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc \n# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list> \n# 1 truthTable(bigf) 2.13s 2.13s 0.469 64MB 5.63 1 12 2.13s <lgl[,18] [131,072 ~ <df[,3] [262,351~ <bch:t~ <tibble [1 x~\n# 2 truthTable2(bigf) 2.43s 2.43s 0.412 76.5MB 5.77 1 14 2.43s <lgl[,18] [131,072 ~ <df[,3] [262,218~ <bch:t~ <tibble [1 x~\n# Warning message:\n# Some expressions had a GC in every iteration; so filtering is disabled. \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T23:41:43.827",
"Id": "449537",
"Score": "0",
"body": "Indeed, code duplication should be avoided, and unused packager will be deleted (although may return as i find a faster way to convert the iterator from numeric to logical vector). Other than that, the suggested function (for illustrative purposed I will call it ```truthTable2``` is slower in my tests on a function with many (17, to be specific) arguments. It just returns ```TRUE``` all the time, so this is more of a test to see how fast the function handles the truth table generation. While ```truthTable``` takes 3 seconds to compute, the ```truthtable2``` takes 28."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T23:46:52.457",
"Id": "449538",
"Score": "0",
"body": "But I appreciate the clarity of the code and will try to implement the best practices to improve the function performance. But R is not all about performance, and I might need to code this function in C++ to gain a significant boost, might do it later"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T02:06:28.400",
"Id": "449540",
"Score": "2",
"body": "Assuming `func` is vectorized, like it is the case with your `majority`, replacing the `sapply` with a single call `result <- do.call(func, df)` should give it a good boost."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:42:58.693",
"Id": "449937",
"Score": "0",
"body": "@F.Rosty You're right, it was really slow! The main bottleneck was the `split` on dataframe rows, I've replaced it and now it's much faster. And as flodel said you can also use the fact that `func` is vectorized (if it is)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T22:54:30.210",
"Id": "230670",
"ParentId": "230662",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T19:20:52.290",
"Id": "230662",
"Score": "9",
"Tags": [
"r"
],
"Title": "Truth table generator for an arbitrary function"
}
|
230662
|
<p>I just started learning python a couple of weeks back from and like many others here, I too seek feedback on my simplified Blackjack game. I would like to know if the code could have been more elegant/ shorter and how. </p>
<p>PS - In my code, aces count only as 1 for the time being.</p>
<pre><code>class Bank():
def __init__(self,bet,balance):
self.bet = bet
self.balance = balance
def transaction_win(self):
self.balance+=self.bet*2
return self.balance
def transaction_loss(self):
self.balance-=self.bet
return self.balance
def introduction():
print('*'*40)
print('\nWelcome to Blackjack!')
print('This is a simplified version of the actual game')
print('Each card club is represented by its initial i.e. (H)earts,(S)pade,(D)iamond and (C)lub')
print('Player can only Hit or Stay. Double down, insurance, card splits are not a feature of the game')
print('Rest of the rules remain the same. Good luck and have fun!\n')
print('*'*40)
print('\n\n')
balance = int(input('What is the maximum total balance you can bet?'))
bet = int(input('What amount would you like to bet?'))
return balance,bet
class Deck():
def __init__(self,card_no):
self.card_no = card_no
def card_display(self):
if self.card_no in range(1,14):
card_house = 'H'
elif self.card_no in range(14,27):
card_house = 'S'
elif self.card_no in range(27,40):
card_house = 'D'
else:
card_house = 'C'
temp = self.card_no%13
if temp==0:
temp = 13
return str(temp)+card_house
def card_score(self):
temp = self.card_no%13
if temp in range(1,11):
card_score = 1
elif temp in range(11,13):
card_score = 10
else:
card_score = 10
return card_score
def start_game(player_hand,dealer_hand):
cards = list(range(1,53))
shuffle(cards)
print('Card deck shuffled!')
print('Dealing cards\n\n')
player_card = [cards.pop(),cards.pop()]
dealer_card = [cards.pop(),cards.pop()]
player_score = []
dealer_score = []
for (i,j) in zip(player_card,dealer_card):
temp1 = Deck(i)
temp2 = Deck(j)
player_hand.append(temp1.card_display())
player_score.append(temp1.card_score())
dealer_hand.append(temp2.card_display())
dealer_score.append(temp2.card_score())
return player_hand,dealer_hand,cards,player_score,dealer_score
def hand_score(player_score,dealer_score):
return sum(player_score),sum(dealer_score)
def display_hand(player_hand,dealer_hand,choice):
if choice == 1:
print('Dealer hand:',end=' ')
for i in dealer_hand[:-1]:
print(i,end=' ')
print('*')
else:
print('Dealer hand: '+' '.join(dealer_hand))
print('\n'*5)
print('Player hand: '+' '.join(player_hand))
def player_choice():
while True:
try:
choice = int(input('Do you want to Hit(1) or Stay(2)?'))
except:
print('Error! Not a numeral input or invalid numeral input. Please try again')
else:
if choice not in [1,2]:
print('Invalid numeral input. Please try again')
continue
else:
return choice
break
def win_check(player_total,dealer_total,bet,balance,choice):
temp = Bank(bet,balance)
if player_total == 21:
print('Congrats! You won!')
balance = temp.transaction_win()
return True,balance
elif dealer_total == 21 and choice == 2:
print('Sorry, you lost your bet')
balance = temp.transaction_loss()
return True,balance
elif player_total>21:
print('Bust! Sorry, you lost your bet')
balance = temp.transaction_loss()
return True,balance
elif dealer_total<21 and dealer_total>player_total and choice == 2:
print('Sorry, you lost your bet')
balance = temp.transaction_loss()
return True,balance
elif dealer_total>21 and choice == 2:
print('Congrats! You won!')
balance = temp.transaction_win()
return True,balance
else:
return False,balance
def play_again(balance):
wish = input('Do you wish to play again? (Y)es or (N)o?')
bet = 0
if 'y' in wish.lower():
answer = True
print('Available balance: {}'.format(balance))
while True:
try:
bet = int(input('how much would you like to bet?'))
except:
print('please give a numeric input')
else:
if balance-bet<0:
print('Please do not bet more than available balance. Try again')
continue
else:
break
elif 'n' in wish.lower():
answer = False
print('Thanks for playing. Your final balance is {}'.format(balance))
else:
clear_output()
print('Give proper input please')
play_again(balance)
return answer,bet
from random import shuffle
from IPython.display import clear_output
play_answer = True
balance,bet = introduction()
while balance>0 and play_answer == True:
choice = 1
winner_check = False
player_hand,dealer_hand,cards,player_score,dealer_score = start_game([],[])
player_total,dealer_total = hand_score(player_score,dealer_score)
display_hand(player_hand,dealer_hand,choice)
choice = player_choice()
while (choice == 1 or choice == 2) and winner_check == False:
card_drawn = cards.pop()
temp = Deck(card_drawn)
if choice == 1:
player_total+=temp.card_score()
player_hand.append(temp.card_display())
player_score.append(temp.card_score())
else:
dealer_total+=temp.card_score()
dealer_hand.append(temp.card_display())
dealer_score.append(temp.card_score())
clear_output()
display_hand(player_hand,dealer_hand,choice)
winner_check,balance = win_check(player_total,dealer_total,bet,balance,choice)
if winner_check==True:
break
elif winner_check == False and choice == 1:
choice = player_choice()
else:
pass
if balance == 0:
print('You are too poor to bet more. Better luck next time.')
break
else:
pass
play_answer,bet = play_again(balance)
del winner_check,player_hand,dealer_hand,cards,player_score,dealer_score,player_total,dealer_total,temp
</code></pre>
|
[] |
[
{
"body": "<p>I would be more mindful of the space that you have around operators. PEP8 recommends <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"nofollow noreferrer\">single spaces around operators unless you want to help distinguish different operator precedences</a>. I find, for example, <code>self.card_no%13</code> to read very poorly. It isn't easy to readily see that there's a <code>%</code> operator in there. It looks like it's a part of the name. I also think a line like <code>print('*'*40)</code> would be much clearer with spacing:</p>\n\n<pre><code>print('*' * 40)\n</code></pre>\n\n<hr>\n\n<p>In <code>introduction</code>, you're calling <code>int</code> on user input outside of a <code>try</code>. Making sure you're accounting for bad user input is important. You don't want to have the whole thing crash just because the user accidentally typed in <code>10a</code> instead of <code>10</code>.</p>\n\n<hr>\n\n<pre><code>if winner_check==True:\n break\nelif winner_check == False and choice == 1:\n choice = player_choice()\nelse:\n pass\n</code></pre>\n\n<p>This has a few notable things:</p>\n\n<ul>\n<li><p><code>== True</code> and <code>== False</code> are unnecessary. Just negate the condition or use the condition directly.</p></li>\n<li><p>In the <code>elif</code>, <code>check_winner</code> <em>must</em> be false. If it was true, the previous condition would have triggered.</p></li>\n<li><p>The <code>else</code> is useless. You do not need an <code>else</code> unless you need some code to run when all other conditions are false. You're just <code>pass</code>ing though, which is a no-op.</p></li>\n<li><p>Note the inconsistency of your spacing. Within two lines of each other, you have <code>winner_check==True</code> and <code>winner_check == False</code>. Even if you didn't want to follow PEP8, you should at least be consistent.</p></li>\n</ul>\n\n<p>I'd write this as:</p>\n\n<pre><code>if winner_check:\n break\n\nelif choice == 1:\n choice = player_choice()\n</code></pre>\n\n<hr>\n\n<p>At the bottom you have:</p>\n\n<pre><code> del winner_check,player_hand,dealer_hand,cards,player_score,dealer_score,player_total,dealer_total,temp\n</code></pre>\n\n<p>I'm not sure why though. You are not required to delete references when you're done with them. That data will be freed when it goes out of scope. You only need to use <code>del</code> if for some reason you really don't want a variable to be in scope later on, within the same scope.</p>\n\n<hr>\n\n<p>I say this a lot, but don't write a plain <code>except:</code> unless you have a very good reason (like you want to do a catch-all to log errors, and can handle arbitrary catastrophic failure):</p>\n\n<pre><code>try:\n choice = int(input('Do you want to Hit(1) or Stay(2)?'))\nexcept:\n . . .\n</code></pre>\n\n<p>You're using the <code>try</code> to catch a <code>ValueError</code> from <code>int</code>, so that's what you should be catching:</p>\n\n<pre><code>try:\n choice = int(input('Do you want to Hit(1) or Stay(2)?'))\nexcept ValueError:\n . . .\n</code></pre>\n\n<p>You don't want to accidentally catch an error that was caused by a programming error.</p>\n\n<hr>\n\n<p>On the subject of spacing, look at <code>win_check</code>. It's one giant block of text. Not only are you missing spaces around the operators (including <code>,</code>), you're missing empty lines. I would write this function as:</p>\n\n<pre><code>def win_check(player_total, dealer_total, bet, balance, choice):\n temp = Bank(bet, balance)\n\n if player_total == 21:\n print('Congrats! You won!')\n balance = temp.transaction_win()\n return True, balance\n\n elif dealer_total == 21 and choice == 2:\n print('Sorry, you lost your bet')\n balance = temp.transaction_loss()\n return True, balance\n\n elif player_total > 21:\n print('Bust! Sorry, you lost your bet')\n balance = temp.transaction_loss()\n return True, balance\n\n elif dealer_total < 21 and dealer_total > player_total and choice == 2:\n print('Sorry, you lost your bet')\n balance = temp.transaction_loss()\n return True, balance\n\n elif dealer_total > 21 and choice == 2:\n print('Congrats! You won!')\n balance = temp.transaction_win()\n return True, balance\n\n else:\n return False, balance\n</code></pre>\n\n<p>Yes, this is much bulkier. It has breathing room though for your eyes to rest at while reading. I found that my eyes kept losing their place while scanning over the function. There weren't any good \"landmarks\" to reference.</p>\n\n<p>Also note how you repeatedly return <code>True, balance</code>. I'm drawing a blank at the moment, but there's almost definitely a clean way of reducing that redundancy.</p>\n\n<hr>\n\n<p>I question the need for the <code>Bank</code> class. You only ever use it once inside of <code>win_check</code>. Are you really gaining anything from using them? Why not just subtract from the <code>balance</code> that was passed it? Needlessly wrapping code in a class just muddies its purpose. If all you need to do is add or subtract a number, just use <code>+</code> or <code>-</code>.</p>\n\n<p>It may be worth it if you passed the <code>Bank</code> object around instead of using it solely in the one function. That would only make sense though if the <code>bet</code> never changed.</p>\n\n<hr>\n\n<p>All imports should be at the very top unless you have a good reason to do otherwise (like you're doing importing in a <code>try</code> because you aren't sure what modules are available.</p>\n\n<hr>\n\n<p>This isn't at all a real concern, but I'll just mention that in:</p>\n\n<pre><code>if choice not in [1,2]:\n</code></pre>\n\n<p>The <code>[1, 2]</code> should really be a set. It won't make any real difference here, but it's a good habit to get into. Use the correct structure for the job. Just change it to <code>{1, 2}</code>.</p>\n\n<hr>\n\n<p>Python 3 has <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\">f-strings</a> that make string interpolation easier. Instead of writing:</p>\n\n<pre><code>'Available balance: {}'.format(balance)\n</code></pre>\n\n<p>Write:</p>\n\n<pre><code>f'Available balance: {balance}' # Note the f\n</code></pre>\n\n<p>That reads much nicer.</p>\n\n<hr>\n\n<hr>\n\n<p>I don't think I can justify avoiding going downstairs for Thanksgiving any longer .</p>\n\n<p>Good luck and happy (early) Thanksgiving.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T05:14:17.987",
"Id": "449553",
"Score": "0",
"body": "Thank you for the feedback. \n\nI am aware of the spacing and formatting issue. I do try to make the code more readable but since I am just starting to code again after a couple of years, it's taking some time. \n\nAs for the else statement in the winner_check block, I initially did not have it there since it is unnecessary. However, the code would not compile and would get stuck. So I thought maybe it expects an else to be there. Could that be the case? FYI I use Jupyter notebooks.\n\nHope you had a great Thanksgiving :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T05:17:32.737",
"Id": "449554",
"Score": "0",
"body": "@DigvijayRawat A missing `else` should never cause an error. At worst it would cause a linter warning. I can't see why a warning would happen there though. I'd have to see the error message to be able to say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T05:26:51.167",
"Id": "449555",
"Score": "0",
"body": "There would not be a warning or an error, the code would just get stuck on that statement. Sometimes the Jupyter kernels also bug out, I will check again."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T23:41:24.837",
"Id": "230673",
"ParentId": "230668",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T21:21:11.010",
"Id": "230668",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"playing-cards"
],
"Title": "Simplified Blackjack in Python"
}
|
230668
|
<p>This script sends and receives text messages and logs responses in a google sheet. Demo Gif here: <a href="https://github.com/RyGuy96/HealthTracker" rel="noreferrer">https://github.com/RyGuy96/HealthTracker</a>.</p>
<p>I'm a self-taught beginner coder just starting my formal education in college. I've never had an experienced programmer look over my work; it was suggested to me that I needed to start building my professional profile. I'd be very grateful if someone would look through this script and:</p>
<ol>
<li>Tell me if there are any glaring syntactical errors or best practices I've ignored.</li>
<li>Suggest any obvious ways it might be improved in terms of readability or speed.</li>
</ol>
<p>Thank you, I really do appreciate any and all advice! This is my first post here - if there something I've missed in the guidelines please let me know.</p>
<pre><code>#!/usr/bin/env python
"""receiver.py: Receives an sms message to a specifind number; parses and saves data in a Google Spreadsheet."""
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
import gspread
import re
import datetime
import time
from twilio.rest import Client
from oauth2client.service_account import ServiceAccountCredentials
import pytz
def sms_sender(message_text: str, recipient_num: str) -> None:
"""Define credentials for Twilio API sms."""
# Find these values at https://twilio.com/user/account (note that this is not a secure method)
account_sid = "YOUR_SID"
auth_token = "YOUR_AUTH_TOKEN"
client = Client(account_sid, auth_token)
message = client.api.account.messages.create(to= recipient_num,
from_="YOUR_TWILIO_NUMBER",
body= message_text)
def open_spreadsheet() -> object:
"""Authorize Google Drive access and return spreadsheet reference."""
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('JSON_FILE', scope)
gc = gspread.authorize(credentials)
wks_health = gc.open("Health Tracker").sheet1
return wks_health
def get_date() -> datetime:
utc_now = pytz.utc.localize(datetime.datetime.utcnow())
return datetime.datetime.strftime(utc_now.astimezone(pytz.timezone("America/Chicago")), '%Y-%m-%d')
def parse_sms(sms_reply: str) -> dict:
"""Return single dictionary of relevant values in sms."""
# ratings
ratings = re.compile(r"\b\d+\b")
rating_vals = (ratings.findall(sms_reply)[:5])
# added meds
add = re.compile(r"\+(.*?\))")
add_meds = add.findall(sms_reply)
# removed meds
remove = re.compile(r"\-(.*?\))")
remove_meds = remove.findall(sms_reply)
# notes
note = re.compile(r"Note\((.*?)\)", flags=re.IGNORECASE)
add_note = [] if not note.findall(sms_reply) else note.findall(sms_reply)[0]
# help
helpme_variants = ["help me", "helpme", "help-me"]
display_help = any([re.findall(i, sms_reply, flags=re.IGNORECASE) for i in helpme_variants])
# see meds
med_variants = ["seeMeds", "see-meds", "see meds"]
display_meds = any([re.findall(i, sms_reply, flags=re.IGNORECASE) for i in med_variants])
parsed_response = {"ratings": rating_vals, "add meds": add_meds, "remove meds": remove_meds, "notes": add_note,
"display help": display_help, "display meds": display_meds}
return parsed_response
def get_current_meds() -> str:
wks_health = open_spreadsheet()
time.sleep(4)
return wks_health.acell('G2').value.strip('][').split(', ')
def validate_sms(parsed_response: dict) -> str:
"""Check sms and return 'Valid' or one or more error messages to be sent to user."""
invalid_responses = []
try:
assert len(parsed_response["ratings"]) == 5
except AssertionError:
invalid_responses.append("Invalid number of ratings (there should be five)")
current_meds = get_current_meds()
try:
for med in parsed_response["remove meds"]:
assert med in current_meds
except AssertionError:
invalid_responses.append("Med to remove not found, see your meds by replying 'see-meds'")
try:
for med in parsed_response["add meds"]:
assert med not in current_meds
except AssertionError:
invalid_responses.append("Med to be added already listed, see your meds by replying 'see-meds'")
finally:
if invalid_responses:
return ", ".join(invalid_responses)
else:
return "Valid"
def record_sms(parsed_response: dict) -> None:
"""Log sms responses in Google Sheets."""
note = parsed_response["notes"]
remove = parsed_response["remove meds"]
add = parsed_response["add meds"]
current_meds = get_current_meds()
revised_med_list = [med for med in current_meds if med not in remove] + add
revised_med_list_formated = str(revised_med_list).replace("\'", "")
line = [get_date()] + parsed_response["ratings"] + [revised_med_list_formated]
line.append(note if note else "")
wks_health = open_spreadsheet()
wks_health.insert_row(line, value_input_option='USER_ENTERED', index=2)
def help_message() -> str:
# change symptoms as you see fit - some refactoring will be required if you you want to track more or less than five
message = "Respond to messages with: " \
"\n1. Hours slept " \
"\n2. Stress level (1-9) " \
"\n3. Joints (1-9) " \
"\n4. Energy (1-9) " \
"\n5. Mood (1-9) " \
"\n6. Add a note with NOTE(YOUR NOTE)* " \
"\n7. Add a med with +MEDNAME(DOSE)* " \
"\n8. Remove a med with -MEDNAME(DOSE)* " \
"\n9. See all meds with 'see-meds'* " \
"\n10. See this menu with 'help-me'*" \
"\n*Optional values in response"
return message
def see_meds_message() -> str:
message = "Your current meds are: " + str(get_current_meds())
return message
app = Flask(__name__)
@app.route("/sms", methods=['GET', 'POST'])
def main() -> str:
"""Listen for incoming sms and log content or reply with one or more error messages."""
from_body = request.values.get('Body', None)
resp = []
while from_body is not None:
try:
sms = parse_sms(from_body)
except:
resp.append("issue parsing")
break
try:
if sms['display help'] == True:
resp.append(help_message())
break
except:
resp.append("issue with help message")
break
try:
if sms['display meds'] == True:
resp.append(see_meds_message())
break
except:
resp.append("issue with showing meds")
break
try:
validation_val = validate_sms(sms)
except:
resp.append("issue validating")
break
try:
if validation_val == "Valid":
record_sms(sms)
resp.append("Response recorded!")
break
except:
resp.append("issue logging valid sms")
break
try:
if validation_val != "Valid":
resp.append(validation_val)
break
except:
resp.append("issue logging invalid sms")
break
mess= MessagingResponse()
mess.message(str(", ".join(resp)))
return str(mess)
if __name__ == "__main__":
app.run(debug=True)
</code></pre>
|
[] |
[
{
"body": "<h2>Regex compilation</h2>\n\n<p>Your code here:</p>\n\n<pre><code># ratings\nratings = re.compile(r\"\\b\\d+\\b\")\nrating_vals = (ratings.findall(sms_reply)[:5])\n\n# added meds\nadd = re.compile(r\"\\+(.*?\\))\")\nadd_meds = add.findall(sms_reply)\n\n# removed meds\nremove = re.compile(r\"\\-(.*?\\))\")\nremove_meds = remove.findall(sms_reply)\n</code></pre>\n\n<p>gets only halfway to a good idea. It is useful to separate regex compilation from regex execution, but only if the compiled regexes are persisted. You can put them as constants in global scope. Then the compilation cost is only paid once.</p>\n\n<h2>Help me</h2>\n\n<pre><code>helpme_variants = [\"help me\", \"helpme\", \"help-me\"]\ndisplay_help = any([re.findall(i, sms_reply, flags=re.IGNORECASE) for i in helpme_variants])\n</code></pre>\n\n<p>First of all: <code>any</code> doesn't require a list; you should be passing the generator to <code>any</code> directly.</p>\n\n<p>Beyond that: you don't need \"variants\" or a generator at all; you can do this with another regex:</p>\n\n<pre><code>display_help_re = re.compile(r'help[ -]?me', flags=re.IGNORECASE)\n\n# ...\n\ndisplay_help = display_help_re.search(sms_reply) is not None\n</code></pre>\n\n<p>The same is true of your <code>med_variants</code>.</p>\n\n<h2>Waiting for...?</h2>\n\n<pre><code>time.sleep(4)\n</code></pre>\n\n<p>Why is this here? It's spooky. At the very least, drop a comment. More likely is that you should attempt some manner of polling if possible to detect when the given condition is met.</p>\n\n<h2>Magic values</h2>\n\n<p><code>'G2'</code> is a magic value. At the least, it should be put into a named constant. More likely is that you should be making a named range in your spreadsheet and using that range, if this is at all possible.</p>\n\n<p>5 is also a magic value here:</p>\n\n<pre><code> assert len(parsed_response[\"ratings\"]) == 5\n</code></pre>\n\n<h2>Logic by exception</h2>\n\n<p>This:</p>\n\n<pre><code>try:\n for med in parsed_response[\"remove meds\"]:\n assert med in current_meds\nexcept AssertionError:\n invalid_responses.append(\"Med to remove not found, see your meds by replying 'see-meds'\")\n</code></pre>\n\n<p>is awkward and not necessary. Just do the check yourself, and use a <code>set</code> instead:</p>\n\n<pre><code>parsed_meds = set(parsed_response['remove_meds'])\nfor missing_med in parsed_meds - current_meds:\n invalid_responses.append(f'Med to remove \"{missing_med} not found; see your meds by replying \"see-meds\"')\n</code></pre>\n\n<h2>Character escapes</h2>\n\n<pre><code>\"\\'\"\n</code></pre>\n\n<p>does not need an escape backslash.</p>\n\n<h2>String continuation</h2>\n\n<p>Rather than using backslashes here:</p>\n\n<pre><code>message = \"Respond to messages with: \" \\\n \"\\n1. Hours slept \" \\\n \"\\n2. Stress level (1-9) \" \\\n \"\\n3. Joints (1-9) \" \\\n \"\\n4. Energy (1-9) \" \\\n \"\\n5. Mood (1-9) \" \\\n \"\\n6. Add a note with NOTE(YOUR NOTE)* \" \\\n \"\\n7. Add a med with +MEDNAME(DOSE)* \" \\\n \"\\n8. Remove a med with -MEDNAME(DOSE)* \" \\\n \"\\n9. See all meds with 'see-meds'* \" \\\n \"\\n10. See this menu with 'help-me'*\" \\\n \"\\n*Optional values in response\"\n</code></pre>\n\n<p>Put the whole thing in parens and drop the backslashes.</p>\n\n<h2>f-strings</h2>\n\n<pre><code>def see_meds_message() -> str:\n message = \"Your current meds are: \" + str(get_current_meds())\n return message\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def see_meds_message() -> str:\n return f'Your current meds are: {get_current_meds()}'\n</code></pre>\n\n<h2>Implicit <code>None</code></h2>\n\n<p>Drop the <code>, None</code> from this:</p>\n\n<pre><code>from_body = request.values.get('Body', None)\n</code></pre>\n\n<p>Because that's already the default for <code>get</code>.</p>\n\n<h2>Boolean comparison</h2>\n\n<pre><code> if sms['display help'] == True:\n</code></pre>\n\n<p>should simply be</p>\n\n<pre><code> if sms['display help']:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T17:52:34.933",
"Id": "449799",
"Score": "1",
"body": "You are a wizard, thank you so much Reinderien. The \"magic\" values 5 and G2 are used in multiple functions. I assume you would declare a function that returns those Constants? e.g. `def NUM_OF_RATINGS():\n return 5` and `def MEDS_CELL():\n return chr(ord('a') + 1 + NUM_OF_RATINGS()) + \"2\"`? Would you group both the constant functions as methods in a constant class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T19:54:29.787",
"Id": "449809",
"Score": "1",
"body": "Nah; it's easier just to declare a globally-scoped constant variable, `NUM_OF_RATINGS = 5`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:08:41.177",
"Id": "230719",
"ParentId": "230671",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230719",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T23:12:07.347",
"Id": "230671",
"Score": "5",
"Tags": [
"python",
"beginner"
],
"Title": "Log Text Messages In Google Sheets"
}
|
230671
|
<p>I'd like to receive a CR for the following command-line program options' initializing using <code>boost::program_options</code>. I'd like to know if there is a better way of doing this using <code>boost::program_options</code> or using another available library/code:</p>
<pre><code>#include <iostream>
#include <boost/program_options.hpp>
using namespace std;
namespace po = boost::program_options;
int main(int ac, char* av[]) {
/// Command line options initialize
po::options_description visible_desc("Usage: program [options] [path/]logger_filename");
po::options_description full_desc;
po::positional_options_description pd;
bool verbose, anomaly_detection, analyze_activity;
string normal_login_word;
string log_file_path;
string week_start_day;
auto generic_group = po::options_description("Generic options");
generic_group.add_options()
("help,h", "produce help message")
("verbose", po::value<bool>(&verbose)->default_value(false), "Show detailed times of login.")
;
auto calender_group = po::options_description("Calender options");
calender_group.add_options()
("week-start-day,d", po::value<string>(&week_start_day)->default_value("Monday"), "Week starting day ('--week-start-day help' for a list).")
;
auto log_group = po::options_description("Logger options");
log_group.add_options()
;
auto hidden_options_group = po::options_description("Logger options");
hidden_options_group.add_options()
("log-path,l", po::value<string>(&log_file_path)->default_value("/home/sherlock/message_from_computer"), "Path to login/logout logger.")
;
auto anomalies_group = po::options_description("Mode options");
anomalies_group.add_options()
("analyze-log", po::value<bool>(&analyze_activity)->default_value(true), "Analyze activity - show activity times and summarise activity.")
("anomaly-detection", po::value<bool>(&anomaly_detection)->default_value(false), "Check for anomalies in logger.")
("normal-login-word", po::value<string>(&normal_login_word)->default_value("login"), "For anomaly detector- word that should symbol a login line in login/logout logger (after '+' sign).")
;
pd.add("log-path", -1);
visible_desc.add(generic_group).add(calender_group).add(log_group).add(anomalies_group);
full_desc.add(generic_group).add(calender_group).add(log_group).add(anomalies_group).add(hidden_options_group);
/// Command line options applying
po::variables_map vm;
po::store(
po::command_line_parser(ac, av)
.options(full_desc)
.positional(pd)
.run(), vm);
po::notify(vm);
/*
... Analyze options ...
*/
return 0;
}
</code></pre>
<hr>
<p><h2>Update:</h2> after @pacmaninbw and @ALX23z CRs I created a new updated post: <a href="https://codereview.stackexchange.com/questions/230728/program-options-from-command-line-initialize-v2-after-cr">program options from command line initialize [v2 - after CR]</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T22:48:53.180",
"Id": "449706",
"Score": "1",
"body": "From our help pages, https://codereview.stackexchange.com/help/someone-answers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T22:54:17.597",
"Id": "449707",
"Score": "1",
"body": "You should have enough rep points now to ask questions in the 2nd Monitor, the code review chat room at https://chat.stackexchange.com/rooms/8595/the-2nd-monitor. You can also ask questions on Code Review Meta which you can reach from your profile page look at the upper right and click on the Meta User link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T23:50:59.687",
"Id": "449710",
"Score": "0",
"body": "@pacmaninbw thanks a lot! I would like to continue the CR of the updated version: https://codereview.stackexchange.com/questions/230728/program-options-from-command-line-initialize-v2-after-cr."
}
] |
[
{
"body": "<p>I tried boost::program_options but simply didn't like it.</p>\n\n<p>boost::program_options has the feature that certain options are additive or hidden - which is why their usage requires so much extra work (you have to specify each option you use and state how they are processed). If you are fine without these features, you can work with config files - <a href=\"https://en.wikipedia.org/wiki/INI_file\" rel=\"nofollow noreferrer\">*.ini format</a> - and simply read and store all option that the file has, no need for the whole mess in the main. It is not hard to implement a config file reader and Windows has built in functions for reading arguments from a .ini file.</p>\n\n<p>Also this way you can supply input parameters via an .ini file instead of command line, which is much more convenient if you have more than 5 parameters and I tend to have dozens in tests.</p>\n\n<p>In my case, I implemented a class ConfigFile that basically wraps a <code>std::map<string,string></code> whose keys are in format SECTION/NAME; with added functions for getting/setting int/double/string values as well as functionality for reading a whole ini file.</p>\n\n<p>In case you want to read a command line via the ConfigFile class: you can reinterpret cmd arguments and store them inside the ConfigFile class. string-based options simply store as is or optionally add a prefix-section. To support index based options you ought to provide a vector of strings to that interprets them.</p>\n\n<p>I don't know of any open-source library that implements something like this, though I didn't check for any. But it is easy to implement on your own. I might publish my implementation together with a couple of other utility features as an open-source but not now. So...</p>\n\n<p>Example of CMD parsing:</p>\n\n<pre><code>class CConfig\n{\npublic:\n // sKeys is used to store index based inputs of CMD\n void ParseCMD( int argc,\n const char** argv,\n std::vector<std::string> sKeys = {});\n\n std::string GetString(std::string key, std::string defaultValue);\n double GetDouble(std::string key, double defaultValue);\n int GetInt( std::string key, int defaultValue);\n\n void SetString(std::string key, std::string value);\n void SetDouble(std::string key, double value);\n void SetInt( std::string key, int value);\n\nprivate:\n std::mutex m_mutex;\n std::map<std::string, std::string> m_map;\n};\n\nvoid CConfig::ParseCMD( int argc,\n const char** argv,\n std::vector<std::string> sKeys)\n {\n std::lock_guard<std::mutex> g(m_mutex);\n size_t index = 0;\n for (int i = 1; i < argc; i++)\n {\n if (argv[i][0] != '-')\n {\n if (sKeys.size() <= index)\n {\n std::cout \"\\n[warning]: unassigned input parameters; total number of index-based input parameters is: \" << sKeys.size();\n continue;\n }\n\n m_map[sKeys[index]] = argv[i][0];\n continue;\n }\n\n if (i + 1 < argc && argv[i + 1][0] != '-')\n {\n m_map[argv[i]+1] = argv[i + 1];\n i++;\n }\n else\n {\n // simply defines this key with empty value\n m_map[argv[i]+1] = {};\n }\n }\n\n if (sKeys.size() > index)\n {\n // or add option for making it into an error and not just a warning print\n std::cout << \"\\n[warning]: not all index-based values were assigned\");\n }\n }\n\n// in main simply write:\n int main(int argc, const char* argv[])\n {\n CConfig config;\n config.ParseCMD(argc, argv, {/*list of strings for identification*/});\n ...\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T12:06:56.467",
"Id": "449604",
"Score": "0",
"body": "Hi, thanks for the advice. I am working on Linux OS, so the `.ini` files are extreme solution, because the terminal controls here. Although it is really good to know new options and ways, I would prefer to stick to the command-line options parser this time. But thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T22:56:42.047",
"Id": "449708",
"Score": "0",
"body": "I happen to agree with you about the boost::program_options so I voted for your answer, but this answer isn't really directed at the posters code and it should be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T06:45:53.210",
"Id": "449732",
"Score": "0",
"body": "@KorelK I mean, it can be used for CMD parsing as advised. Also added some code into the answer so you can see better what I meant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T06:47:40.603",
"Id": "449734",
"Score": "0",
"body": "@pacmaninbw Thx! OP asked if there are alternatives to `boost::program_options` which is what my answer is all about..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:37:21.547",
"Id": "230702",
"ParentId": "230672",
"Score": "2"
}
},
{
"body": "<p>In addition to the command line, there are at least two other methods to pass this information in: the <code>.ini</code> file was mentioned in another answer, environment variables are also an option. It's best not to force the user to type in too many options for the command line.</p>\n<h2>Avoid Using Namespace <code>std</code></h2>\n<p>If you are coding professionally, you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This <a href=\"//stackoverflow.com/q/1452721\">Stack Overflow question</a> discusses this in more detail.</p>\n<h2>Complexity</h2>\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>The code to set up the command line options should be in a function of its own. That function should probably call multiple functions to set up the options: one function for each of the option descriptions created.</p>\n<p>For a program that is going to be this complex it might be good to <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>#include <cstdlib></code> and use <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code></a> to make the code more self-documenting.</p>\n<h2>Variable Names and Declarations</h2>\n<p>The variable name <code>pd</code> is not very descriptive; someone who had to maintain the code would not be able to do it easily.</p>\n<p>For the same reason using <code>po</code> rather than <code>boost::program_options::</code> could make the program a lot harder to maintain. A maintainer would have to search through the program to find out what <code>po</code> is.</p>\n<p>When declaring variables such as <code>verbose</code>, <code>anomaly_detection</code> and <code>analyze_activity</code> it would be better to declare each variable on a separate line and possibly initialize them at the same time. This would make it easier to add more variables and to find the variable declarations.</p>\n<pre><code> bool verbose = true;\n bool anomaly_detection = false;\n bool analyze_activity = true;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:10:31.320",
"Id": "449695",
"Score": "0",
"body": "Why use `bool verbose = true; bool anomaly_detection = false; bool analyze_activity = true;` instead of separating them with commas, and set new line after each one of them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:12:07.327",
"Id": "449696",
"Score": "0",
"body": "And why should I initialize them, if they are getting set from the command line?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:23:03.927",
"Id": "449698",
"Score": "0",
"body": "@KorelK 1) because it's a good habit to initialize all the variables, it reduces bugs in the future. 2) You don't know that they will be set by the command line. 3) If you initialize them you don't need the `->default_value(true)` code, which will make your code cleaner and easier to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:26:48.853",
"Id": "449699",
"Score": "0",
"body": "The `default_value` do one more thing except initialize them, it lets the user know what is the default value if he won't set them. I think it's more user friendly this way, and both ways reach the habit target. And I know that they will be set from the cmd because I set them a `default_value` there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:27:15.547",
"Id": "449700",
"Score": "0",
"body": "New Question: to avoid a lot more code complexity when separating this part to smaller functions, would it be better to create a class with this target?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:27:19.917",
"Id": "449701",
"Score": "0",
"body": "@KorelK I explained about the first one in the review, but the reason is the code is very hard to maintain if there are multiple declarations on a line, it becomes harder to find the declaration and is harder to modify the line to either add or remove variables. One should always think about the other programmers that maintain the code, you may win several million dollars and quit your jon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T21:48:12.663",
"Id": "449703",
"Score": "0",
"body": "Can I edit my post to update the current state, so I can receive an updated CR?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T22:44:42.337",
"Id": "449705",
"Score": "1",
"body": "@KorelK Once you have a review you can't edit the question, but you can start a new question related to the old question. Make sure to provide a link back to the old question in the new question."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:10:17.147",
"Id": "230712",
"ParentId": "230672",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230712",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T23:18:49.357",
"Id": "230672",
"Score": "3",
"Tags": [
"c++",
"boost"
],
"Title": "program options from command line initialize"
}
|
230672
|
<p>I'm applying what I learned in statistics class to a program to calculate everything automatically, but encountered an unexpected 'mistake' in my code. I say unexpected, because it's not the first time I use malloc() to make a variable sized array and used reference from my previous work, but it goes off limits with the resulting size, when earlier, it worked fine as intended.</p>
<p>Can you tell me why the size ends up wrong?</p>
<p>I know something's wrong in the way I wrote it that should be corrected before I keep using this code, because it's exactly the same as before, and results should not change in a good code.</p>
<p>Code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int MakeSample();
int PrintSample();
int *sample;
int main(void)
{
MakeSample();
PrintSample();
}
int MakeSample()
{
int sampleSize;
int valueN;
printf("Enter size of your sample: ");
scanf("%d", &sampleSize);
sample = malloc(sampleSize * sizeof(int));
for (int i = 1; i <= sampleSize; i++)
{
printf("Enter value #%d: ", i);
scanf("%d", &valueN);
sample[i - 1] = valueN;
}
}
int PrintSample()
{
for (int k = 1; k <= sizeof(sample); k++)
{
printf("Value #%d: %d\n", k, sample[k - 1]);
}
}
</code></pre>
<p>The result is this for a sampleSize of 1:</p>
<pre><code>Value #1: 1
Value #2: 0
Value #3: 0
Value #4: 0
Value #5: 0
Value #6: 0
Value #7: 133057
Value #8: 0
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:45:25.643",
"Id": "449600",
"Score": "1",
"body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:18:28.833",
"Id": "449617",
"Score": "0",
"body": "Sorry about the misunderstanding, I won't do it again."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T01:50:50.117",
"Id": "230674",
"Score": "1",
"Tags": [
"beginner",
"c",
"array"
],
"Title": "Size out of limits in array made with malloc"
}
|
230674
|
<p>I recently interviewed for a software engineering job that requires at least one year of C# and experience with the Microsoft stack. Even though I made it clear at the outset that I had zero experience with C#, they still wanted me to take their engineering test, which led me to believe that they were willing to give me a shot because I am really good at learning new programming languages and am otherwise a solid developer. Here are the details for the "bowling exercise" test they gave me:</p>
<blockquote>
<p>To complete this coding exercise, you will need to write a class that
implements the interface below and provides logic to score a bowling
game according to the bowling scoring rules. If you are not familiar
with the rules of bowling, we encourage you to briefly research the
intricacies of the scoring rules. You can write your implementation in
either C# or VB.NET.</p>
<p>You do not need to handle invalid input in your class. Your code does
not need to have a user interface.</p>
<hr>
<h2>C# Interface</h2>
</blockquote>
<pre><code>public interface ISimpleBowlingGame
{
// Called when a player completes a frame.
// This method will be called 10 times for a bowling game.
// The throws parameter provides the number of pins knocked down on each throw in the frame being recorded.
// The 10th frame may have 3 values.
void RecordFrame(params int[] throws);
// Called at the end of the game to get the final score.
int Score { get; }
}
</code></pre>
<p>That's it. That is all of the instruction they provided for this exercise. </p>
<p>So I worked on it for three nights and a whole weekend, and in the end thought I had nailed it. I learned how to implement an interface, set up classes, developed the logic, and included test cases that I thought proved that I had succeeded with this. All of the scoring tests I ran produced the correct final scores. </p>
<p>So I turned in the following code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace bowlingScore
{
public interface ISimpleBowlingGame
{
// Called when a player completes a frame.
// This method will be called 10 times for a bowling game.
// The throws parameter provides the number of pins knocked down on each throw in the frame being recorded.
// The 10th frame may have 3 values.
void RecordFrame(params int[] throws);
// Called at the end of the game to get the final score.
int Score { get; }
}
public class BowlingGame : ISimpleBowlingGame
{
public int Score { get; set; }
public int frame = 0; // The current frame
public int frameScore = 0; // The total of first two throws in a normal frame
public int[] throws; // Input
public int throw1; // First throw in a frame
public int throw2; // Second throw in a frame
public int throw3; // Third throw in the 10th frame
public List<int> tenFrameScores = new List<int>();
public int[][] tenFrames = new int[10][]; // a JaggedArray (to allow for three numbers in the 10th frame)
// RecordFrame records all frames to a data container, to allow for easy scoring
public void RecordFrame(params int[] throws)
{
throw1 = throws[0];
// In case there is no second number (0) provided when someone throws a strike
throw2 = (throws.Length == 1) ? 0 : throws[1];
throw3 = (throws.Length == 3) ? throws[2] : 0;
frameScore = throw1 + throw2;
// Store the frame scores in a list as they come in, to be updated with strike and spare bonuses
tenFrameScores.Add(frameScore);
// Dynamically populate the JaggedArray tenFrames
if (throws.Length == 3)
{
tenFrames[frame] = new[] { throw1, throw2, throw3 };
}
else
{
tenFrames[frame] = new[] { throw1, throw2 };
}
Console.WriteLine("Throws: " + string.Join(",", throws));
// Get the number of non-null elements in the tenFrames array
int numberFramesSoFar = tenFrames.Count(s => s != null);
//Console.WriteLine("Number of frames so far: " + numberFramesSoFar);
frame++;
if (numberFramesSoFar == 10) // Ready to calculate a score
{
Console.WriteLine("Ten frames of data have been received. Ready to score the game.");
for (int i = 0; i < 10; i++) // iterate through the data container of throws
{
Console.WriteLine("tenFrames[" + i + "]: " + string.Join(",", tenFrames[i]));
throw1 = tenFrames[i][0];
throw2 = tenFrames[i][1];
frameScore = tenFrameScores[i];
//Console.WriteLine("Frame total: " + tenFrameScores[i]);
// Strikes and Spares in frames 1-9
if (frameScore == 10 && i < 9)
{
int nextFrameScore = tenFrameScores[i+1];
if (throw1 == 10) // it's a strike
{
ColorMessage(ConsoleColor.Green, "STRIKE!");
// Check to see if the next throw was also a strike
if (tenFrames[i+1][0] == 10) // it's a strike
{
// bonus = 10 + the first throw of the next frame
if (i < 8)
{
int strikeBonus = 10 + tenFrames[i+2][0];
Console.WriteLine("\tNext frame is a strike strikeBonus: " + strikeBonus);
tenFrameScores[i] += strikeBonus;
}
else // frame 9, look at just the first two throws of frame 10
{
int strikeBonus = tenFrames[i+1][0] + tenFrames[i+1][1];
Console.WriteLine("\tNext frame is a strike strikeBonus: " + strikeBonus);
tenFrameScores[i] += strikeBonus;
}
}
else
{
// bonus = the total of the two throws in the next frame (nextFrameScore)
Console.WriteLine("\tstrikeBonus: " + nextFrameScore);
tenFrameScores[i] += nextFrameScore;
}
}
else // spare
{
ColorMessage(ConsoleColor.Cyan, "SPARE!");
Console.WriteLine("\tspareBonus: " + tenFrames[i+1][0]);
tenFrameScores[i] += tenFrames[i+1][0];
}
}
else // Tenth frame bonuses
{
if (throw1 == 10) // strike in the tenth frame
{
ColorMessage(ConsoleColor.Green, "STRIKE! (in the 10th)");
// bonus = throw2 + throw3 (throw2 is already included in tenFrameScores[i])
Console.WriteLine("\tstrikeBonus: " + (throw2 + throw3));
tenFrameScores[i] += throw3;
}
else if (frameScore == 10) // spare in the first two throws of the 10th frame
{
ColorMessage(ConsoleColor.Cyan, "SPARE (in the 10th)!");
// bonus = last throw of the 10th frame
Console.WriteLine("\tspareBonus: " + throw3);
tenFrameScores[i] += throw3;
}
}
}
for (int i = 0; i < 10; i++)
{
Score += tenFrameScores[i];
Console.WriteLine(tenFrameScores[i]);
}
}
}
public void ColorMessage(ConsoleColor color, string message)
{
// Set text color
Console.ForegroundColor = color;
// Write message
Console.WriteLine(message);
// Reset text color
Console.ResetColor();
}
}
public class Test
{
public static void Main()
{
BowlingGame newGame = new BowlingGame();
// Test first game - SUCCESS! (190)
//newGame.RecordFrame(4, 6);
//newGame.RecordFrame(3, 6);
//newGame.RecordFrame(2, 1);
//newGame.RecordFrame(10); // 30
//newGame.RecordFrame(10); // 30
//newGame.RecordFrame(10); // 21
//newGame.RecordFrame(10); // 20
//newGame.RecordFrame(1, 9);
//newGame.RecordFrame(10,0);
//newGame.RecordFrame(10, 4, 6);
// Test perfect game - SUCCESS! (300)
//newGame.RecordFrame(10);
//newGame.RecordFrame(10, 0);
//newGame.RecordFrame(10);
//newGame.RecordFrame(10);
//newGame.RecordFrame(10);
//newGame.RecordFrame(10);
//newGame.RecordFrame(10);
//newGame.RecordFrame(10);
//newGame.RecordFrame(10);
//newGame.RecordFrame(10, 10, 10);
// Test all zeroes
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(0, 0);
// Test successful (111)
//newGame.RecordFrame(10, 0);
//newGame.RecordFrame(2, 8);
//newGame.RecordFrame(4, 3);
//newGame.RecordFrame(0, 8);
//newGame.RecordFrame(0, 5);
//newGame.RecordFrame(7, 0);
//newGame.RecordFrame(1, 9);
//newGame.RecordFrame(10, 0);
//newGame.RecordFrame(0, 0);
//newGame.RecordFrame(10, 10, 0);
// Test successful (236)
//newGame.RecordFrame(3, 7);
//newGame.RecordFrame(9, 1);
//newGame.RecordFrame(10, 0);
//newGame.RecordFrame(10, 0);
//newGame.RecordFrame(8, 2);
//newGame.RecordFrame(10, 0);
//newGame.RecordFrame(10, 0);
//newGame.RecordFrame(9, 1);
//newGame.RecordFrame(10, 0);
//newGame.RecordFrame(10, 10, 10);
// All spares + bonus in 10th (150)
newGame.RecordFrame(1, 9);
newGame.RecordFrame(2, 8);
newGame.RecordFrame(3, 7);
newGame.RecordFrame(4, 6);
newGame.RecordFrame(5, 5);
newGame.RecordFrame(6, 4);
newGame.RecordFrame(7, 3);
newGame.RecordFrame(8, 2);
newGame.RecordFrame(9, 1);
newGame.RecordFrame(0, 10, 6);
string finalScore = "\nThe FINAL score is : " + newGame.Score;
newGame.ColorMessage(ConsoleColor.Red, finalScore);
}
}
}
</code></pre>
<p>A couple days later I heard feedback from them that basically they were disappointed with the code that I turned in, but they didn't say more than that.</p>
<p>Can someone tell me why? Did I fail to understand what they were really looking for? I thought my code was good because it met all of their stated requirements and does what it's supposed to. </p>
<p>What am I missing?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:47:40.910",
"Id": "449626",
"Score": "0",
"body": "With what language do you have the one year experience?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:51:40.783",
"Id": "449640",
"Score": "1",
"body": "*What am I missing?* The question is not really a good test of C# knowledge. It lacks a description of how bowling scores work. While the ability to research bowling scores might be a useful skill, it's not a C# skill and candidates familiar with bowling are at an advantage over those who are not. The hiring team was too lazy to actually describe the problem. Wasting your time and not providing useful feedback is just an extension of that. There are better employers out there. Good luck."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:41:38.580",
"Id": "449659",
"Score": "0",
"body": "@Denis, this problem would have been extremely easy for me to accomplish in Python or JavaScript. I would also be able to complete it in Perl or PHP. I love using data structures for things like this. While I do understand OOP, what I don't understand well is unstated expectations. For example, the expectation that the code make use of more classes, or be highly optimized (or elegant). I was just trying to meet the requirements with working code. They know I don't yet know C#. Optimization could come later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T05:20:08.290",
"Id": "449728",
"Score": "0",
"body": "@benrudgers is right if they give you the [Bowling Kata](http://codingdojo.org/kata/Bowling/) as test there should be _some_ more information on how to solve it and what they expect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T18:38:00.247",
"Id": "449800",
"Score": "0",
"body": "I noticed a common theme with a lot of the responses I got on this Code Review. C# developers tend to view their code almost as art! I see the terms elegant, clear, clean, production quality, etc.. One person was bothered that my ternaries weren't lined up in the same order! \n\nThis is a really different culture than I am used to. As a utilitarian developer, my focus is almost always on code that works. I use a lot of Python, and I do try to adhere to PEP 8 standards, so I guess I am used to what looks good in Python but am just naive about what does or doesn't look good in C#."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T18:38:14.367",
"Id": "449801",
"Score": "0",
"body": "Thanks everyone for their feedback! I think I am going to rewrite this exercise solution the \"right\" way based on the comments here."
}
] |
[
{
"body": "<h1>Private versus public</h1>\n\n<pre><code> public int frame = 0; // The current frame\n public int frameScore = 0; // The total of first two throws in a normal frame\n public int[] throws; // Input\n public int throw1; // First throw in a frame\n public int throw2; // Second throw in a frame\n public int throw3; // Third throw in the 10th frame\n\n public List<int> tenFrameScores = new List<int>();\n public int[][] tenFrames = new int[10][]; // a JaggedArray (to allow for three numbers in the 10th frame)\n</code></pre>\n\n<p>All these fields should be <code>private</code>. Since your class implements the interface <code>ISimpleBowlingGame</code>, the idea is that most, if not all, interaction with this class should be based on that interface. By making these fields <code>public</code>, you're allowing the user to mess with the internal state of the class, which might mess up all logic you have.</p>\n\n<p>The same goes for <code>Score.Set</code>, this should be <code>private</code>; the score is determined by the frames given through <code>RecordFrame()</code>, adjusting the score manually makes no sense.</p>\n\n<p>When to use <code>public/private/internal</code> is a pretty basic part of understanding languages like C#, so be sure to review this some more.</p>\n\n<hr>\n\n<h1>Class fields versus method variables</h1>\n\n<pre><code> public int throw1; // First throw in a frame\n public int throw2; // Second throw in a frame\n public int throw3; // Third throw in the 10th frame\n</code></pre>\n\n<p>These are only ever used within <code>RecordFrame</code>, so make them local variables within that method.</p>\n\n<hr>\n\n<h1><code>Console.WriteLine</code></h1>\n\n<p>The spec specifically said that you didn't have to provide a user interface. So all of the printing to console was a wasted effort. Especially with all the different colours and such.</p>\n\n<p>Not even was it unnecessary, but it's not the most flexible implementation either. What if instead of writing the output to console we wanted to write it to a file? Remember that the primary concern of the class is to calculate a bowling score. You don't know how it is going to be used yet, or where. So it's best to not make assumptions to that.</p>\n\n<p>If you want to provide a way to turn the state of the class into a string, so that the user could <strong>choose</strong> to print it to commandline, provide an implementation of <code>ToString()</code>, which you can override:</p>\n\n<pre><code>public override string ToString() {\n // implementation;\n}\n</code></pre>\n\n<hr>\n\n<h1>Scoring</h1>\n\n<p>Your scoring code is a bit of a mess. Let's quickly go over the rules:</p>\n\n<ol>\n<li>A throw is worth at least the number of pins thrown.</li>\n<li>If a strike is thrown (10 pins in the first throw of a frame), the next two throws are added to the score of the strike.</li>\n<li>If a spare is thrown (10 pins in the frame, not a strike), the next throw is added to the score of the spare.</li>\n<li>If the tenth frame ends in a strike or spare, 2 or 1 throws are added respectively to add the bonus score, these don't count on their own.</li>\n</ol>\n\n<p>Given that the complexity of the challenge is in the scoring mechanism, this should be leading for how you store the throws. I don't think that separating the throws in frames in <code>tenFrames</code> is the best approach.</p>\n\n<p>Why? Because to score spares and strikes, you need to be able to look ahead to the next throws to determine the score. This is easiest if the next throws are adjacent in an array, instead of in a jagged array. Remember that if you throw 2 strikes in a row, you need to look two frames ahead to determine the score of the first strike!</p>\n\n<p>So let's assume all throws are in an <code>int[]</code>, the first frame could then be scored as such:</p>\n\n<pre><code>if(throws[0] == 10) {\n // strike\n score += 10 + throws[1] + throws[2];\n} else if (throws[0] + throws[1] == 10) {\n // spare\n score += 10 + throws[2];\n} else {\n // normal throw\n score += throws[0] + throws[1];\n}\n</code></pre>\n\n<p>That's pretty neat isn't it? Let's loop over all frames:</p>\n\n<pre><code>public int ScoreFrames(int[] throws)\n{\n var frame = 1;\n var score = 0;\n var frameStart = 0;\n while (frame <= 10)\n {\n if (throws[frameStart] == 10)\n {\n // strike\n score += 10 + throws[frameStart + 1] + throws[frameStart + 2];\n frameStart += 1;\n }\n else if (throws[frameStart] + throws[frameStart + 1] == 10)\n {\n // spare\n score += 10 + throws[frameStart + 2];\n frameStart += 2;\n }\n else\n {\n // normal throw\n score += throws[frameStart] + throws[frameStart + 1];\n frameStart += 2;\n }\n frame++;\n }\n return score;\n}\n</code></pre>\n\n<p>You can keep track of where the next frame starts in <code>frameStart</code>: a strike is only one throw in a frame, the rest is two.</p>\n\n<p>The rest is simple:</p>\n\n<pre><code> public class SimpleBowlingGame : ISimpleBowlingGame {\n private readonly List<int> throws = new List<int>(21); // 21 is the maximum amount of throws.\n private int numberOfFrames = 0;\n\n public int Score { get; private set; }\n\n public void RecordFrame(params int[] throws) {\n // Optional input validation.\n\n this.throws.AddRange(throws);\n numberOfFrames++;\n\n if(numberOfFrames == 10) {\n SetScore();\n }\n }\n\n private void SetScore() {\n var frame = 1;\n var score = 0;\n var frameStart = 0;\n while (frame <= 10) {\n if (throws[frameStart] == 10) {\n // strike\n score += 10 + throws[frameStart + 1] + throws[frameStart + 2];\n frameStart += 1;\n }\n else if (throws[frameStart] + throws[frameStart + 1] == 10) {\n // spare\n score += 10 + throws[frameStart + 2];\n frameStart += 2;\n }\n else {\n // normal throw\n score += throws[frameStart] + throws[frameStart + 1];\n frameStart += 2;\n }\n frame++;\n }\n Score = score;\n }\n }\n</code></pre>\n\n<hr>\n\n<h1>Bonus points: input validation</h1>\n\n<p>Spec says it's not necessary, but it never hurts to verify that the throws you get as input are actually legal. In the <code>SetScore</code> method, we rely heavily on the inputs as we expect them to be, so it doesn't hurt to validate:</p>\n\n<ol>\n<li>All numbers in <code>throws</code> are between 0 and 10</li>\n<li>If the first number is lower than 10, the second can at most be <code>10 - throws[0]</code></li>\n<li><code>throws.Length</code> is 1 or 2, unless it's the tenth frame, then it can only be 3 if it's a spare or strike, else it's 2.</li>\n<li>After the tenth frame, no more input is taken.</li>\n</ol>\n\n<hr>\n\n<h1>Bonus points: Disallow <code>Score</code> from being called before the tenth frame is provided.</h1>\n\n<pre><code>private int score;\npublic int Score {\n get {\n if (numberOfFrames != 10) {\n throw new InvalidOperationException(\"Can't provide score before 10 frames are recorded\");\n }\n return score;\n }\n private set {\n score = value;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:14:11.613",
"Id": "449594",
"Score": "2",
"body": "I find it counterintuitive to throw an exception on the score when the game is in progress, as opposed to showing the _current_ score. It's an unjustified exception usage, imho. Every bowling score tracker I've seen shows you the current score (and yes, you can't account for the potential bonus points on recent strikes and spares and that's okay)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T12:48:30.630",
"Id": "449612",
"Score": "0",
"body": "@Flater that's a design decision that can be justified. The spec says `Called at the end of the game to get the final score.` and the property isn't filled until the last frame is entered, so in this implementation, showing the score before the tenth frame is not supported. This is, IMO, a good reason to throw, instead of returning `default(int)` as if everything was ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:29:41.590",
"Id": "449657",
"Score": "0",
"body": "Does this solution allow for the possibility that in a strike frame there may be a 0, as the second value? For example (10, 0)? Not knowing if the input for a strike is going to be a single int 10, or if there would always be two values for throws, thus a zero after the 10, is the main reason for the nested if statements I used. If I knew that strikes would always just be a 10 and no second throw value, then I would have set this up differently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:43:57.400",
"Id": "449660",
"Score": "0",
"body": "@JAD, _The spec specifically said that you didn't have to provide a user interface. So all of the printing to console was a wasted effort. Especially with all the different colours and such. Not even was it unnecessary, but it's not the most flexible implementation either. What if instead of writing the output to console we wanted to write it to a file?_\n\nThe instructions said it does not need to have an interface, but it didn't say that I couldn't use my own in order to show my testing and thought process. Right? I guess I am not good at imagining what the testers expect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:07:05.523",
"Id": "449665",
"Score": "0",
"body": "@ChrisNielsen after a strike, you don't throw again. So I'd consider `new [] { 10, 0 }` invalid input. As for the userinterface, using it for testing is perfectly fine, but I wouldn't expect random print statements in production code. It seems like that is what they expected with the assignment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:33:45.043",
"Id": "449671",
"Score": "0",
"body": "Thanks @JAD. I understand what you mean and it makes logical sense. Maybe they did expect the code to look like production quality code.. If they stated so I certainly wouldn't have included my print statements. I guess I am just not presumptuous enough. It also explains my hesitation to assume that there would not be a second value after a strike.. Logically, it should just be a 10 for that frame and that's it. But how do I know what they are going to send my way? I didn't want the scoring to break based on an assumption."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:53:08.437",
"Id": "449672",
"Score": "0",
"body": "@ChrisNielsen That sounds like a very good reason to add input validation ;) In your `RecordFrame` method, before you do anything, verify all your assumptions and comment them. This serves two purposes: If you throw meaningful exceptions, you show the user of the code what your class expects in terms of input, and how to deal with that. But alongside with that, you show the interviewers that you thought about what edgecases there can be, that you thought about what the input should look like. That helps a lot too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:33:10.647",
"Id": "449678",
"Score": "1",
"body": "@JAD, they said in the instructions: _You do not need to handle invalid input in your class._ but they never said what was valid! I guess this means that some level of logical assumption IS necessary. Thank you for all the input. I am learning from this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-17T16:54:52.870",
"Id": "450044",
"Score": "1",
"body": "@JAD It looks like you are using one long array called throws to store all of the throws and are abandoning the frame distinction in RecordFrame. Your idea is to recreate frames using logic in the SetScore function? So if someone wanted to create a \"print game\" function later, showing the throws in each frame, they would have to recreate the game using logic rather than just printing the game based on frames and throws that were originally input? I am normally in favor of using data structures that mimic the input, rather than recreating the data using logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-17T16:55:48.110",
"Id": "450045",
"Score": "1",
"body": "@JAD Even in OOP, we want to maintain data integrity right? Coming from Python, an array of tuples would be perfect for this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T05:49:56.040",
"Id": "450091",
"Score": "0",
"body": "@ChrisNielsen good points. It sounds like a good idea to indeed create a frame class to store the frames (a bit like Flater suggested). The `SetScore` method could then instead retrieve the individual throws and put it in a single list for it to process internally. (I still think that having the throws organised in frames hurts the scoring algorithm, since the scoring isn't nicely contained within frames)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T07:47:54.200",
"Id": "230684",
"ParentId": "230675",
"Score": "5"
}
},
{
"body": "<h2>Inconsistency</h2>\n\n<p>This is a minor thing, but I tripped over it when skimming your code:</p>\n\n<pre><code>throw2 = (throws.Length == 1) ? 0 : throws[1];\nthrow3 = (throws.Length == 3) ? throws[2] : 0;\n</code></pre>\n\n<p>Why did you invert one of the ternaries? It'd be easier to read if you kept the same structure, e.g.</p>\n\n<pre><code>throw2 = (throws.Length >= 2) ? throws[1] : 0;\nthrow3 = (throws.Length >= 3) ? throws[2] : 0;\n</code></pre>\n\n<hr>\n\n<h2>Variable juggling</h2>\n\n<p>You're spending a whole lot of effort on putting things in other locations and then putting them back. Look at what happens to the throw data:</p>\n\n<pre><code>public void RecordFrame(params int[] throws)\n{\n throw1 = throws[0];\n // In case there is no second number (0) provided when someone throws a strike\n throw2 = (throws.Length == 1) ? 0 : throws[1];\n throw3 = (throws.Length == 3) ? throws[2] : 0;\n frameScore = throw1 + throw2;\n // Store the frame scores in a list as they come in, to be updated with strike and spare bonuses\n tenFrameScores.Add(frameScore);\n\n // Dynamically populate the JaggedArray tenFrames\n if (throws.Length == 3)\n {\n tenFrames[frame] = new[] { throw1, throw2, throw3 };\n } \n else\n {\n tenFrames[frame] = new[] { throw1, throw2 };\n }\n\n // ...\n}\n</code></pre>\n\n<ol>\n<li>You get an array of throws</li>\n<li>You define a custom variable for each element of the array</li>\n<li>You then merge these custom variables into an array to store them.</li>\n</ol>\n\n<p>There's no point to making these separate variables. There is no coding overhead compared to e.g. calling <code>throws[0]</code> (which you already have) as opposed to <code>throw1</code> (which you need to create.</p>\n\n<p>This can be rewritten to a much simpler:</p>\n\n<pre><code>public void RecordFrame(params int[] throws)\n{\n tenFrameScores.Add(throws.Take(2).Sum());\n tenFrames[frame] = throws;\n\n // ...\n}\n</code></pre>\n\n<p>To be fair, what I have omitted here is the default <code>0</code> assignment to unmentioned throws which may be important down the line, but that is something I will tackle in a subsequent feedback point as I suggest reworking this much further. For the currently mentioned code, it will not throw an exception even if only one throw value was entered.</p>\n\n<hr>\n\n<h2>Storing empty throws</h2>\n\n<p>I disagree that you should store empty throws. I don't mean gutter balls, but rather never-thrown values, such as the second throw in a strike frame, or the third throw in the 10th frame if there was no spare or strike.</p>\n\n<p>By storing them as a <code>0</code> value, you make it harder on yourself to later tell the difference between a gutter ball (an actual <code>0</code> throw) or a non-existent throw.</p>\n\n<p>The reason you should avoid this is that it complicates your strike bonus calculation. Very basically, the logic of a strike is that you add the value of the <strong>next two throws</strong> to the strike's score.<br>\nNow, if the next frame is also a strike, and you were to store this second frame as <code>(10,0)</code>, your logic would think that those were the \"next two\" throws.</p>\n\n<p>That is not the case. The second throw does not exist and does not count.</p>\n\n<p>Compare this to if the second frame is <code>(0,0)</code> (two gutter balls). Here, the second throw <strong>does</strong> exist and it does count towards the \"next two throws\" after the strike.</p>\n\n<p>By not storing the non-existent throws as zeroes, you could severely cut down on the complexity of your scoring calculation, as you wouldn't need to handle things like \"is the second throw also a strike\" fringe cases.</p>\n\n<hr>\n\n<h2>No validation</h2>\n\n<p>You aren't really validating any of the input. There are some simple validation checks you could be implementing:</p>\n\n<ul>\n<li>Making sure at least 1 throw value is registered for each frame</li>\n<li>Making sure no more than 2/3 values are registered for each frame (based on whether it's the 10th frame or not)</li>\n<li>Making sure no frame contains more than 10 total score (unless it's the 10th frame, in which case 30 is the maximum)</li>\n<li>Making sure no single throw value is lower than 0</li>\n<li>Making sure no single throw value is higher than 10</li>\n</ul>\n\n<p>Validation can be short or elaborate, and we can argue and disagree which validation is necessary or superfluous; but as a job interviewer I would want to see <strong>some</strong> validation in the code as a matter of good practice.</p>\n\n<hr>\n\n<h2>Lists vs arrays</h2>\n\n<pre><code>private readonly List<int> throws = new List<int>(21); // 21 is the maximum amount of throws.\n</code></pre>\n\n<p>One the the main sticking point of using a <code>List<></code> over an array is that you do not need to pre-emptively specify the collection size. Lists can grow dynamically. It makes little sense to specify a maximum size here.</p>\n\n<p><em>To be fair, I find it weird that the language allows for it, but I suspect this is one of those \"it could be done even though no one really needs it\" instances, the .Net framework has a few of those.</em></p>\n\n<hr>\n\n<h2>Expected usage inconsistency</h2>\n\n<p>I noticed this in your test cases:</p>\n\n<pre><code>// Test perfect game - SUCCESS! (300)\nnewGame.RecordFrame(10);\nnewGame.RecordFrame(10, 0);\nnewGame.RecordFrame(10);\n</code></pre>\n\n<p>I disagree that <code>(10,0)</code> should be a valid throw. You are not allowed to throw a second time in a frame if the first throw was a strike. It's a counterintuitive approach.</p>\n\n<p>That being said, I also slightly disagree with the interface (which is not your fault but I'd still like to point it out), it makes more sense to use explicit parameters with default values here, e.g.:</p>\n\n<pre><code>void RecordFrame(int throw1, int throw2 = 0, int throw3 = 0);\n</code></pre>\n\n<p>This enforces that a frame always consists of 1 to 3 throws. Using an <code>int[]</code> allows for 0 or more than 3 values, which is plain wrong.</p>\n\n<p>I know you can't change the requirement you were given, but I think it is still useful to point it out as an improvement nonetheless.</p>\n\n<hr>\n\n<h2>When to calculate the end score</h2>\n\n<p>I disagree with the location you've chosen to do the calculations:</p>\n\n<pre><code>public void RecordFrame(params int[] throws)\n{\n // Record frame logic\n\n if (numberFramesSoFar == 10) // Ready to calculate a score\n {\n // Scoring logic\n }\n}\n</code></pre>\n\n<p>Recording frames and calculating scores are two completely separate responsibilities. As an <strong>absolute minimum</strong>, these should've been separated into separate methods just to break up the monolithic method you've ended up with. E.g.:</p>\n\n<pre><code>public void RecordFrame(params int[] throws)\n{\n // Record frame logic\n\n if (numberFramesSoFar == 10) // Ready to calculate a score\n {\n CalculateFinalScore();\n }\n}\n\npublic void CalculateFinalScore()\n{\n // Scoring logic\n}\n</code></pre>\n\n<p>But I also disagree with triggering the score calculation during the recording of the tenth frame. It's much more intuitive to do this when the score is being observed:</p>\n\n<pre><code>public void RecordFrame(params int[] throws)\n{\n // Record frame logic\n}\n\npublic int CalculateFinalScore()\n{\n // Scoring logic\n}\n\npublic int Score => CalculateFinalScore();\n</code></pre>\n\n<p>Note that you could cache the calculated score so that accessing the property a second time doesn't retrigger a recalculation, but I'm going to currently dismiss that as a \"nice to have\" based on more pressing issues with the code you've currently posted.</p>\n\n<p>Nonetheless, if you are interested, here's a basic implementation:</p>\n\n<pre><code>public void CalculateFinalScore()\n{\n // Scoring logic\n\n _calculatedScore = // result from calculation\n _scoreWasCalculated = true;\n}\n\nprivate bool _scoreWasCalculated = false;\nprivate int _calculatedScore = 0;\n\npublic int Score \n{\n get\n {\n if(!_scoreWasCalculated)\n CalculateFinalScore();\n\n return _calculatedScore;\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Lack of OOP</h2>\n\n<p>The biggest issue I see in the codebase is that you are not using OOP.</p>\n\n<p>I won't rehash JAD's answer, but he is correct about the public/private issues and some of the scope declarations (class variables vs local variables).</p>\n\n<p>One thing I think hasn't been pointed out yet is that your entire logic relies on arrays and primitives. The only OOP object you've used is the <code>BowlingGame</code> class, which you were forced to use because of the interface in the requirements.</p>\n\n<blockquote>\n <p>They were willing to give me a shot because I am really good at learning new programming languages and am otherwise a solid developer.</p>\n</blockquote>\n\n<p>Without trying to be mean, I'm going to disagree here. The low readability of your code is something that is independent of C#. Whatever your existing experience is in, I suspect your code is going to be of equally low readability, which is not what I would associate with a \"solid developer\".</p>\n\n<p>Please don't take this as an attack - I genuinely don't mean to insult. There's nothing wrong with being a starter. Everyone has to start somewhere, we all had to learn the ropes, I've written worse C# code than yours when I was just beginning. But I would advise you against overselling yourself.<br>\nIf you overstate your ability and then fail to meet that claim, you're going to be less likely to be hired (if I were your interviewer) compared to if you are humble about your ability but put a genuine effort forward (even if you end up with mistakes).</p>\n\n<p>As this was a job interview, as an interviewer I would conclude that you do not grasp the basics of OOP and are not a good fit for the position of a C# developer. A one year experience requirement is not very much, but in one year a developer should at least be able to apply OOP principles. </p>\n\n<p>You can't be expected to apply OOP perfectly (SOLID etc) even if you had the required one year of experience, but you should at least be using it and in this exercise you didn't really try to implement OOP. </p>\n\n<p>Without intending to sound mean, I can't explain the entirety of OOP and how it could be used for your example, but I will try to get you started on what you can look at (I suggest following some OOP tutorials as StackExchange cannot provide the same level of guidance)</p>\n\n<p>As a basic example, a <code>Frame</code> class would come to mind, where you store the throw information. This allows you to not only work with neatly separated data objects, it also allows for reusable logic such as <code>IsStrike</code> or <code>IsSpare</code> checks.</p>\n\n<p>A rough draft (this is open to many improvements, I'm trying to give you the simplest example to get started):</p>\n\n<pre><code>public class Frame\n{\n public List<int> Throws { get; private set; }\n\n public Frame(List<int> throws)\n {\n if(throws == null || throws.Count() < 1 || throws.Count() > 3)\n throw new ArgumentException(\"Frames must consist of 1 to 3 throws\", \"throws\");\n\n if(throws.Any(throw => throw > 10))\n throw new ArgumentException(\"A single throw cannot contain more 10 pins\");\n\n this.Throws = throws;\n } \n\n public bool IsSpare()\n {\n return this.Throws.Take(2).Sum() == 10;\n }\n\n public bool IsStrike()\n {\n return this.Throws.First() == 10;\n }\n\n}\n</code></pre>\n\n<p>This means you can change all your \"value equals 10\" checks with a much more readable call to the <code>IsStrike()</code> and <code>IsSpare()</code> methods. Not only is it more readable, it's also more refactor-friendly (though admittedly I don't expect the rules of bowling to be changed anytime soon, the point still stands on principle).</p>\n\n<p>I suggest you follow up with some C# OOP tutorials to learn the finer points of OOP and how to implement it.</p>\n\n<hr>\n\n<blockquote>\n <p>Can someone tell me why? Did I fail to understand what they were really looking for? I thought my code was good because it met all of their stated requirements and does what it's supposed to.</p>\n</blockquote>\n\n<p>The code doing what it's supposed to do is not the only measure of a good developer. I can write massively different code files that are treated exactly the same by a compiler, yet are dramatically different in terms of quality.</p>\n\n<p>As a silly but blatant example:</p>\n\n<pre><code>private int poizpdodz(int pdnzfe, int poknsdds)\n{\n return pdnzfe + poknsdds;\n}\n\nprivate int Add(int a, int b)\n{\n return a + b;\n}\n</code></pre>\n\n<p>The compiler does not care about method/variable names and both methods will be compiled (and executed) the exact same way, but we can all agree that the second method is much better written.</p>\n\n<p>Furthermore, it's not just about how the code works <em>now</em>, but also how easy it is to maintain the code in the future. A lot of code in the average codebase I work in is not related to the business goal of the specific application, but rather framework/architecture than ensures that any changes that need to be made in the future can be minimized in terms of effort and impact.</p>\n\n<p>In short, there are many more metrics to the quality of code than just \"it works\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:11:18.533",
"Id": "449667",
"Score": "0",
"body": "With regards to specifying the length of the list of throws on creation; I'll admit that it's a micro-optimisation, but just because `List<T>` supports growing lists, doesn't mean we should make use of it. There is an overhead involved in growing the internal array, so if we can pre-empt that by knowing the theoretical max size (and min size), why not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:14:49.693",
"Id": "449668",
"Score": "0",
"body": "I think the tricky part of creating a `Frame` class is that it gains you little for calculating the score of the frame, due to the special status of strikes and spares. Minor nitpick: maybe expose `Frame.Throws` as a `IReadOnlyList`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:15:06.827",
"Id": "449669",
"Score": "0",
"body": "That's it for my nitpicks, agreed with the rest. +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T10:12:07.377",
"Id": "449750",
"Score": "0",
"body": "Another thing to possibly add is the use of code comments to describe what the code is doing because it is not expressive enough. This ties back into your comment about not having a full grasp of OOP."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:04:54.493",
"Id": "230706",
"ParentId": "230675",
"Score": "8"
}
},
{
"body": "<p>To the many useful points already made I have only a small contribution to add:</p>\n\n<blockquote>\n<pre><code> public class Test\n {\n public static void Main()\n {\n BowlingGame newGame = new BowlingGame();\n\n // Test first game - SUCCESS! (190)\n //newGame.RecordFrame(4, 6);\n //newGame.RecordFrame(3, 6);\n //newGame.RecordFrame(2, 1);\n //newGame.RecordFrame(10); // 30\n //newGame.RecordFrame(10); // 30\n //newGame.RecordFrame(10); // 21\n //newGame.RecordFrame(10); // 20\n //newGame.RecordFrame(1, 9);\n //newGame.RecordFrame(10,0);\n //newGame.RecordFrame(10, 4, 6);\n</code></pre>\n</blockquote>\n\n<p>That's not an elegant way of doing tests. The \"best practice\" would be to use a testing framework like NUnit or Microsoft's testing SDK.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T05:01:58.940",
"Id": "449727",
"Score": "0",
"body": "Thanks for the info. I've never heard of those as C# and the Microsoft stack are brand new to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T09:54:42.670",
"Id": "449747",
"Score": "0",
"body": "@ChrisNielsen, for what it's worth, lots of languages have something similar. If you get a similar coding task for a Java interview, for example, I'm guessing that JUnit is still the de facto standard."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T21:00:50.203",
"Id": "230723",
"ParentId": "230675",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T02:42:48.193",
"Id": "230675",
"Score": "5",
"Tags": [
"c#",
"interview-questions"
],
"Title": "C# Bowling Game interview test"
}
|
230675
|
<p>I'm currently creating a 2d game in python. I have to calculate the closest enemy so the player knows which one to target. I have the following function to accomplish this task:</p>
<pre><code>import math
def find_closest(character: tuple, enemies: list) -> (int, int):
"""
Finds the closest enemy in enemies
:param character: An (x, y) representing the position of the character\n
:param enemies: A list of tuples (x, y) that represent enemies
:return: A tuple (x, y) of the closest enemy
"""
closest_enemy = None
smallest_distance = 100_000_000 # Set to large number to ensure values can be less #
for enemy in enemies:
distance = math.sqrt(math.pow(character[0] - enemy[0], 2) + (math.pow(character[1] - enemy[1], 2)))
if distance < smallest_distance:
closest_enemy = (enemy[0], enemy[1])
smallest_distance = distance
return closest_enemy
if __name__ == "__main__":
# Test Case #
character = (5, 6)
enemies = [(1, 2), (3, 4), (7, 6), (11, 4)]
closest = find_closest(character, enemies)
print(closest)
</code></pre>
<p>I would like to know if there's any better way to go about doing this. While it is a simple function, I'm sure there's some built in python function that can accomplish this even shorter. I use tuples because, in my opinion, they're the best way to represent coordinates. Any and all suggestions and/or improvements are welcome and appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:21:32.260",
"Id": "449582",
"Score": "0",
"body": "If you can use scipy, kdtree.query does exactly that https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.query.html#scipy.spatial.KDTree.query"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:53:43.343",
"Id": "449590",
"Score": "3",
"body": "I assume you need the distance _as the crow flies_, not factoring in pathfinding?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T12:28:31.410",
"Id": "449608",
"Score": "0",
"body": "You could easily simplify this by using `return \"code\"` ;P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T04:41:41.980",
"Id": "449726",
"Score": "0",
"body": "This question was basically asked ~6 years ago: https://codereview.stackexchange.com/questions/28207/finding-the-closest-point-to-a-list-of-points"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T08:43:37.487",
"Id": "449743",
"Score": "0",
"body": "For large number you should use math.inf (infinity)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T20:21:09.540",
"Id": "449810",
"Score": "0",
"body": "Take a look at the Jonker Volgenant Algorithm. There's a python implementation here: https://github.com/hrldcpr/pyLAPJV. For reference, I rewrote this algorithm in Java for exactly your purpose, and it was able to optimally solve huge bipartite graphs exponentially quicker than brute force (https://github.com/dberm22/Bipartite-Solver). Greedy search is even faster, but not necessarily optimal."
}
] |
[
{
"body": "<p>Specific suggestions:</p>\n\n<ol>\n<li>I believe collection types should be taken from <code>typing</code>, so your signature would be something like <code>find_closest(character: Tuple[int, int], enemies: List[Tuple[int, int]]) -> Tuple[int, int]</code>. At which point you may want to pull out and reuse a <code>Coordinate</code> type.</li>\n<li>Because your coordinates could be anything from millimetres to light-years I'd probably choose a much larger initial smallest distance. Or bite the bullet and set it to <code>None</code> and return an <code>Optional[Tuple[int, int]]</code>.</li>\n<li>This was probably just for illustration purposes, but just in case, test cases are usually in a separate file and use <code>TestCase.assert*</code> methods to verify the results.</li>\n<li>Since a² < b² implies a < b (when a and b are positive) you can remove the <code>math.sqrt</code> for a speed-up.</li>\n</ol>\n\n<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"noreferrer\"><code>flake8</code></a> with a strict complexity limit can give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n<li><p>I would then recommend validating your <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> using a strict <a href=\"https://github.com/python/mypy\" rel=\"noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_any_generics = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T05:24:43.703",
"Id": "230678",
"ParentId": "230676",
"Score": "10"
}
},
{
"body": "<p>I would make the function slightly more generic. After all, you do calculate <em>all</em> distances anyway. I don't think list length becomes a storage space issue here, so why not return a list sorted by distance to the player?</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Tuple, List\n\ndef distance(character: Tuple[int, int], enemy: Tuple[int, int]) -> int:\n return math.sqrt((character[0] - enemy[0]) ** 2 + (character[1] - enemy[1]) ** 2)\n</code></pre>\n\n<p>No reason to use math.pow when we have a perfectly valid <code>**</code> operator. Some would also prefer to use it to get the root, but I don't really like that with regards to readability.</p>\n\n<p>To sort a list, you can supply a <code>key: Callable=(...)</code> keyword argument. We want to supply the above distance function to sort by. I'm using <code>functools.partial</code> to \"bake in\" the characters data, but you could also declare the function inside your sorting function and leave the argument definition out.</p>\n\n<p>Then return a list like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from functools import partial\n\ndef sort_closest(character: Tuple[int, int], enemies: List[Tuple[int, int]]) -> List[Tuple[int, int]]:\n \"\"\"\n Finds the closest enemy in enemies\n\n :param character: An (x, y) representing the position of the character\\n\n :param enemies: A list of tuples (x, y) that represent enemies\n\n :return: A tuple (x, y) of the closest enemy\n \"\"\"\n return sorted(enemies, key=partial(distance, character))\n</code></pre>\n\n<p>Then retrieve the closest enemy with:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>closest = sort_closest(player, enemies)[0]\n</code></pre>\n\n<p>Note: I also included @I0b0's typing reccomendation. You could of course omit the <code>math.sqrt</code> function in <code>distance()</code> if you <em>only</em> use it for sorting, but then you'd have to also rename it to not be \"distance\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T07:02:57.933",
"Id": "230681",
"ParentId": "230676",
"Score": "5"
}
},
{
"body": "<p>First of all, let's talk about magic numbers. <code>smallest_distance = 100_000_000</code> is a problem. Where's the hundred million come from? When you have numbers in your code, there should ideally be a specific reason for why you're using that number instead of any other, and numbers that are picked just to be ludicrously large have a weird habit of turning out to be smaller than something when your code evolves. If all your enemies happen to be further than a hundred million units away, this function will return <code>None</code> and possibly cause something to blow up. There are two conventional starting values for a min loop: either the maximum possible number supported by that data type, or the first element of the array. Using the first element is generally better, especially in Python where things can be a bit fuzzy on exactly what data type we're using.</p>\n\n<p>That said, there's an easier way to write this min loop. Don't.<br>\nPython's biggest strength is the way that it provides functions to do a lot of this stuff for you. In particular, it provides a <a href=\"https://docs.python.org/3/library/functions.html#min\" rel=\"noreferrer\"><code>min</code></a> function. Normally you'd use min like this:</p>\n\n<pre><code>min([4, 2, 9, 2, 8])\n</code></pre>\n\n<p>That would return 2 with no messing around with what initial value you want to guess. You can also provide a <code>key</code> function to change what you're comparing on, which you'll want to do here to use the hypotenuse to your character. </p>\n\n<pre><code>def find_enemy_distance(enemy):\n return math.sqrt(math.pow(character[0] - enemy[0], 2) + (math.pow(character[1] - enemy[1], 2)))\n</code></pre>\n\n<p>Then you can call min as follows:</p>\n\n<pre><code>min(enemies, key=find_enemy_distance)\n</code></pre>\n\n<p>Speaking of python providing functions that make things easier, there is a math.hypot which removes the need to do your own squaring and square rooting. We can then go for </p>\n\n<pre><code>def find_enemy_distance(enemy):\n return math.hypot((character[0] - enemy[0]), (character[1] - enemy[1]))\n</code></pre>\n\n<p>The overall function, (without your entirely appropriate docstring), looks like</p>\n\n<pre><code>def find_closest(character: tuple, enemies: list) -> (int, int):\n def find_enemy_distance(enemy):\n return math.hypot((character[0] - enemy[0]), (character[1] - enemy[1]))\n return min(enemies, key=find_enemy_distance)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T09:13:46.157",
"Id": "449574",
"Score": "0",
"body": "In your `find_enemy_distance()`, you can remove all but the parens of the math.hypot function call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T09:23:40.183",
"Id": "449575",
"Score": "0",
"body": "True. I actually took them out initially, but I found it slightly more readable just for the grouping. That's very much subjective stylistic stuff."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T09:34:31.487",
"Id": "449577",
"Score": "0",
"body": "True, it's very subjective, and we apparently end up on different sides of the preference, then. It's rare for me to prefer any parens if I could do without them. I also didn't know that min() accepted key=, so that's nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T09:48:04.653",
"Id": "449578",
"Score": "0",
"body": "This version only returns the distance to the closest enemy, not their identity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:26:37.720",
"Id": "449585",
"Score": "1",
"body": "@PeterJennings, no it doesn't. `min` uses the `key` function to do the comparison, but it still returns the original item from the collection. In the provided example case, it returns `(7, 6)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:54:51.247",
"Id": "449641",
"Score": "0",
"body": "math.hypot contains a sqrt-call that is not needed as it's a monotonic function and does not change the order of the elements (a<b -> sqrt(a) < sqrt(b) (for positive numbers). So we can compare the squared distances (dx**2+dy**2) instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:00:22.037",
"Id": "449663",
"Score": "0",
"body": "That is true. Personally, I would consider the readability benefit of hypot for hypotenuse to justify using it as a default, but I agree that if profiling revealed it to be a hotspot then it would be the first thing to strip down."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T08:34:14.493",
"Id": "230686",
"ParentId": "230676",
"Score": "14"
}
},
{
"body": "<p>For small lists of enemies, linearly scanning all of them and computing the distance to the character is sufficient. However, if you have many enemies, a more efficient data structure is needed.</p>\n\n<p>If your list of enemies does not change (or changes less often than you need to find the closest enemy), I would use <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html#scipy.spatial.cKDTree\" rel=\"noreferrer\"><code>scipy.spatial.cKDTree</code></a>. kd-trees take <span class=\"math-container\">\\$\\mathcal{O}(n\\log n)\\$</span> time to build, but afterwards each query only takes <span class=\"math-container\">\\$\\mathcal{O}(\\log n)\\$</span>.</p>\n\n<pre><code>from scipy.spatial import cKDTree as KDTree\n\ndef find_closest_kdtree(character: tuple, enemies: KDTree) -> (int, int):\n \"\"\"\n Finds the closest enemy in enemies\n\n :param character: An (x, y) representing the position of the character\\n\n :param enemies: A KDTree that represent enemies\n\n :return: A tuple (x, y) of the closest enemy\n \"\"\"\n _, i = enemies.query([character], 1)\n return i[0]\n\n\nif __name__ == \"__main__\":\n\n # Test Case #\n\n character = (5, 6)\n enemies = [(1, 2), (3, 4), (7, 6), (11, 4)]\n enemies_tree = KDTree(enemies)\n closest = enemies[find_closest_kdtree(character, enemies_tree)]\n print(closest)\n</code></pre>\n\n<p>If you do regularly need to update the list of enemies (because they are spawned, get killed, move off-screen, etc), you might be able to use a <a href=\"http://toblerity.org/rtree/\" rel=\"noreferrer\">R* tree</a> instead:</p>\n\n<pre><code>from rtree.index import Rtree\n\n\ndef find_closest_rtree(character: tuple, enemies) -> (int, int):\n \"\"\"\n Finds the closest enemy in enemies\n\n :param character: An (x, y) representing the position of the character\\n\n :param enemies: A KDTree that represent enemies\n\n :return: A tuple (x, y) of the closest enemy\n \"\"\"\n return next(enemies.nearest(character, 1, objects='raw'))\n\n\nif __name__ == \"__main__\":\n\n # Test Case #\n\n character = (5, 6)\n enemies = [(1, 2), (3, 4), (7, 6), (11, 4)]\n enemies_tree = Rtree()\n for i, p in enumerate(enemies):\n enemies_tree.insert(i, p+p, p)\n\n closest = find_closest_rtree(character, enemies_tree)\n print(closest)\n</code></pre>\n\n<p>Here is how the different methods compare performance wise, including the implementation using <code>min</code> and your original implementation:</p>\n\n<p><a href=\"https://i.stack.imgur.com/unxds.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/unxds.png\" alt=\"enter image description here\"></a></p>\n\n<p>Note that building all the R* trees for this took multiple minutes, while building all the KDTrees took only a couple of seconds. So you would probably have to rebuild the KDTree quite often for it to be worth it to switch to the R* tree. </p>\n\n<hr>\n\n<p>In case you are interested, this is how I generated that graph:</p>\n\n<pre><code>import numpy as np\nimport pandas as pd\nfrom functools import partial\nimport timeit\nfrom scipy.spatial import cKDTree as KDTree\nfrom rtree.index import Rtree\n\ndef get_time(func, *x):\n timer = timeit.Timer(partial(func, *x))\n t = timer.repeat(repeat=5, number=1)\n return np.min(t), np.std(t) / np.sqrt(len(t))\n\ndef get_times(func, inputs):\n return np.array(list(map(partial(get_time, func), inputs))\n\ndef find_closest(character: tuple, enemies: list) -> (int, int):\n closest_enemy = None\n smallest_distance = 100_000_000 # Set to large number to ensure values can be less #\n for enemy in enemies:\n distance = math.sqrt(math.pow(character[0] - enemy[0], 2) + (math.pow(character[1] - enemy[1], 2)))\n if distance < smallest_distance:\n closest_enemy = (enemy[0], enemy[1])\n smallest_distance = distance\n return closest_enemy\n\ndef find_closest_min(character: tuple, enemies: list) -> (int, int):\n def find_enemy_distance(enemy):\n return math.hypot((character[0] - enemy[0]), (character[1] - enemy[1]))\n return min(enemies, key=find_enemy_distance)\n\ndef find_closest_kdtree(character: tuple, enemies: KDTree) -> (int, int):\n _, i = enemies.query([character], 1)\n return i[0]\n\ndef find_closest_rtree(character: tuple, enemies) -> (int, int):\n return next(enemies.nearest(character, 1, objects='raw'))\n\ndef find_closest_kdtree_with_build(character: tuple, enemies) -> (int, int):\n enemies_tree = KDTree(enemies)\n _, i = enemies_tree.query([character], 1)\n return enemies[i[0]]\n\nif __name__ == \"__main__\":\n character = 5, 6\n x = [list(map(tuple, np.random.randint(-n, n, (n, 2))))\n for n in np.logspace(1, 6, dtype=int)]\n kdtrees = [KDTree(v) for v in x]\n rtrees = []\n for y in x:\n rtrees.append(Rtree())\n for i, v in enumerate(y):\n rtrees[-1].insert(i, v+v, v)\n\n df = pd.DataFrame(list(map(len, x)), columns=[\"x\"])\n df[\"find_closest\"], df[\"find_closest_err\"] = get_times(partial(find_closest, character), x).T\n df[\"find_closest_min\"], df[\"find_closest_min_err\"] = get_times(partial(find_closest_min, character), x).T\n df[\"find_closest_kdtree\"], df[\"find_closest_kdtree_err\"] = get_times(partial(find_closest_kdtree, character), kdtrees).T\n df[\"find_closest_rtree\"], df[\"find_closest_rtree_err\"] = get_times(partial(find_closest_rtree, character), rtrees).T\n df[\"find_closest_kdtree_with_build\"], df[\"find_closest_kdtree_with_build_err\"] = get_times(partial(find_closest_kdtree_with_build, character), x).T\n\n for label in df.columns[1::2]:\n plt.errorbar(df[\"x\"], df[label], yerr=df[label + \"_err\"], fmt='o-', label=label)\n plt.xlabel(\"Number of enemies\")\n plt.ylabel(\"Time [s]\")\n plt.xscale(\"log\")\n plt.yscale(\"log\")\n plt.legend()\n plt.show()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:28:05.900",
"Id": "449621",
"Score": "3",
"body": "Another, minor optimisation - instead of the comparatively expensive series of squares and `sqrt`s a Manhattan distance may very well be sufficient for this purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T13:34:07.763",
"Id": "449623",
"Score": "0",
"body": "The values in the graph... are these single instances of `find_closest()`? Maybe perfoming say... 1000 lookups would provide a more realistic timing? For example, it would show the difference between the original `find_closest()` and the `kdtree_with_build()` implementations better, if the build only has to be performed once for all 1000 calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:01:46.857",
"Id": "449630",
"Score": "0",
"body": "@Baldrickk: Yes, it is one lookup each (actually the minimum of 5 runs with the same inputs). The time with the build only once is the `_kdtree` line, there the building of the tree is not included in the timing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:04:34.290",
"Id": "449632",
"Score": "0",
"body": "@Baldrickk: That sounds like it would constitute its own answer. Incidentally, the KDTree supports this out of the box by using `enemies.query([character], k=1, p=1)` instead of the default value of `p=2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:17:56.960",
"Id": "449633",
"Score": "5",
"body": "@Baldrickk: Manhattan distance can be 41.4% wrong, which might very visible. It's possible to simply remove `sqrt` while comparing distances, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:38:04.073",
"Id": "449635",
"Score": "0",
"body": "@EricDuminil hence the \"_may_\". The sqrt will be the majority of the execution time though, so that will also be a significant improvement."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:51:47.807",
"Id": "230698",
"ParentId": "230676",
"Score": "18"
}
}
] |
{
"AcceptedAnswerId": "230698",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T03:22:31.510",
"Id": "230676",
"Score": "8",
"Tags": [
"python",
"python-3.x"
],
"Title": "Find the closest enemy"
}
|
230676
|
<p>As a spare-time personal project, I'm implementing a set of symmetric-key cryptographic primitives. </p>
<p>One thing I've left vacant for a long time, is the key/state eraser, which I decide to add right now. </p>
<p>I intend it to be a macro, so that it doesn't require any additional object file; the macro should be statement-like (as per <a href="https://stackoverflow.com/q/154136/6230282">this question</a>), so that its usage is consistent with those from other lines. </p>
<p>Here's my current code: </p>
<pre class="lang-c prettyprint-override"><code>#define ERASE_STATES(buf, len) \
do { \
for(uintptr_t i=0; i<len; i++) \
((char *)buf)[i] = 0; \
} while(0)
</code></pre>
<p>There's a few things I'm not entirely confident about. </p>
<ol>
<li><p><code>len</code> is a cardinal and it'd probably be a <code>size_t</code>, but <code>i</code> is an ordinal, should I also use <code>size_t</code>, or change it to some other type for semantic consistency? (I'm using <code>uintptr_t</code> right now.)</p></li>
<li><p>The signedness of the type <code>char</code> is explicitly undefined according to standard, but could it nontheless be used without sacrificing semantic consistency, as a generic type representing a byte when assigning non-negative values to it? </p></li>
<li><p>Anything else I've missed? </p></li>
</ol>
<p><strong>Update</strong></p>
<p>I'm not using <code>memset</code> because I designed my code to be compilable in free-standing environment. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T06:28:13.043",
"Id": "449559",
"Score": "0",
"body": "Doing things you know are *undefined* behaviour and expecting *defined* behaviour isn't going to work. What is your concern in this regard? Have you tested the current code in multiple situations and does it appear to function correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T06:32:54.523",
"Id": "449561",
"Score": "0",
"body": "@Mast I assume you mean my Q2, as it's the only Q with the word \"undefined\" in it. My concern is that (assuming I've casted type correctly) the content of `buf` would end up with non-zero bits, or observable gap didn't get re-initialized."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T06:40:10.420",
"Id": "449564",
"Score": "0",
"body": "@Mast, I've tested the code on my 64-bit macOS Catalina, but I don't currently have a big-endian or 32-bit environment available to me right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:21:34.513",
"Id": "449670",
"Score": "0",
"body": "What's with the loop? A plain old braced block is entirely valid C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T04:27:34.610",
"Id": "449725",
"Score": "1",
"body": "@Reinderien As mentioned in the OP, \"per [this question](https://stackoverflow.com/q/154136/6230282)\"."
}
] |
[
{
"body": "<h1>Q1</h1>\n\n<p><code>uintptr_t</code> is used for representing pointers numerically, so it's not suitable even if the underlying representation is identical to that of <code>size_t</code>, the same can be said for <code>ptrdiff_t</code>. </p>\n\n<p>On the other hand, it's common knowledge that the set of finite ordinals is isomorphic to the set of finite cardinals, so <code>size_t</code> can be your friend here. What's more, the loop condition may be improved by adding a cast to <code>size_t</code> to <code>len</code> to ensure the loop always ends even when the original type of <code>len</code> has greater width than <code>size_t</code> although one should always ensure <code>len</code> has a sane value. Also, the cast would be necessarily present had you actually implement <code>ERASE_STATES</code> as a function. </p>\n\n<p>So use <code>size_t</code>. </p>\n\n<h1>Q2</h1>\n\n<p>If you're really concerned that assigning the literal <code>0</code> to a <code>char</code> would get you a \"negative zero\" in one's complement or signed magnitude representation, then use <code>unsigned char</code> (which is just the same intermediate type used when the standard defined <code>memset</code>). Otherwise, the a world proliferous of two's complement signed integers, a plain <code>char</code> offers better clarity when the value is non-negative. </p>\n\n<p>Also, there's guarantee that <code>char[]</code> is gap-free (unlike <code>uint8_t</code>). </p>\n\n<h1>Q3</h1>\n\n<p>Since it's a macro and not a function, <code>buf</code> and <code>len</code> will be evaluated multiple times during the loop. This limits its usage to lvalues and constant expressions. </p>\n\n<p>Unless you assign arguments to temporary variables. </p>\n\n<h1>Improved Code</h1>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define ERASE_STATES(buf, len) \\\n do { \\\n char *ba = (void *)buf; \\\n size_t l = (size_t)len; \\\n for(size_t i=0; i<l; i++) \\\n ba[i] = 0; \\\n } while(0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T07:17:55.857",
"Id": "449567",
"Score": "1",
"body": "I don't know the answer to this. In the improved code, is the compiler guaranteed to spot that the cast of len to size_t only has to happen once? Or will this spend half its time casting for the check?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T07:25:42.553",
"Id": "449568",
"Score": "0",
"body": "@Josiah, good point, changed answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T07:03:51.600",
"Id": "230682",
"ParentId": "230680",
"Score": "1"
}
},
{
"body": "<p>There is not much code so I won't write much review</p>\n\n<p>The issue that makes me most uneasy is the interface decision, specifically requiring calling code to calculate len in bytes.</p>\n\n<p>If I am in \"trying my best mode\" as a coder, late at night with a stressful customer deadline hanging over me, it'll be all I can manage to remember to clear memory. I will inevitably try to clear an int array of 8 elements with <code>ERASE_STATE(arr, 8)</code>. If I am lucky I will remember to use 32 and add a comment about the 4x8 calculation. I am unlikely to remember to account for the fact that other architectures could have a 16 or 64 bit int.</p>\n\n<p>I would very much prefer a macro that took care of the type sizes for me and left the interface as passing the the natural array size. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T07:32:49.177",
"Id": "230683",
"ParentId": "230680",
"Score": "2"
}
},
{
"body": "<p>There's not much to review here, since it's only a single macro, but there's still room for improvement.</p>\n\n<h2>Don't use a macro</h2>\n\n<blockquote>\n <p>I intend it to be a macro, so that it doesn't require any additional object file</p>\n</blockquote>\n\n<p>If that's the motivation for using a macro, it's based on a misconception. You can get that and avoid the <a href=\"https://stackoverflow.com/questions/9104568/macro-vs-function-in-c\">problems of macros</a>, by defining a static function instead. Consider this code:</p>\n\n<pre><code>#include <stdint.h>\n\n#define ERASE_STATES(buf, len) \\\n do { \\\n for(uintptr_t i=0; i<len; i++) \\\n ((char *)buf)[i] = 0; \\\n } while(0)\n\nunsigned buffer1[11];\nunsigned buffer2[13];\n\nstatic void memclr(void *buf, unsigned len) {\n for (char *b = buf ;len; --len, ++b) {\n *b = 0;\n }\n}\n\nvoid foo1() {\n ERASE_STATES(buffer1, sizeof(buffer1)*sizeof(*buffer1));\n}\n\nvoid foo2() {\n ERASE_STATES(buffer2, sizeof(buffer2)*sizeof(*buffer2));\n}\n\nvoid bar1() {\n memclr(buffer1, sizeof(buffer1)*sizeof(*buffer1));\n}\n\nvoid bar2() {\n memclr(buffer2, sizeof(buffer2)*sizeof(*buffer2));\n}\n\nint main() {\n foo1();\n foo2();\n bar1();\n bar2();\n}\n</code></pre>\n\n<p>Does a modern compiler generate different code for <code>foo1</code> versus <code>bar1</code>? No. It generates the <a href=\"https://godbolt.org/z/MKg6aQ\" rel=\"nofollow noreferrer\">exact same code</a> without requiring any additional libraries or translation units, and without any runtime overhead for function calls. It also does not sacrifice type safety and is easier to debug and maintain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-20T02:12:05.700",
"Id": "450264",
"Score": "0",
"body": "Isn't it against convention to define functions in header files? Also, what about those \"unused static function\" warnings in object files that don't use it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-20T03:09:16.343",
"Id": "450265",
"Score": "0",
"body": "Don’t put a static function in a header file. If it is needed in multiple C files, duplicate it in multiple C files."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-19T19:35:45.887",
"Id": "231016",
"ParentId": "230680",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T06:19:16.207",
"Id": "230680",
"Score": "-1",
"Tags": [
"c",
"cryptography",
"type-safety"
],
"Title": "Implement state eraser for NIST DRBG and other crypto primitives using macro"
}
|
230680
|
<p>I'm writing some OO Python and I would like to know which of these methods is more pythonic, or which is generally better, or faster. This is an accessor for an attribute which is a dictionary.</p>
<p>Method 1: <code>if/else</code></p>
<pre><code>def GetSlot(self, slot_name):
if slot_name in self.Slots:
return self.Slots[slot_name]
else:
return None
</code></pre>
<p>Method 2: <code>try/except</code></p>
<pre><code>def GetSlot(self, slot_name):
try:
return self.Slots[slot_name]
except KeyError:
return None
</code></pre>
<p>I understand that using <code>try/except</code> is better use of duck typing, but will this make a positive impact on performance?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T12:12:26.753",
"Id": "449606",
"Score": "0",
"body": "It's 'Look Before You Leap' LBYL vs 'Easier to Ask for Forgiveness than Permission' EAFP. The latter is probably more Pythonic, but performance doesn't come into it until you apply this to a real problem and start profiling. And that's the problem with this question: the code is two snippets. We don't do snippets. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T12:21:03.143",
"Id": "449607",
"Score": "0",
"body": "Oh yes you're right, sorry. I didn't read the posting rules. I suppose that's why code review exists and this isn't just stack overflow 2. Should I move/remove this question, or leave it as it already has an answer? If it's gonna get struck down by mods I may as well save them the trouble"
}
] |
[
{
"body": "<h1>It depends.</h1>\n\n<p>Mostly, it depends on whether it'll generally be in the dictionary or not. If it's nearly always in the dictionary, then the try/except method would win out, while if it's in there as often as not, then checking would be somewhat faster.</p>\n\n<p>However, python already anticipated your need. There's a better option:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def GetSlot(self, slot_name):\n return self.Slots.get(slot_name)\n</code></pre>\n\n<p>All mappings support get, which has a default optional argument that defaults to None. This should be the best option. However, that said...</p>\n\n<ul>\n<li><code>GetSlot</code> is not a PEP8-compliant name. It should be <code>get_slot</code>.</li>\n<li><code>self.Slots</code> should probably be <code>self.slots</code>.</li>\n<li>NOTE: Since you confirmed in a comment that you are in fact using externally defined names, I think it is best practice to follow those names as well as their naming conventions when appropriate.</li>\n<li>This should probably not be a method at all. In python, accessor functions are somewhat frowned upon. If you really need to do something like this, use <a href=\"https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work\">properties</a>. However, anything wanting to get <code>slot_name</code> from <code>self.Slots</code> should just use <code>self.Slots.get(slot_name)</code>. <em>Even if you're reaching into the object from outside</em>. Java and other languages that advocate getter/setter methods do so because it later allows you to change how it is gotten, but Python is better and doesn't require workarounds like this to influence how you access a variable. <a href=\"https://stackoverflow.com/a/36943813/4331885\">Read more here.</a></li>\n</ul>\n\n<h3>A note on Python getters and setters</h3>\n\n<p>Python <a href=\"https://docs.python.org/3.7/howto/descriptor.html\" rel=\"nofollow noreferrer\">descriptors</a> are a powerful tool. It's not actually an object, it's a protocol of how python retrieves variables when they're used as object attributes. The classic example is python's <code>property</code>, but in truth methods on a class are also descriptors. An object implements this protocol by having <code>__get__</code>, <code>__set__</code> or <code>__delete__</code> methods on it. Not all are required for every type of descriptors - please follow the link for in-depth classification and usages. </p>\n\n<p>What this all means in practice is that python objects can change how they are retrieved. This is impossible in languages like Java, which can cause engineering issues. </p>\n\n<p>Let's first figure out why people use getters and setters in Java, because the reasons they have are quite important.</p>\n\n<p>So I have a class with an attribute that I want to expose to the public for usage.</p>\n\n<p>(NOTE: Java users please don't take offense. I'm writing just Python here since I've honestly never used Java. All my knowledge of it is second-hand at best.)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Point:\n def __init__(self, x, y):\n self.x, self.y = x, y\n self.distance_to_orgin = pythagoras(x, y)\n# Later...\ninstance = Point(a, b)\ninstance.distance_to_orgin \n</code></pre>\n\n<p>Now, everyone can access it. So I publish my library, and everyone's code works fine. </p>\n\n<p>But then, I get a better idea - every point already knows it's x and y, so I can always calculate the distance_to_orgin if I need it. </p>\n\n<p>In Java, I now have a problem. Because to calculate something on retrieval, I NEED a function - but everyone accesses it by attribute access. I cannot make this change in a backwards compatible manner. So, programmers learn to make getter and setter methods. Compare to before:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Point:\n def __init__(self, x, y):\n self.x, self.y = x, y\n self.distance_to_orgin = pythagoras(x, y)\n\n def get_distance_to_orgin(self):\n return self.distance_to_orgin\n\n\n# Later...\ninstance = Point(a, b)\ninstance.get_distance_to_orgin()\n</code></pre>\n\n<p>Now, if I want to change how it works, I can just write a different get_distance_to_orgin method and I can make the change - fully backwards compatible!</p>\n\n<p>So why isn't this a problem in Python?</p>\n\n<p>Because we have descriptors. In 99.9% of cases, the builtin property() does everything you want. I can just amend my class definition like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Point:\n def __init__(self, x, y):\n self.x, self.y = x, y\n # self._distance_to_orgin = pythagoras(x, y) No longer needed\n\n @property\n def distance_to_orgin(self):\n return pythagoras(self.x, self.y)\n\n# Later...\ninstance = Point(a, b)\ninstance.distance_to_orgin\n</code></pre>\n\n<p>And the external usage is <em>exactly</em> the same as it was at the very start, back when we were building a class in a naive way! </p>\n\n<p>So that is why getters and setters are important for many languages, but why we don't need them in Python.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:59:16.443",
"Id": "449591",
"Score": "0",
"body": "Not a crappy answer, this is exactly what I was hoping for. Thank you :) I appreciate your other comments, but unfortunately I'm making a replacement for a module that's already in place, so I need to copy their naming for my code to slot in without changing anything other than the import statement :// The module I'm replacing/emulating is PyCLIPS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:24:56.287",
"Id": "449595",
"Score": "0",
"body": "A question related to your second point - Is using setter methods also frowned upon? In my case each `Slot` may or may not have strict allowed values. Each `Slot` object has an attribute `AllowedValues` which is a list that may be empty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:33:36.470",
"Id": "449597",
"Score": "0",
"body": "That explanation about getter/setters is a bit to long for a comment, I'll edit it in. But if you're building on/wrapping a library with another style, then keeping that style is IMO better than twisting yourself to obey PEP8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T12:09:19.537",
"Id": "449605",
"Score": "0",
"body": "I see now! I don't think I've ever found a reason for using descriptors justified that clearly before, thank you :) And I suppose I could always define `SetSlot(self, name, value)` to call this property if I want both methods available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T14:49:35.787",
"Id": "449637",
"Score": "0",
"body": "Since there's nothing in your question about setters: I'd just use `self.Slots[slot_name] = value`, and try/except around where you use it. No real need for a setter either. And if you don't like exceptions, just check from outside: `if value in self.Slots[slot_name].AllowedValues: self.Slots[slot_name] = value`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T16:06:56.237",
"Id": "449646",
"Score": "0",
"body": "In the future, please refrain from answering off-topic questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T06:53:09.317",
"Id": "449737",
"Score": "0",
"body": "@Mast I thought this one was ok, but I guess I was wrong then. I'll keep an eye out."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:47:13.930",
"Id": "230697",
"ParentId": "230691",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230697",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:22:35.377",
"Id": "230691",
"Score": "0",
"Tags": [
"python"
],
"Title": "Python - 'if name in dict:' OR 'try:/except:'"
}
|
230691
|
<p>I'm toying with the idea of writing a "bigint" library in 6502
assembler that would handle variable-length integers up to 255 bytes
long. Since this would be unit tested using pytest, and to help wrap
my mind around the representation issues, I've come up with a function
in Python that takes a decmial integer and deposits it into (emulated)
memory as its binary representation: as a length byte followed by the
bytes of the value from least to most significant. (The 6502 is
little-endian.) This could be used, for example, to generate a couple
of inputs to test an "add" or "multiply" function.</p>
<p>As background, the <code>M</code> or <code>Machine</code> object here is the emulated CPU
and RAM, with the RAM as an array of unsigned 0-255 integers. It
offers a <code>deposit(addr, list)</code> method to put values into memory,
<code>byte(addr)</code> to retrive a single byte, and <code>bytes(addr, len)</code> to
retrieve multiple bytes. (This is actually a wrapper around a
<code>py65.devices.mpu6502</code> from <a href="https://github.com/mnaberez/py65" rel="noreferrer">py65</a>; all the code is in my <a href="https://github.com/0cjs/8bitdev" rel="noreferrer">8bitdev</a>
repo if you're curious.)</p>
<pre class="lang-py prettyprint-override"><code>from testmc.m6502 import Machine, Registers as R, Instructions as I
import pytest
@pytest.fixture
def M():
M = Machine()
M.load('.build/obj/objects')
return M
def depint(M, addr, value):
''' Deposit a bigint in locations starting at `addr`.
`addr` contains the length of the following bytes,
which hold the value from LSB to MSB.
'''
next = addr + 1 # Skip length byte; filled in at end
if value >= 0: # Positive number; fill byte by byte
while next == addr+1 or value > 0:
value, byte = divmod(value, 0x100)
M.deposit(next, [byte])
next += 1
if byte >= 0x80: # MSbit = 1; sign in additional byte
M.deposit(next, [0x00])
next += 1
else: # Negative: fill with two's complement values
value = abs(value+1) # two's complement = -(n+1)
while next == addr+1 or value > 0:
value, byte = divmod(value, 0x100)
byte = 0xFF - byte # two's complement
M.deposit(next, [byte])
next += 1
if byte < 0x80: # MSbit = 0; sign in additional byte
M.deposit(next, [0xFF])
next += 1
# Store the length
M.deposit(addr, [next - (addr + 1)])
@pytest.mark.parametrize('value, bytes', [
(0, [0x00]),
(1, [0x01]),
(127, [0x7F]),
(128, [0x80, 0x00]),
(255, [0xFF, 0x00]),
(256, [0x00, 0x01]),
(0x40123456, [0x56, 0x34, 0x12, 0x40]),
(0xC0123456, [0x56, 0x34, 0x12, 0xC0, 0x00]),
(-1, [0xFF]),
(-128, [0x80]),
(-129, [0x7F, 0xFF]),
(-255, [0x01, 0xFF]),
(-256, [0x00, 0xFF]),
(-257, [0xFF, 0xFE]),
(0-0x40123456, [0xFF-0x56+1, 0xFF-0x34, 0xFF-0x12, 0xFF-0x40]),
(0-0xC0123456, [0xFF-0x56+1, 0xFF-0x34, 0xFF-0x12, 0xFF-0xC0, 0xFF]),
])
def test_depint(M, value, bytes):
print('DEPOSIT', value, 'expecting', bytes)
addr = 30000 # arbitrary location for deposit
size = len(bytes) + 2 # length byte + value + guard byte
M.deposit(addr, [222] * size) # 222 ensures any 0s really were written
depint(M, addr, value)
bvalue = M.bytes(addr+1, len(bytes))
assert (len(bytes), bytes, 222) \
== (M.byte(addr), bvalue, M.byte(addr+size-1))
# Test against Python's conversion
assert list(value.to_bytes(len(bytes), 'little', signed=True)) \
== bvalue
</code></pre>
<p>Things you might consider when reviewing:</p>
<ul>
<li>Is it actually correct? Do the tests provide sufficient coverage?
(FWIW, in this particular implementation I don't feel the need to
test for overflow, since all input values would be fully under my
control.)</li>
<li>Is there a clearer way to describe the tests?</li>
<li>The <code>next == addr+1</code> condition in the <code>while</code> loops is a bit
awkward; is there a better way of handling this? The obvious thing
would be to use a <code>do</code> loop (the first time I can recall wanting one
in a <em>long</em> time), but Python doesn't have them.</li>
<li>Perhaps it would make more sense just to use Python's <code>bit_length()</code>
and <code>to_bytes()</code> to handle the conversion.</li>
<li>Regarding how useful this is, it's occurred to me that I'll probably
want a reader routine (in 6502 assembler) to do this same ASCII
decmal → bigint conversion, which would mean I could just unit test
it using Python's <code>to_bytes()</code> and use that routine in unit tests
for add, multiply, etc. routines. The only issue might be that it
could be a lot slower in 6502 emulation than using the native Python
library would be.</li>
</ul>
|
[] |
[
{
"body": "<h2>Name shadowing</h2>\n\n<pre><code>next = addr + 1 # Skip length byte; filled in at end\n</code></pre>\n\n<p>Don't call a variable <code>next</code>. That's already a built-in. You could use <code>next_addr</code> for example.</p>\n\n<p>Similarly,</p>\n\n<pre><code>def test_depint(M, value, bytes):\n</code></pre>\n\n<p>should not use the built-in name <code>bytes</code>. I'm not completely clear on what it does in context, but maybe <code>message</code>, <code>deposit</code>, <code>deposit_span</code>, etc. are possible.</p>\n\n<h2>Masking</h2>\n\n<pre><code> value, byte = divmod(value, 0x100)\n</code></pre>\n\n<p>Are you sure that this shouldn't just be</p>\n\n<pre><code>byte = value & 0xFF\nvalue >>= 8\n</code></pre>\n\n<h2>Assert decomposition</h2>\n\n<blockquote>\n <p>Is there a clearer way to describe the tests?</p>\n</blockquote>\n\n<pre><code>assert (len(bytes), bytes, 222) \\\n == (M.byte(addr), bvalue, M.byte(addr+size-1))\n</code></pre>\n\n<p>Don't combine this. Tests are more useful if you can see exactly which term in an assertion failed:</p>\n\n<pre><code>assert len(bytes) == M.byte(addr)\nassert bytes == bvalue\nassert M.byte(addr+size-1) == 222\n</code></pre>\n\n<h2>f-strings</h2>\n\n<pre><code>print('DEPOSIT', value, 'expecting', bytes)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>print(f'DEPOSIT {value} expecting {bytes}')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:28:14.343",
"Id": "449676",
"Score": "1",
"body": "Can you suggest better names for the ones you don't like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:40:59.780",
"Id": "449679",
"Score": "0",
"body": "Sure thing; edited"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:41:01.227",
"Id": "449680",
"Score": "0",
"body": "Regarding `value &= ~0xFF`; that does something different from the `divmod()`: the latter returns the _quotient_ and remainder, not the original value minus the remainder. If I merely subtracted the remainder from `value`, on the next round there would be no further remainder (it's already been subtracted) and `value` would stay the same forever, causing an infinite loop. (I think; it's late here and I'm a bit tired.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:42:06.457",
"Id": "449681",
"Score": "1",
"body": "My mistake. That should have been a bitshift."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:51:22.053",
"Id": "449683",
"Score": "0",
"body": "`bytes` is the list of bytes that were deposited in memory. I'm not entirely clear with the issues on using my own variable names that shadow built-ins; variable names (though perhaps not so frequently built-ins) are shadowed all the time even in the Python core source, both as [local vars](https://github.com/python/cpython/blob/3.7/Lib/pdb.py#L403-L404) and in public interfaces ([nntplib](https://docs.python.org/3/library/nntplib.html?highlight=next#nntplib.NNTP.next), [tarfile](https://docs.python.org/3/library/tarfile.html?highlight=next#tarfile.TarFile.next)). What does `next` shadow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:52:05.163",
"Id": "449684",
"Score": "1",
"body": "Combining the tests is very useful. If one of the values fails, you can look at the others to see more context. In your variant, the error message is \"40 bytes expected, got only 36, but I don't tell you anything about their values\", which is it not helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:53:40.470",
"Id": "449686",
"Score": "1",
"body": "https://docs.python.org/3/library/functions.html#next"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:54:07.343",
"Id": "449687",
"Score": "0",
"body": "Re \"don't combine\": I combined the three so I can see all of values if any one or more of them fails; I found this to make debugging significantly easier. It does show you exactly which term failed (and which ones didn't); the position in the tuple shows it. (With enough `-v` options, pytest prints out two lines and points out the differences within them.) I believe Roland is [pointing out the same thing](https://codereview.stackexchange.com/questions/230693/bigint-decimal-to-twos-complement-binary-list-of-bytes-in-python/230717#comment449684_230717)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:58:06.363",
"Id": "449689",
"Score": "0",
"body": "It's an awkward way of getting context. If you're _actually_ debugging, your debugger can break at the point where the assertion failure is raised, and you'll have all of the context you need. Otherwise, to see the parameter values, see https://stackoverflow.com/questions/57136918/pytest-show-parameter-values-in-failure-report"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:58:45.873",
"Id": "449690",
"Score": "0",
"body": "Ah, re the mask and bitshift: yes, I think that's more clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:01:06.200",
"Id": "449691",
"Score": "0",
"body": "Re the f-strings: I like them better, but I still am using Python 3.5 on some systems which I think does not have them, does it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:01:59.980",
"Id": "449692",
"Score": "0",
"body": "That's unfortunately true :/ https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:15:45.180",
"Id": "230717",
"ParentId": "230693",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:26:04.627",
"Id": "230693",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"number-systems"
],
"Title": "\"Bigint\" decimal to two's complement binary list of bytes in Python"
}
|
230693
|
<p>I have implemented a BFS. Does this look like a proper implementation of BFS in Python 3? And if you think something needs to be improved, say it.</p>
<pre><code>class Node(object):
def __init__(self, name):
self.name = name
self.adjacencyList = []
self.visited = False
self.predecessor = None
class BreadthFirstSearch(object):
def bfs(self, startNode):
queue = []
queue.append(startNode)
startNode.visited = True
# BFS -> queue
while queue:
actualNode = queue.pop(0)
print(actualNode.name)
for n in actualNode.adjacencyList:
if not n.visited:
n.visited = True
queue.append(n)
node1 = Node("A")
node2 = Node("B")
node3 = Node("C")
node4 = Node("D")
node5 = Node("E")
node1.adjacencyList.append(node2)
node1.adjacencyList.append(node3)
node2.adjacencyList.append(node4)
node4.adjacencyList.append(node5)
bfs = BreadthFirstSearch()
bfs.bfs(node1)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:52:26.627",
"Id": "449770",
"Score": "0",
"body": "I'm a little confused. When doing a search, shouldn't you be searching for something?"
}
] |
[
{
"body": "<p>There are a few <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> issues:</p>\n\n<ul>\n<li>In Python3, class definitions have been overhauled a bit, and one can simply do <code>class Node:</code> instead of <code>class Node(object):</code>. </li>\n<li>The spacing is a bit all over the place: there should be two blank lines between class definitions, and I find the spacing within <code>def bfs(self, start_node)</code> difficult.</li>\n<li>The naming convention is to be snake_cased.</li>\n</ul>\n\n<p>To address this type of issues, have a look at <a href=\"http://flake8.pycqa.org/en/latest/index.html#quickstart\" rel=\"nofollow noreferrer\">flake8</a> or <a href=\"https://black.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">black</a></p>\n\n<p><code>Node.visited</code> is problematic.<br>\nFirst, if the node is in several trees, you may not visit it if it's already been visited in another tree, or even in the same tree when doing a second search.</p>\n\n<p>The fact that you have visited a node is part of the algorithm, and not so much a property of a <code>Node</code>. </p>\n\n<p>With a few tweaks you can rely on <code>queue</code> only, or have a second list of visited:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>visited = []\nfor node in current_node.adjacency_list:\n if not node in visited:\n visited.append(node)\n</code></pre>\n\n<p>The comment <code>#BFS -> queue</code> is not very telling.</p>\n\n<p>Lastly, this is iterating through the tree, and not doing actual search. Where's the exit condition? What's returned? What should I get when searching for <code>node4</code> from <code>node1</code>? <code>node4</code> from <code>node3</code>? <code>node3</code> from <code>node2</code>?</p>\n\n<p>It's not quite done...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:43:53.620",
"Id": "230704",
"ParentId": "230694",
"Score": "4"
}
},
{
"body": "<h3>collections.deque()</h3>\n\n<p>The documentation for <code>collections.deque()</code> says it is more efficient than a list when appending/popping elements. (Popping the 0th element from a list, may cause the rest of the list to be copied forward one space.) So use a deque instead of a list for the queue.</p>\n\n<h3>set()</h3>\n\n<p>Use a <code>set()</code> instead of a <code>list()</code> for the adjacent nodes. Also use a set for the visited nodes. This lets you do set difference to determine what nodes to add to the queue.</p>\n\n<pre><code>from collections import deque\n\ndef bfs(self, startNode):\n\n visited_set = set(startNode)\n queue = deque(visited_set)\n\n while queue:\n\n actual_node = queue.popleft()\n print(actual_node.name)\n\n unvisited_nodes = actual_node.adjacency_set - visited_set\n for node in unvisited_nodes:\n\n # here is where you test to see if `node` is the search target\n # and take some action if it is.\n\n # otherwise append all the unvisited nodes to the queue and continue searching\n queue.extend(unvisited)\n visited_set |= unvisited\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T23:48:31.510",
"Id": "230727",
"ParentId": "230694",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230704",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:32:02.407",
"Id": "230694",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"graph",
"breadth-first-search"
],
"Title": "Breadth-first search(BFS) Implementation in Python 3"
}
|
230694
|
<p>I have a solution for making the .kml file transparent in the Leaflet Map. The working code looks like this:</p>
<pre><code>L.KML = L.FeatureGroup.extend({
initialize: function (kml) {
this._kml = kml;
this._layers = {};
if (kml) {
this.addKML(kml);
}
},
addKML: function (xml) {
var layers = L.KML.parseKML(xml);
if (!layers || !layers.length) return;
for (var i = 0; i < layers.length; i++) {
this.fire('addlayer', {
layer: layers[i]
});
this.addLayer(layers[i]);
}
this.latLngs = L.KML.getLatLngs(xml);
this.fire('loaded');
},
latLngs: []
});
L.Util.extend(L.KML, {
parseKML: function (xml) {
var style = this.parseStyles(xml);
this.parseStyleMap(xml, style);
var el = xml.getElementsByTagName('Folder');
var layers = [], l;
for (var i = 0; i < el.length; i++) {
if (!this._check_folder(el[i])) { continue; }
l = this.parseFolder(el[i], style);
if (l) { layers.push(l); }
}
el = xml.getElementsByTagName('Placemark');
for (var j = 0; j < el.length; j++) {
if (!this._check_folder(el[j])) { continue; }
l = this.parsePlacemark(el[j], xml, style);
if (l) { layers.push(l); }
}
el = xml.getElementsByTagName('GroundOverlay');
for (var k = 0; k < el.length; k++) {
l = this.parseGroundOverlay(el[k]);
if (l) { layers.push(l); }
}
return layers;
},
// Return false if e's first parent Folder is not [folder]
// - returns true if no parent Folders
_check_folder: function (e, folder) {
e = e.parentNode;
while (e && e.tagName !== 'Folder')
{
e = e.parentNode;
}
return !e || e === folder;
},
parseStyles: function (xml) {
var styles = {};
var sl = xml.getElementsByTagName('Style');
for (var i=0, len=sl.length; i<len; i++) {
var style = this.parseStyle(sl[i]);
if (style) {
var styleName = '#' + style.id;
styles[styleName] = style;
}
}
return styles;
},
parseStyle: function (xml) {
var style = {}, poptions = {}, ioptions = {}, el, id;
var attributes = {color: true, width: true, Icon: true, href: true, hotSpot: true};
function _parse (xml) {
var options = {};
for (var i = 0; i < xml.childNodes.length; i++) {
var e = xml.childNodes[i];
var key = e.tagName;
if (!attributes[key]) { continue; }
if (key === 'hotSpot')
{
for (var j = 0; j < e.attributes.length; j++) {
options[e.attributes[j].name] = e.attributes[j].nodeValue;
}
} else {
var value = e.childNodes[0].nodeValue;
if (key === 'color') {
options.opacity = parseInt(value.substring(0, 2), 16) / 255.0;
options.color = '#' + value.substring(6, 8) +
value.substring(4, 6) + value.substring(2, 4);
} else if (key === 'width') {
options.weight = value;
} else if (key === 'Icon') {
ioptions = _parse(e);
if (ioptions.href) { options.href = ioptions.href; }
} else if (key === 'href') {
options.href = value;
}
}
}
return options;
}
el = xml.getElementsByTagName('LineStyle');
if (el && el[0]) { style = _parse(el[0]); }
el = xml.getElementsByTagName('PolyStyle');
if (el && el[0]) { poptions = _parse(el[0]); }
if (poptions.color) { style.fillColor = poptions.color; }
if (poptions.opacity) { style.fillOpacity = poptions.opacity; }
el = xml.getElementsByTagName('IconStyle');
if (el && el[0]) { ioptions = _parse(el[0]); }
if (ioptions.href) {
style.icon = new L.KMLIcon({
iconUrl: ioptions.href,
shadowUrl: null,
anchorRef: {x: ioptions.x, y: ioptions.y},
anchorType: {x: ioptions.xunits, y: ioptions.yunits}
});
}
id = xml.getAttribute('id');
if (id && style) {
style.id = id;
}
return style;
},
parseStyleMap: function (xml, existingStyles) {
var sl = xml.getElementsByTagName('StyleMap');
for (var i = 0; i < sl.length; i++) {
var e = sl[i], el;
var smKey, smStyleUrl;
el = e.getElementsByTagName('key');
if (el && el[0]) { smKey = el[0].textContent; }
el = e.getElementsByTagName('styleUrl');
if (el && el[0]) { smStyleUrl = el[0].textContent; }
if (smKey === 'normal')
{
existingStyles['#' + e.getAttribute('id')] =
existingStyles[smStyleUrl];
}
}
return;
},
parseFolder: function (xml, style) {
var el, layers = [], l;
el = xml.getElementsByTagName('Folder');
for (var i = 0; i < el.length; i++) {
if (!this._check_folder(el[i], xml)) { continue; }
l = this.parseFolder(el[i], style);
if (l) { layers.push(l); }
}
el = xml.getElementsByTagName('Placemark');
for (var j = 0; j < el.length; j++) {
if (!this._check_folder(el[j], xml)) { continue; }
l = this.parsePlacemark(el[j], xml, style);
if (l) { layers.push(l); }
}
el = xml.getElementsByTagName('GroundOverlay');
for (var k = 0; k < el.length; k++) {
if (!this._check_folder(el[k], xml)) { continue; }
l = this.parseGroundOverlay(el[k]);
if (l) { layers.push(l); }
}
if (!layers.length) { return; }
if (layers.length === 1) { return layers[0]; }
return new L.FeatureGroup(layers);
},
parsePlacemark: function (place, xml, style, options) {
var h, i, j, k, el, il, opts = options || {};
el = place.getElementsByTagName('styleUrl');
for (i = 0; i < el.length; i++) {
var url = el[i].childNodes[0].nodeValue;
for (var a in style[url]) {
opts[a] = style[url][a];
}
}
il = place.getElementsByTagName('Style')[0];
if (il) {
var inlineStyle = this.parseStyle(place);
if (inlineStyle) {
for (k in inlineStyle) {
opts[k] = inlineStyle[k];
}
}
}
var multi = ['MultiGeometry', 'MultiTrack', 'gx:MultiTrack'];
for (h in multi) {
el = place.getElementsByTagName(multi[h]);
for (i = 0; i < el.length; i++) {
return this.parsePlacemark(el[i], xml, style, opts);
}
}
var layers = [];
var parse = ['LineString', 'Polygon', 'Point', 'Track', 'gx:Track'];
for (j in parse) {
var tag = parse[j];
el = place.getElementsByTagName(tag);
for (i = 0; i < el.length; i++) {
var l = this['parse' + tag.replace(/gx:/, '')](el[i], xml, opts);
if (l) { layers.push(l); }
}
}
if (!layers.length) {
return;
}
var layer = layers[0];
if (layers.length > 1) {
layer = new L.FeatureGroup(layers);
}
var name, descr = '';
el = place.getElementsByTagName('name');
if (el.length && el[0].childNodes.length) {
name = el[0].childNodes[0].nodeValue;
}
el = place.getElementsByTagName('description');
for (i = 0; i < el.length; i++) {
for (j = 0; j < el[i].childNodes.length; j++) {
descr = descr + el[i].childNodes[j].nodeValue;
}
}
if (name) {
layer.on('add', function () {
layer.bindPopup('<h2>' + name + '</h2>' + descr, { className:
'kml-popup'});
});
}
return layer;
},
parseCoords: function (xml) {
var el = xml.getElementsByTagName('coordinates');
return this._read_coords(el[0]);
},
parseLineString: function (line, xml, options) {
var coords = this.parseCoords(line);
if (!coords.length) { return; }
return new L.Polyline(coords, options);
},
parseTrack: function (line, xml, options) {
var el = xml.getElementsByTagName('gx:coord');
if (el.length === 0) { el = xml.getElementsByTagName('coord'); }
var coords = [];
for (var j = 0; j < el.length; j++) {
coords = coords.concat(this._read_gxcoords(el[j]));
}
if (!coords.length) { return; }
return new L.Polyline(coords, options);
},
parsePoint: function (line, xml, options) {
var el = line.getElementsByTagName('coordinates');
if (!el.length) {
return;
}
var ll = el[0].childNodes[0].nodeValue.split(',');
return new L.KMLMarker(new L.LatLng(ll[1], ll[0]), options);
},
parsePolygon: function (line, xml, options) {
var el, polys = [], inner = [], i, coords;
el = line.getElementsByTagName('outerBoundaryIs');
for (i = 0; i < el.length; i++) {
coords = this.parseCoords(el[i]);
if (coords) {
polys.push(coords);
}
}
el = line.getElementsByTagName('innerBoundaryIs');
for (i = 0; i < el.length; i++) {
coords = this.parseCoords(el[i]);
if (coords) {
inner.push(coords);
}
}
if (!polys.length) {
return;
}
if (options.fillColor) {
options.fill = true;
}
if (polys.length === 1) {
return new L.Polygon(polys.concat(inner), options);
}
return new L.MultiPolygon(polys, options);
},
getLatLngs: function (xml) {
var el = xml.getElementsByTagName('coordinates');
var coords = [];
for (var j = 0; j < el.length; j++) {
// text might span many childNodes
coords = coords.concat(this._read_coords(el[j]));
}
return coords;
},
_read_coords: function (el) {
var text = '', coords = [], i;
for (i = 0; i < el.childNodes.length; i++) {
text = text + el.childNodes[i].nodeValue;
}
text = text.split(/[\s\n]+/);
for (i = 0; i < text.length; i++) {
var ll = text[i].split(',');
if (ll.length < 2) {
continue;
}
coords.push(new L.LatLng(ll[1], ll[0]));
}
return coords;
},
_read_gxcoords: function (el) {
var text = '', coords = [];
text = el.firstChild.nodeValue.split(' ');
coords.push(new L.LatLng(text[1], text[0]));
return coords;
},
parseGroundOverlay: function (xml) {
var latlonbox = xml.getElementsByTagName('LatLonBox')[0];
var bounds = new L.LatLngBounds(
[
latlonbox.getElementsByTagName('south')[0].childNodes[0].nodeValue,
latlonbox.getElementsByTagName('west')[0].childNodes[0].nodeValue
],
[
latlonbox.getElementsByTagName('north')[0].childNodes[0].nodeValue,
latlonbox.getElementsByTagName('east')[0].childNodes[0].nodeValue
]
);
var attributes = {Icon: true, href: true, color: true};
function _parse (xml) {
var options = {}, ioptions = {};
for (var i = 0; i < xml.childNodes.length; i++) {
var e = xml.childNodes[i];
var key = e.tagName;
if (!attributes[key]) { continue; }
var value = e.childNodes[0].nodeValue;
if (key === 'Icon') {
ioptions = _parse(e);
if (ioptions.href) { options.href = ioptions.href; }
} else if (key === 'href') {
options.href = value;
} else if (key === 'color') {
options.opacity = parseInt(value.substring(0, 2), 16) / 255.0;
options.color = '#' + value.substring(6, 8) + value.substring(4, 6) + value.substring(2, 4);
}
}
return options;
}
var options = {};
options = _parse(xml);
if (latlonbox.getElementsByTagName('rotation')[0] !== undefined) {
var rotation = latlonbox.getElementsByTagName('rotation')[0].childNodes[0].nodeValue;
options.rotation = parseFloat(rotation);
}
return new L.RotatedImageOverlay(options.href, bounds, {opacity: options.opacity, angle: options.rotation});
}
});
L.KMLIcon = L.Icon.extend({
options: {
iconSize: [32, 32],
iconAnchor: [16, 16],
},
_setIconStyles: function (img, name) {
L.Icon.prototype._setIconStyles.apply(this, [img, name]);
if( img.complete ) {
this.applyCustomStyles( img )
} else {
img.onload = this.applyCustomStyles.bind(this,img)
}
},
applyCustomStyles: function(img) {
var options = this.options;
this.options.popupAnchor = [0,(-0.83*img.height)];
if (options.anchorType.x === 'fraction')
img.style.marginLeft = (-options.anchorRef.x * img.width) + 'px';
if (options.anchorType.y === 'fraction')
img.style.marginTop = ((-(1 - options.anchorRef.y) * img.height) + 1) + 'px';
if (options.anchorType.x === 'pixels')
img.style.marginLeft = (-options.anchorRef.x) + 'px';
if (options.anchorType.y === 'pixels')
img.style.marginTop = (options.anchorRef.y - img.height + 1) + 'px';
}
});
L.KMLMarker = L.Marker.extend({
options: {
icon: new L.KMLIcon.Default()
}
});
// Inspired by
https://github.com/bbecquet/Leaflet.PolylineDecorator/tree/master/src
L.RotatedImageOverlay = L.ImageOverlay.extend({
options: {
angle: 0
},
_reset: function () {
L.ImageOverlay.prototype._reset.call(this);
this._rotate();
},
_animateZoom: function (e) {
L.ImageOverlay.prototype._animateZoom.call(this, e);
this._rotate();
},
_rotate: function () {
if (L.DomUtil.TRANSFORM) {
// use the CSS transform rule if available
this._image.style[L.DomUtil.TRANSFORM] += ' rotate(' +
this.options.angle + 'deg)';
} else if (L.Browser.ie) {
// fallback for IE6, IE7, IE8
var rad = this.options.angle * (Math.PI / 180),
costheta = Math.cos(rad),
sintheta = Math.sin(rad);
this._image.style.filter += '
progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\', M11=' +
costheta + ', M12=' + (-sintheta) + ', M21=' + sintheta + ', M22=' + costheta + ')';
}
},
getBounds: function () {
return this._bounds;
}
});
// ---------- end L.KML -----------------------------
var myKML = '<?xml version="1.0" encoding="UTF-8"?>' +
'<kml xmlns="http://www.opengis.net/kml/2.2"
xmlns:gx="http://www.google.com/kml/ext/2.2"
xmlns:kml="http://www.opengis.net/kml/2.2"
xmlns:atom="http://www.w3.org/2005/Atom">' +
'<Document>' +
'<GroundOverlay>' +
'<name>Coventry.tif</name>' +
'<description>http://localhost/testc/Coventry.tif</description>' +
'<Icon>' +
'<href>https://i.imgur.com/58CbNhB.png</href>' +
'<viewBoundScale>0.75</viewBoundScale>' +
'</Icon>' +
'<color>55ffffff</color>' +
'<LatLonBox>' +
'<north>52.39388512224325</north>' +
'<south>52.39299906007814</south>' +
'<east>-1.458241039649089</east>' +
'<west>-1.460061203494303</west>' +
'</LatLonBox>' +
'</GroundOverlay>' +
'<GroundOverlay>' +
'<name>Coventry2.tif</name>' +
'<description>http://localhost/testc/Coventry.tif2</description>' +
'<Icon>' +
'<href>https://i.imgur.com/58CbNhB.png</href>' +
'<viewBoundScale>0.75</viewBoundScale>' +
'<color>00ff6633</color>' +
'</Icon>' +
'<LatLonBox>' +
'<north>52.39299906007814</north>' +
'<south>52.39199906007814</south>' +
'<east>-1.458241039649089</east>' +
'<west>-1.460061203494303</west>' +
'</LatLonBox>' +
'</GroundOverlay>' +
'</Document>' +
'</kml>';
parser = new DOMParser();
kml = parser.parseFromString(myKML,"text/xml");
track = new L.KML(kml);
map.addLayer(track);
const bounds = track.getBounds();
map.fitBounds( bounds );
sldOpacity.onchange = function() {
document.getElementById('image-opacity').innerHTML = this.value;
track.setStyle({fillOpacity: this.value});
}
</code></pre>
<p>Whereas the 1st part code of the L.KML.js, that belongs to the leaflet-kml plugin based here:</p>
<p><a href="https://github.com/windycom/leaflet-kml" rel="nofollow noreferrer">https://github.com/windycom/leaflet-kml</a></p>
<p>and can be attached as an internal script.</p>
<p>then an another section of the code must be inside ther main script. I am not convinced to the form. Here I have to separate each single line of the XML code, punctuating it line be line.
Is it possible to make a direct fetch of the .kml file as per the code below:</p>
<pre><code> var track
var kml = fetch('Coventry.kml')
.then( res => res.text() )
.then( kmltext => {
// Create new kml overlay
parser = new DOMParser();
kml = parser.parseFromString(kmltext,"text/xml");
track = new L.KML(kml);
//console.log(kml)
//const track = new L.KML(kml)
map.addLayer(track)
// Adjust map to show the kml
const bounds = track.getBounds()
map.fitBounds( bounds )
});
</code></pre>
<p>in order to avoid typing each single line of the .kml file?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T05:55:02.780",
"Id": "452094",
"Score": "0",
"body": "“_Here I have to separate each single line of the XML code, punctuating it line be line._” Can you [edit] your post and better explain what that means? Does it have to do with how `myKML` is parsed?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:35:35.527",
"Id": "230695",
"Score": "2",
"Tags": [
"javascript",
"xml"
],
"Title": "Changing opacity of KML file (with icon linked) fetched in the Leaflet Map"
}
|
230695
|
<p>We faced an issue where URLs had a wrong "subfolder" in its URL, so e.g. </p>
<pre><code>example.com/match1/randomgenerated
</code></pre>
<p>should have been</p>
<pre><code>example.com/rewritewiththis/randomgenerated
</code></pre>
<p>We currently use this code for redirecting URLs that (maybe it could be that it only starts at urls that are "bad"):</p>
<pre><code>$oldurl = JUri::getInstance();
$newurl = str_replace(['match1','match2','match3'], 'rewritewiththis', $oldurl);
$bad_urls = array('match1','match2','match3');
foreach($bad_urls as $bad_url){
if(strpos($oldurl, $bad_url) !== false) {
exit(header("Location: $newurl", true, 301));
}
}
</code></pre>
<p>We use the <code>$newurl</code> also for things like this (this rewrites the generated URLs to use a correct URL and prevent duplicate content):</p>
<pre><code>$oldurl = $this->getRoute($event->url_query . '&Itemid=' . $request->query->page_id)->toString();
$data['url'] = str_replace('match1', 'rewritewiththis', $oldurl);
</code></pre>
<p>Are there better options to do this are are is this already a good way to solve this issue?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T22:16:36.853",
"Id": "449704",
"Score": "0",
"body": "If this is a Joomla script, you might like to ask at [joomla.se] Stack Exchange -- where folks with intimate knowledge about the CMS can tell you about pre-scripted functionalities and best practices within the CMS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T06:58:03.387",
"Id": "449738",
"Score": "0",
"body": "@mickmackusa yes, this was about Joomla. The issue here is that we don't have such a deep knowledge of the component, as we didn't program it fully. The URL generation is one of this, that we didn't change. But thanks for the link to the Joomla Stack Exchange. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T07:07:02.327",
"Id": "449740",
"Score": "0",
"body": "We have some pretty smart cookies over there. I recommend a cross post."
}
] |
[
{
"body": "<p>I think it looks good, a little verbose. Could be simplified to this</p>\n\n<pre><code>$oldurl = JUri::getInstance();\n$bad_urls = ['match1','match2','match3'];\n$newurl = str_replace($bad_urls, 'rewritewiththis', $oldurl);\n\nif(in_array($oldurl, $bad_urls))\n exit(header(\"Location: $newurl\", true, 301));\n</code></pre>\n\n<p>If you need to use something like this in many locations, or you need to elaborate on what are considered bad urls a router system/class may be a better way to go.</p>\n\n<p>If you're asking if there's a different way to re-route without using <code>header()</code> I don't think there is. Any router system I have seen uses <code>header()</code> to re-route, no matter how much code surrounds and abstracts them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T16:15:07.393",
"Id": "230710",
"ParentId": "230699",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230710",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T10:53:14.800",
"Id": "230699",
"Score": "2",
"Tags": [
"php",
"url-routing",
"joomla"
],
"Title": "PHP code for blacklisting and rewriting/redirecting URLs"
}
|
230699
|
<p>My Linux kernel version is</p>
<pre class="lang-none prettyprint-override"><code>Linux version 5.0.0-29-generic
</code></pre>
<p>I'm currently learning how to write kernel modules for Linux and implemented this simple module which creates a new procfs entry and allows some data to be read from it.</p>
<p>The module consists of the following files:</p>
<p><code>init.c</code>:</p>
<pre><code>#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include "pfs_regfile.h"
MODULE_LICENSE("GPL");
static struct proc_dir_entry *pde_regfile;
static struct file_operations fops_regfile = {
.owner = THIS_MODULE,
.open = pfs_open,
.read = pfs_device_read,
.release = pfs_release
};
static int __init init_md(void){
pde_regfile = proc_create(PROC_REGFILE_NAME, 0, NULL, &fops_regfile);
if(!pde_regfile){
remove_proc_entry(PROC_REGFILE_NAME, NULL);
printk(KERN_ALERT "Error: could not initialize procfs entry /proc/%s", PROC_REGFILE_NAME);
return -ENOMEM;
}
return 0;
}
static void __exit exit_md(void){
remove_proc_entry(PROC_REGFILE_NAME, NULL);
}
module_init(init_md);
module_exit(exit_md);
</code></pre>
<p><code>pfs_regfile.h</code>:</p>
<pre><code>#ifndef PFS_REGFILE_H
#define PFS_REGFILE_H
#include <linux/fs.h>
#define PROC_REGFILE_NAME "pfs_regfile"
int pfs_open(struct inode*, struct file *);
int pfs_release(struct inode *, struct file *);
ssize_t pfs_device_read(struct file *, char __user * buffer, size_t, loff_t *);
#endif //PFS_REGFILE_H
</code></pre>
<p><code>pfs_regfile.c</code>:</p>
<pre><code>#include <linux/module.h>
#include <linux/uaccess.h>
#include "pfs_regfile.h"
static char data[5000];
static char *current_ptr;
int pfs_open(struct inode* in, struct file *filp){
for (int i = 0; i < sizeof(data) - 1; i++){
data[i] = 'a';
}
current_ptr = data;
try_module_get(THIS_MODULE);
return 0;
}
int pfs_release(struct inode *in, struct file *filp){
module_put(THIS_MODULE);
return 0;
}
ssize_t pfs_device_read(struct file *file, char __user * buffer, size_t len, loff_t *off){
size_t pos = (size_t)(current_ptr - data);
size_t to_copy = pos + len < sizeof data ? len : sizeof data - pos;
unsigned long not_copied = copy_to_user(buffer, current_ptr, to_copy);
if(not_copied){
printk(KERN_ALERT "Unknown error occurred when copying data into userspace\n");
}
size_t copied = to_copy - (size_t) not_copied;
current_ptr += copied;
return (ssize_t) copied;
}
</code></pre>
<p>I'm not sure if this module should work in all cases and its implementation is sort of "idiomatic". I'm especially concerned about concurrency. I tried to access it concurrently from different processes (<code>cat /proc/pfs_regfile</code>), and it worked fine. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:36:13.823",
"Id": "449658",
"Score": "0",
"body": "`i < sizeof(data) - 1` - why leave the last byte uninitialized?"
}
] |
[
{
"body": "<h2><code>memset</code></h2>\n\n<pre><code>for (int i = 0; i < sizeof(data) - 1; i++){\n data[i] = 'a';\n}\n</code></pre>\n\n<p>shouldn't be needed. Just use <code>memset</code> from <code>string.h</code>, which is indeed available in the kernel.</p>\n\n<h2><code>sizeof</code></h2>\n\n<p>You have this:</p>\n\n<pre><code>int i = 0; i < sizeof(data) - 1; i++\n</code></pre>\n\n<p>but also this:</p>\n\n<pre><code>pos + len < sizeof data ? len : sizeof data - pos\n</code></pre>\n\n<p>Today I learned that the parens are <a href=\"https://en.wikipedia.org/wiki/Sizeof\" rel=\"nofollow noreferrer\">needed on types and optional on expressions</a>:</p>\n\n<blockquote>\n <p>The operator has a single operand, which is either an expression or a data type cast. A cast is a data type enclosed in parenthesis. </p>\n</blockquote>\n\n<p>The only syntax I've ever seen is with parens. You should at least stay internally consistent.</p>\n\n<h2>Buffer sizes</h2>\n\n<p>5000 is a little unusual, especially inside the kernel. Unless there are hidden motivations, consider just making it 1024*4 == 4096.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T06:27:18.707",
"Id": "449731",
"Score": "0",
"body": "I was not sure if it legitimate to use standard library function from Kernel Space. That's why I used the loop."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:52:33.973",
"Id": "230716",
"ParentId": "230701",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230716",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T11:07:00.710",
"Id": "230701",
"Score": "5",
"Tags": [
"c",
"linux",
"kernel"
],
"Title": "Creating procfs entry on linux in Kernel Module"
}
|
230701
|
<p>I am currently implementing an app that uses an architecture based on features & usecases and message sending. </p>
<p>Features are created with message handler passed in.<br>
To test the feature, a handler intercepting the resulting message, must be passed in. </p>
<p>I came up with 2 solutions, both currently being present in the project's code:</p>
<ol>
<li><p>use an object implementing the message handling protocol and offering a callback.</p>
<pre><code>import Quick
import Nimble
@testable import LibExample
class Mock {
class MessageHandler: MessageHandling {
init(callBack: @escaping (Message) -> ()) {
self.callBack = callBack
}
let callBack: (Message) -> ()
func handle(msg: Message) {
callBack(msg)
}
}
}
class SettingsFeatureSpec: QuickSpec {
override func spec() {
describe("the SettingsFeature UseCase") {
var sut: SettingsFeature!
var messageHandler: Mock.MessageHandler!
var receivedModes: [TransportOption]!
beforeEach {
receivedModes = []
messageHandler = Mock.MessageHandler {
if case .feature(.settings(.useCase(.transport(.action(.didActivate(let m)))))) = $0 {
receivedModes.append(m)
}
}
sut = SettingsFeature(with: messageHandler)
}
afterEach {
receivedModes = nil
messageHandler = nil
sut = nil
}
it("switches transport modes") {
sut.handle(feature: .settings(.useCase(.transport(.action(.activate(.udp))))))
sut.handle(feature: .settings(.useCase(.transport(.action(.activate(.tcp))))))
sut.handle(feature: .settings(.useCase(.transport(.action(.activate(.tls))))))
sut.handle(feature: .settings(.useCase(.transport(.action(.activate(.udp))))))
expect(receivedModes) == [.udp, .tcp, .tls, .udp]
}
}
}
}
</code></pre></li>
<li><p>have the test/spec implement the the message handling</p>
<pre><code>import Quick
import Nimble
@testable import LibExample
class UserHandlingSpec: QuickSpec, MessageHandling {
var loggedInUser:User!
var loggedOutUser:User!
func handle(msg: Message) {
switch msg {
case .feature(.userHandling(.useCase(.login(.action(.logInConfirmed(let user)))))):
self.loggedInUser = user
case .feature(.userHandling(.useCase(.logout(.action(.logOutConfirmed(let user)))))):
self.loggedOutUser = user
default:
break
}
}
override func spec() {
describe("the UserHandling Feature") {
var sut: UserHandlingFeature!
beforeEach {
sut = UserHandlingFeature(with: self)
}
afterEach {
sut = nil
self.loggedOutUser = nil
self.loggedInUser = nil
}
it("logs in user"){
sut.handle(feature: .userHandling(.useCase(.login(.action(.logIn("pinky", "password"))))))
expect(self.loggedInUser.name) == "pinky"
}
it("logs out user"){
sut.handle(feature: .userHandling(.useCase(.logout(.action(.logOut(User(name:"the brain")))))))
expect(self.loggedOutUser.name) == "the brain"
}
}
}
}
</code></pre></li>
</ol>
<p>Which one would be the preferred way and why?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T16:19:33.000",
"Id": "449648",
"Score": "0",
"body": "Have you tried either of these solutions? Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T16:20:59.767",
"Id": "449649",
"Score": "0",
"body": "@Mast: yes, I did"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T15:05:00.630",
"Id": "230708",
"Score": "1",
"Tags": [
"unit-testing",
"swift",
"mocks"
],
"Title": "Message handling: Should a test/spec do it?"
}
|
230708
|
<h3>Problem 1</h3>
<p>Given a string, the task is to reverse the string and return a reversed string.</p>
<h3>Problem 2</h3>
<p>Given a string, return true if the string is a palindrome or false if it is not.</p>
<h2>Code</h2>
<p>Just for practicing, I've implemented reverse string and palindrome problems using JavaScript and Python. If you'd like to review the codes and provide any change/improvement recommendations, please do so and I appreciate that.</p>
<h3>JavaScript</h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Problem 1
// Given a string, return true if the string is a palindrome
// or false if it is not. Palindromes are strings that
// form the same word if it is reversed. *Do* include spaces
// and punctuation in determining if the string is a palindrome.
// --- Examples:
// abba => true
// abc => false
// Problem 2
// Given a string, return a new string with the reversed
// order of characters
// --- Examples
// apple => leppa
// hello => olleh
// Greetings! => !sgniteerG
// This method tests if the string is a palindrome using four reverse string functions
function check_palindrome(original_string) {
original_string = original_string.toLowerCase();
let reversed_string_1 = reverse_string_built_in(original_string);
let reversed_string_2 = reverse_string_reduce(original_string);
let reversed_string_3 = reverse_string_for_of_loop(original_string);
let reversed_string_4 = reverse_string_negative_for_loop(original_string);
// If the original string is a palindrome
if (reversed_string_1 === original_string && reversed_string_2 === original_string && reversed_string_3 === original_string && reversed_string_4 === original_string) {
return true;
// If the original string is not a palindrome
} else {
return false;
}
}
// This method is an slightly optimized version of checking for palindrome
function check_palindrome_optimized(original_string) {
original_string = original_string.toLowerCase();
count = 0;
return original_string.split('').every((char, i) => {
count++;
if (count > Math.floor(original_string.length / 2)) {
return true
}
return char === original_string[original_string.length - i - 1];
});
}
// This method uses reverse() built in function
function reverse_string_built_in(original_string) {
return original_string.split('').reverse().join('');
}
// This method uses for of loop
function reverse_string_for_of_loop(original_string) {
let reversed_string = '';
for (let char of original_string) {
reversed_string = char + reversed_string;
}
return reversed_string;
}
// Using negative for loop and contact
function reverse_string_negative_for_loop(original_string) {
let reversed_string = '';
for (var i = original_string.length - 1; i >= 0; i--) {
reversed_string = reversed_string.concat(original_string[i]);
}
return reversed_string;
}
//Using reduce() method
function reverse_string_reduce(original_string) {
return original_string.split('').reduce((reversed_string, char) => char + reversed_string, '');
}
// Here, we are testing our palindrome words
words_array = ['apple', 'kayak', 'abc1221cba', 'reviver', 'redivider', '1736', 'deified', 'Anna', 'Able was I ere I saw Elba', "Madam, I'm Adam", 'civic', 'RaDar', 'Never odd or even', 'LeVeL', 'kayak', 'racecar', 'Doc, note: I dissent. A fast never prevents a fatness. I diet on cod', 'redder', 'madam', '1991', 'refer'];
for (let word of words_array) {
if (check_palindrome_optimized(word) === true && check_palindrome(word) === true) {
console.log(' "'.concat(word, '" is a palindrome!'));
} else {
console.log(' "'.concat(word, '" is not a palindrome!'));
}
}</code></pre>
</div>
</div>
</p>
<h3>Python</h3>
<pre><code>def reverse_string(original_string):
'''
Returns a reversed string give a string
'''
reversed_string = ''
for char in original_string:
reversed_string = char + reversed_string
return reversed_string
def reverse_string_slice(original_string):
'''Returns a reversed string give a string'''
return original_string[::-1]
def check_palindrome(original_string):
'''Returns true if an input string is a palindrome'''
original_string = original_string.lower()
if reverse_string_slice(original_string) == original_string and reverse_string(original_string) == original_string:
return True
return False
# Here, we are testing our palindrome words
words_array = ['apple', 'kayak', 'abc1221cba', 'reviver', 'redivider', '1736', 'deified', 'Anna', 'Able was I ere I saw Elba', "Madam, I'm Adam", 'civic', 'RaDar',
'Never odd or even', 'LeVeL', 'kayak', 'racecar', 'Doc, note: I dissent. A fast never prevents a fatness. I diet on cod', 'redder', 'madam', '1991', 'refer']
delimiter = '-'*50
for word in words_array:
print(delimiter)
print(f'The reverse of "{word}" is "{reverse_string(word)}"')
if check_palindrome(word) == True:
print(f' "{word}" is a palindrome!')
else:
print(f' "{word}" is not a palindrome!')
</code></pre>
<h3>Output</h3>
<pre><code>--------------------------------------------------
The reverse of "apple" is "elppa"
"apple" is not a palindrome!
--------------------------------------------------
The reverse of "kayak" is "kayak"
"kayak" is a palindrome!
--------------------------------------------------
The reverse of "abc1221cba" is "abc1221cba"
"abc1221cba" is a palindrome!
--------------------------------------------------
The reverse of "reviver" is "reviver"
"reviver" is a palindrome!
--------------------------------------------------
The reverse of "redivider" is "redivider"
"redivider" is a palindrome!
--------------------------------------------------
The reverse of "1736" is "6371"
"1736" is not a palindrome!
--------------------------------------------------
The reverse of "deified" is "deified"
"deified" is a palindrome!
--------------------------------------------------
The reverse of "Anna" is "annA"
"Anna" is a palindrome!
--------------------------------------------------
The reverse of "Able was I ere I saw Elba" is "ablE was I ere I saw elbA"
"Able was I ere I saw Elba" is a palindrome!
--------------------------------------------------
The reverse of "Madam, I'm Adam" is "madA m'I ,madaM"
"Madam, I'm Adam" is not a palindrome!
--------------------------------------------------
The reverse of "civic" is "civic"
"civic" is a palindrome!
--------------------------------------------------
The reverse of "RaDar" is "raDaR"
"RaDar" is a palindrome!
--------------------------------------------------
The reverse of "Never odd or even" is "neve ro ddo reveN"
"Never odd or even" is not a palindrome!
--------------------------------------------------
The reverse of "LeVeL" is "LeVeL"
"LeVeL" is a palindrome!
--------------------------------------------------
The reverse of "kayak" is "kayak"
"kayak" is a palindrome!
--------------------------------------------------
The reverse of "racecar" is "racecar"
"racecar" is a palindrome!
--------------------------------------------------
The reverse of "Doc, note: I dissent. A fast never prevents a fatness. I diet on cod" is "doc no teid I .ssentaf a stneverp reven tsaf A .tnessid I :eton ,coD"
"Doc, note: I dissent. A fast never prevents a fatness. I diet on cod" is not a palindrome!
--------------------------------------------------
The reverse of "redder" is "redder"
"redder" is a palindrome!
--------------------------------------------------
The reverse of "madam" is "madam"
"madam" is a palindrome!
--------------------------------------------------
The reverse of "1991" is "1991"
"1991" is a palindrome!
--------------------------------------------------
The reverse of "refer" is "refer"
"refer" is a palindrome!
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T07:19:31.310",
"Id": "449741",
"Score": "1",
"body": "I presume, by \"string\" you mean \"a sequence of Latin letters\"? Otherwise, your problems would be much harder to solve. See this comment: https://stackoverflow.com/a/16776621/989121"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T10:47:14.730",
"Id": "449753",
"Score": "1",
"body": "Typically, punctuation is ignored when testing for palindromes, so \"Doc, note:...\" should return true. Likewise, \"Never odd or even\" should return true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T15:16:03.653",
"Id": "449788",
"Score": "1",
"body": "You could also go one step further here and add a reverse method to the String prototype (in js) so you could do: \"test\".reverse(). This keeps the code nicely encapsulated and re-usable. With it being on the prototype, every instance gets the same function."
}
] |
[
{
"body": "<h2>Boolean expression returns</h2>\n\n<p>This applies to both your Javascript and Python implementations:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>if (reversed_string_1 === original_string && reversed_string_2 === original_string && reversed_string_3 === original_string && reversed_string_4 === original_string) {\n return true;\n // If the original string is not a palindrome\n} else {\n return false;\n}\n</code></pre>\n\n<pre class=\"lang-python prettyprint-override\"><code>if reverse_string_slice(original_string) == original_string and reverse_string(original_string) == original_string:\n return True\nreturn False\n</code></pre>\n\n<p>Your expression is already a boolean; you don't need an <code>if</code>. In other words,</p>\n\n<pre><code>return reverse_string_slice(original_string) == original_string and reverse_string(original_string) == original_string\n</code></pre>\n\n<h2>Boolean comparison</h2>\n\n<pre><code>if check_palindrome(word) == True:\n</code></pre>\n\n<p>should simply be</p>\n\n<pre><code>if check_palindrome(word):\n</code></pre>\n\n<p>Also, the convention is that boolean-valued functions are named like <code>is_palindrome</code>.</p>\n\n<h2><code>words_array</code></h2>\n\n<p>First of all: This isn't an array, because Python doesn't have those. It's a list. Second, just call it <code>words</code> - usually it's not useful to include the type of a variable in its name. Finally: you shouldn't even be using a list, because you won't be mutating (modifying) it; use a <code>tuple</code> (in parens, not brackets).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T01:56:50.593",
"Id": "449714",
"Score": "1",
"body": "Technically, Python does have [arrays](https://docs.python.org/3/library/array.html). However, they are rarely used. The term \"array\" is also used in the context of `numpy`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T02:17:56.833",
"Id": "449720",
"Score": "1",
"body": "That's fair. It's more accurate to say that Python has arrays, but they aren't first-class."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:20:30.003",
"Id": "230714",
"ParentId": "230709",
"Score": "9"
}
},
{
"body": "<p>In Python, your <code>check_palindrome</code> function can be made more efficient and <em>pythonic</em>: </p>\n\n<pre><code>def check_palindrome(original_string):\n \"\"\"Returns true if an input string is a palindrome\"\"\"\n original_string = original_string.lower()\n return all(r == o for r, o in zip(reversed(original_string), original_string[:len(original_string)//2]))\n</code></pre>\n\n<p>This only iterates over half of the characters as opposed to your version. You could also use islice from itertools, for example:</p>\n\n<pre><code>def check_palindrome(original_string):\n \"\"\"Returns true if an input string is a palindrome\"\"\"\n original_string = original_string.lower()\n original = islice(original_string, len(original_string) // 2)\n return all(r == o for r, o in zip(reversed(original_string), original))\n</code></pre>\n\n<p>Also note that docstrings should be double quoted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T01:59:17.933",
"Id": "449716",
"Score": "2",
"body": "`original_string[::len(original_string)//2]` should be `original_string[:len(original_string)//2]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T02:02:15.177",
"Id": "449717",
"Score": "1",
"body": "@GZ0 Thanks for the catch."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T23:05:12.793",
"Id": "230726",
"ParentId": "230709",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230714",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T15:33:04.063",
"Id": "230709",
"Score": "3",
"Tags": [
"python",
"javascript",
"beginner",
"algorithm",
"strings"
],
"Title": "Palindrome and Reverse a String Problems (JavaScript, Python)"
}
|
230709
|
<p>I am trying to implement a monitor for a certain temporal logic. What this means is the following:</p>
<ul>
<li>There is some external source, from which a trace of items are coming. An item looks like a timestamp along with some propositions which holds at that point.</li>
<li>There is a property of traces we care about. This is specified in some temporal logic. This could look like "So far, p has been true" or "Since q happened in the last two time units, r has always held since then", or "p always holds when q does"</li>
<li>Our task is to build a monitor which is a streaming algorithm whose interface is the operation <code>step</code> which consumes an item from the trace and checks whether the trace fed so far satisfies the given property or not.</li>
</ul>
<p>Here is the Haskell code:</p>
<pre><code>import Control.Monad.State
import qualified Data.Map
import qualified Data.Set
import Data.Maybe
-- in what follows, `t` stands for some time domain. For most purposes, we assume it is totally ordered and has subtraction defined on it.
data Interval t =
OpenOpen t t
| OpenClosed t t
| ClosedOpen t t
| ClosedClosed t t
deriving (Eq, Ord)
inInterval :: Ord t => t -> Interval t -> Bool
inInterval t (OpenOpen s f) = s < t && t < f
inInterval t (OpenClosed s f) = s < t && t <= f
inInterval t (ClosedOpen s f) = s <= t && t < f
inInterval t (ClosedClosed s f) = s <= t && t <= f
inleqInterval :: Ord t => t -> Interval t -> Bool
inleqInterval t (OpenOpen s f) = t < f
inleqInterval t (OpenClosed s f) = t <= f
inleqInterval t (ClosedOpen s f) = t < f
inleqInterval t (ClosedClosed s f) = t <= f
-- Below, we use `prop` to denote a domain for the symbols that represent propositions
-- For most purposes, we'd want to use something like int since we'd use formulae based on this symbols as indices of maps
type TruthAssignment prop = Data.Set.Set prop
type Item t prop = (t, TruthAssignment prop)
type Trace t prop = [Item t prop] -- the programmer should ensure that the timestamps are increasing
data TemporalFormula t prop =
Proposition prop
| Since (Interval t) (TemporalFormula t prop) (TemporalFormula t prop)
| Neg (TemporalFormula t prop)
| And (TemporalFormula t prop) (TemporalFormula t prop)
deriving (Eq, Ord)
isTemporal :: TemporalFormula t prop -> Bool
isTemporal (Since _ _ _) = True
isTemporal _ = False
getTemporalSubformulas :: TemporalFormula t prop -> [TemporalFormula t prop]
getTemporalSubformulas phi@(Since _ phi1 phi2) = [phi] ++ getTemporalSubformulas phi1 ++ getTemporalSubformulas phi2
getTemporalSubformulas (Neg phi) = getTemporalSubformulas phi
getTemporalSubformulas (And phi1 phi2) = (getTemporalSubformulas phi1) ++ (getTemporalSubformulas phi2)
getTemporalSubformulas _ = []
type MonitorState t prop = Data.Map.Map (TemporalFormula t prop) [t]
-- the following type signature says that the monitor is a stateful object which when given a stream of items produces a stream of booleans
monitor :: (Ord t, Ord prop, Num t) => TemporalFormula t prop -> Trace t prop -> State (MonitorState t prop) [Bool]
monitor phi stream = do
iinit phi
loop stream
where
loop (i:is) = do
b <- step i phi
bs <- loop is
return (b:bs)
loop [] = return []
iinit :: (Ord t, Ord prop) => TemporalFormula t prop -> State (MonitorState t prop) ()
iinit phi = do
let subformulas = getTemporalSubformulas phi
put $ foldr (\psi map -> Data.Map.insert psi [] map) Data.Map.empty subformulas
step :: (Num t, Ord t, Ord prop) => Item t prop -> TemporalFormula t prop -> State (MonitorState t prop) Bool
step (_, truths) (Proposition p) = return $ Data.Set.member p truths
step item (Neg formula) = not <$> step item formula
step item (And formula1 formula2) = do
b1 <- step item formula1
b2 <- step item formula2
return $ b1 && b2
step item@(tao, _) phi@(Since inter phi1 phi2) = do
update item phi
bufffs <- get
let lphi = case (Data.Map.lookup phi bufffs) of Just l -> l
case lphi of
[] -> return False
(t:_) -> return $ inInterval (tao - t) inter
update :: (Num t, Ord t, Ord prop) => Item t prop -> TemporalFormula t prop -> State (MonitorState t prop) ()
update (time, truths) phi@(Since inter phi1 phi2) = do
bufffs <- get
let lphi = case (Data.Map.lookup phi bufffs) of Just l -> l
b1 <- step (time, truths) phi1
b2 <- step (time, truths) phi2
let l = if b1 then (ddrop lphi inter time) else []
let lphi' = if b2 then l ++ [time] else l
put (Data.Map.insert phi lphi' bufffs)
ddrop :: (Ord t, Num t) => [t] -> Interval t -> t -> [t]
ddrop [] _ _ = []
ddrop (kappa:ls) inter tao
| inleqInterval (tao - kappa) inter = ddrop' kappa ls inter tao
| otherwise = ddrop ls inter tao
ddrop' :: (Ord t, Num t) => t -> [t] -> Interval t -> t -> [t]
ddrop' kappa [] _ _ = [kappa]
ddrop' kappa (kappa':ls) inter tao
| inInterval (tao - kappa') inter = ddrop' kappa' ls inter tao
| otherwise = (kappa:kappa':ls)
</code></pre>
<p>For comparison, here is a <a href="https://github.com/Agnishom/pltlmonitors/tree/master/pltl-java" rel="nofollow noreferrer">Java implementation</a> of the same idea.</p>
<p>I would like some feedback on my Haskell code:</p>
<ul>
<li>I would like to be able to extend this code with a <code>main</code> and test it on a large stream to see how well it <strong>performs</strong>. Is the State Monad appropriate for the purpose of performance? Is my way of modelling streams as lists appropriate for this purpose?</li>
<li>As implemented, the "monitor state" and the Formula looks like independent objects. Is there a better way to tie them together than to define a seperate MonitorState and initalize it everytime? I think the idea of modelling MonitorState as a Map is ugly and not very haskell-y. <strong>What are some better ways of structuring my code</strong> so that I can avoid the Map and/or show that there is some relation between the state of the monitor and a formula?</li>
<li>Other general comments on improving the code quality.</li>
</ul>
|
[] |
[
{
"body": "<p>I can't comment on performance implications of state monad usage, but it seems like list\n<a href=\"https://stackoverflow.com/questions/5188286/idiomatic-efficient-haskell-append\">concatenation may be a bottleneck</a> (e.g. in <code>getTemporalSubformulas</code> or <code>l ++ [time]</code> in <code>update</code>).</p>\n\n<p><strong>Minor style notes</strong></p>\n\n<p>It is common practice to import <code>Data.Map</code> and <code>Data.Set</code> with alias and to\nimport main type unqualified. This makes type signatures a bit more concise.</p>\n\n<pre><code>import qualified Data.Map as Map\nimport Data.Map (Map)\n\nfoo :: Int -> Map Int String\nfoo x = Map.singleton x \"hello\"\n</code></pre>\n\n<hr>\n\n<p>In <code>isTemporal</code> you can use <code>{}</code> to match on data constructor without matching\nits fields. This is potentially future-proof in case of changing number of\nfields in data constructor.</p>\n\n<pre><code>isTemporal Since{} = True\nisTemporal _ = False\n</code></pre>\n\n<hr>\n\n<p>It may be a bit easier to encode intervals as a pair of bounds:</p>\n\n<pre><code>data EndPoint t = Open t | Closed t\ntype Interval t = (EndPoint t, EndPoint t)\n\nafterStart, beforeEnd :: Ord t => t -> Interval t -> Bool\nafterStart t (Open start) = t > start\nafterStart t (Closed start) = t >= start\nbeforeEnd t (Open end) = t < end\nbeforeEnd t (Closed end) = t <= end\n\ninInterval, inleqInterval :: Ord t => t -> Interval t -> Bool\ninInterval t int = afterStart t int && beforeEnd t int\ninleqInterval = beforeEnd\n</code></pre>\n\n<p>It is also may be beneficial to reuse intervals\nfrom <a href=\"https://hackage.haskell.org/package/data-interval\" rel=\"nofollow noreferrer\">data-interval</a> package.</p>\n\n<hr>\n\n<p>In <code>iinint</code></p>\n\n<pre><code>foldr (\\psi map -> Data.Map.insert psi [] map) Data.Map.empty subformulas\n</code></pre>\n\n<p>can be rewritten as</p>\n\n<pre><code>Map.fromList $ map (,[]) subformulas\n</code></pre>\n\n<hr>\n\n<p>Try to compile with <code>-Wall</code> flag, seems like you have a lot of non-exhaustive\npattern matches, which is bad.</p>\n\n<p>For example:</p>\n\n<pre><code> let lphi = case (Data.Map.lookup phi bufffs) of Just l -> l\n</code></pre>\n\n<p>If you are absolutely sure that lookup won't fail here, you can rewrite it with <a href=\"http://hackage.haskell.org/package/containers-0.6.2.1/docs/Data-Map-Strict.html#v:-33-\" rel=\"nofollow noreferrer\"><code>Data.Map.!</code></a>:</p>\n\n<pre><code> let lphi = bufffs `Map.!` phi\n</code></pre>\n\n<hr>\n\n<p><code>ddrop</code> can be rewritten to make it more explicit what parts of the list you are removing:</p>\n\n<pre><code>ddrop ls inter tao = case dropWhile f ls of\n [] -> []\n kappa:ls' -> kappa : dropWhile g ls'\n where\n f kappa = not $ inleqInterval (tao - kappa) inter\n g kappa = inInterval (tao - kappa) inter\n</code></pre>\n\n<p>or a bit shorter with the <a href=\"https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#view-patterns\" rel=\"nofollow noreferrer\">ViewPatterns</a> extension</p>\n\n<pre><code>ddrop ls inter tao = case dropWhile f ls of\n | dropWhile f ls -> kappa:ls' = kappa : dropWhile g ls'\n | otherwise = []\n where\n f kappa = not $ inleqInterval (tao - kappa) inter\n g kappa = inInterval (tao - kappa) inter\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:04:33.693",
"Id": "230815",
"ParentId": "230711",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:03:10.880",
"Id": "230711",
"Score": "4",
"Tags": [
"algorithm",
"haskell",
"stream"
],
"Title": "Monitoring Traces for Satisfaction of Temporal Logic Properties"
}
|
230711
|
<p>Here is my code, it works fine, just wondering if there any anything to make it even better.</p>
<pre><code> public static boolean isSorted(int[] arr)
{
int n = arr.length;
int i = 0;
while (arr[i] == arr[i + 1]) // same elements at the beginning
i++;
if (arr[i] < arr[i + 1]) // candidate for ascending, non-decreasing
{
i++;
for (; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
else // candidate for descending, non-increasing
{
i++;
for (; i < n - 1; i++)
{
if (arr[i] < arr[i + 1])
return false;
}
return true;
}
}
</code></pre>
<p>It works fine, I have just avoided any class or other method.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:45:37.283",
"Id": "449661",
"Score": "0",
"body": "Why did you avoid methods?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:04:47.263",
"Id": "449664",
"Score": "4",
"body": "This code will crash if all array elements are equal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:08:23.160",
"Id": "449666",
"Score": "0",
"body": "I got it. @Martin R. I didn't consider that case, any other improvement suggesstions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T18:56:43.673",
"Id": "449673",
"Score": "0",
"body": "What happens with an array of length 1?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:31:48.283",
"Id": "449677",
"Score": "0",
"body": "Yeah, that's another issue. Thanks @ Austin Hastings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:57:49.900",
"Id": "449688",
"Score": "1",
"body": "And length 0? For all these edge cases you should write unit tests and publish them here together with your main code. Or if you don't know what unit tests are, only list the examples in human-readable form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:06:01.100",
"Id": "449693",
"Score": "0",
"body": "How many elements do you expect to sort, and how often do you expect this function is called? If the answer to those questions is low enough, I suspect that you shouldn't do this yourself, and just sort-and-compare instead, which would only need one line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:12:57.267",
"Id": "449762",
"Score": "1",
"body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:16:55.610",
"Id": "449764",
"Score": "0",
"body": "I got it @ Vogel612"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T15:09:58.587",
"Id": "449786",
"Score": "0",
"body": "I wrote unit tests code here https://codereview.stackexchange.com/questions/230751/unit-tests-code-for-a-java-class-that-that-checks-whether-an-array-is-sorted#230751 @Reinderien"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T15:20:07.513",
"Id": "449789",
"Score": "0",
"body": "Great, but that doesn't answer my question. In the wild, how much load will this function get?"
}
] |
[
{
"body": "<h3>Edge cases</h3>\n<p>As some comments have pointed out, your current code doesn't handle length-0 arrays, or length-1 arrays, or arrays where all elements are equal (e.g. <code>[5, 5, 5, 5, 5]</code>). In all of these cases, your <code>while</code>-loop at the very beginning of the method will hit an "array index out of bounds" exception. This needs to be fixed.</p>\n<h3>Logic flow</h3>\n<p>Conceptually, the method proceeds through the array comparing elements until one of two things happens:</p>\n<ol>\n<li>It finds elements that are out of order. (Return <code>false</code>.)</li>\n<li>It reaches the end of the array. (Return <code>true</code>.)</li>\n</ol>\n<p>In this scenario, I think it helps to think of returning <code>false</code> as the "exceptional" case and returning <code>true</code> as the "default" case. Instead of having two <em>separate</em> <code>return true</code> statements, we can put one <code>return true</code> statement at the very bottom of the method. So if we haven't returned <code>false</code> earlier in the method, we will return <code>true</code> "by default".</p>\n<p><strong>Post-acceptance edit:</strong> Another simplification to the flow is possible. Your code uses a loop to pass over any duplicates at the start of the array, and <em>then</em> picks whether the sorting order should be ascending or descending by comparing the two elements after those leading duplicates. It is much simpler to pick the sorting order by comparing the <em>first</em> and <em>last</em> elements of the array (an idea which I borrowed/stole from <a href=\"https://codereview.stackexchange.com/users/49476/sanastasiadis\">sanastasiadis</a>'s answer <a href=\"https://codereview.stackexchange.com/a/230766/192133\">here</a>). This means we don't need special handling for duplicates at all.</p>\n<h3>Style</h3>\n<p>This code caught my eye:</p>\n<pre><code> while (arr[i] == arr[i + 1]) // same elements at the beginning\n i++;\n</code></pre>\n<p>Yes, if the the body is only one line, then technically you <em>can</em> write <code>if</code>s and <code>for</code>s and <code>while</code>s without using brackets (<code>{</code> and <code>}</code>). And in some ways it does look cleaner. But it is also risky. If the code where you use that style gets edited later, it is very easy for someone to make a typo like this:</p>\n<pre><code>while (a == b)\n foo();\n bar();\n</code></pre>\n<p>...where it <em>looks</em> like <code>bar()</code> is called as part of the loop, but it's actually called <em>after</em> the loop. For this reason, I recommend that you get into the habit of always using brackets.</p>\n<p>Also, I would prefer to use <code>i + 1 < n</code> instead of <code>i < n - 1</code> for the comparisons, because we're already using <code>i + 1</code> in a lot of places and I think it makes the code easier to read if we just use that more. It gives the reader one concept to grasp, instead of two. But maybe that's just me.</p>\n<h3>Putting it all together</h3>\n<pre><code> public static boolean isSorted(int[] arr)\n {\n int n = arr.length;\n\n if (n == 0 || arr[0] <= arr[n-1]) // candidate for ascending, non-decreasing\n {\n for (int i = 0; i + 1 < n; i++)\n {\n if (arr[i] > arr[i + 1])\n {\n return false;\n }\n }\n }\n else // candidate for descending, non-increasing\n {\n for (int i = 0; i + 1 < n; i++)\n {\n if (arr[i] < arr[i + 1])\n {\n return false;\n }\n }\n }\n\n return true;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T03:57:24.037",
"Id": "230733",
"ParentId": "230715",
"Score": "5"
}
},
{
"body": "<p>We could make it better by making it more maintainable by simplifying the code and reducing duplication in the three for-loops. The problem is essentially checking that all successive pairs in the array are either equal or have the same sort order, so let's code it that way:</p>\n\n<pre><code>import static java.lang.Integer.compare;\nimport static java.lang.Integer.signum;\n\npublic static boolean isSorted(final int[] arr) {\n // The order in which the array is.\n // -1: ascending\n // 0: all elements are the same\n // 1: descending\n int arrayOrder = 0;\n\n for (int i = 0; i < arr.length - 1; i++) {\n // Signum is actually useless, since compare returns -1..1 but\n // we believe the documentation, not the code.\n final int pairOrder = signum(compare(arr[i], arr[i + 1]));\n\n if (arrayOrder == 0) {\n // All elements so far have been equal. First non-equal pair\n // defines the order expected from the following pairs..\n arrayOrder = pairOrder;\n } else if (pairOrder != arrayOrder && pairOrder != 0) {\n // If any pair is not equal and deviates from array order,\n // the array is not sorted.\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n\n<p>Is this more efficient? No. There are more operations inside the for-loop, but we're talking about two equals checks between integers in an O(N) algorithm. If yours takes 4.7s on my laptop, mine takes 5.4s... for 2^31-1 elements.</p>\n\n<p>A benefit in a single for-loop is that we don't need to expose the loop counter outside the loop itself. Code becomes harder to follow and more error prone when the loop counter is modified outside it's logical scope.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T09:06:53.067",
"Id": "449744",
"Score": "0",
"body": "You should add a check for arrays with less than 2 elements to avoid an index out-of-bounds exception: `if (arr.length < 2) return true;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T09:10:15.450",
"Id": "449745",
"Score": "1",
"body": "@RoToRa That check is included in the for loop test. Arrays with length 0 or 1 skip the loop entiorely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T09:12:49.400",
"Id": "449746",
"Score": "0",
"body": "Yes, you are right. I don't know what I was thinking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T19:08:37.293",
"Id": "449807",
"Score": "1",
"body": "I think this is ultimately easier to read and more maintainable than my answer, and I agree that any small loss of efficiency is worth it. +1."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T06:31:25.970",
"Id": "230736",
"ParentId": "230715",
"Score": "6"
}
},
{
"body": "<h1>Advantages</h1>\n\n<p>A very good characteristic of your algorithm is that it iterates through the elements of the array only once.\nThe next loop begins from where the previous one left the iterator <code>i</code>.</p>\n\n<h1>Disadvantages</h1>\n\n<p>However, as it was mentioned in the other 2 answers until now, your code does not take into consideration the case of arrays with 0 or 1 elements.</p>\n\n<p>Moreover, it is not covering the case that all the elements of the array are equal (e.g. [5,5,5,5,5]).</p>\n\n<p>Another disadvantage is that the loop for ascending and the loop for descending are almost duplicated, with the difference of the direction of the inequality sign.</p>\n\n<p>Additionally, I would say that it's not a good practice to return from inside a loop, especially when there are more than one loops in the same method.\nIt's preferable to declare a variable that will hold the returning value, use break/continue in the loops and then return the value of the variable, only once at the end of the method.</p>\n\n<p>As a last point to highlight, when it's possible, I personally prefer using an external value that walks the values of the array rather than manipulating the iterator.\nIn this case the iterator and the walking variable are of type <code>int</code>, so, the memory footprint is the same.</p>\n\n<p>In a different case that the array would contain large objects, then it would be better to access random elements of the array by index, rather than copying and creating instances of that class.</p>\n\n<h1>Solution</h1>\n\n<p>For brevity and for maintainability reasons, I would choose a slightly different approach to solve this problem.</p>\n\n<p>Checking if the first element is bigger than the last, we can safely assume that the array would be sorted descending (or ascending respectively).</p>\n\n<p>So, in a single iteration, I wrote a loop that examines every element in the array, if it complies with the ascending or descending order that was deducted at the beginning.\nIn order to achieve that a variable that is walking the values of the array is used <code>edge</code>.</p>\n\n<pre><code>public class Sorted {\n public static boolean isSorted(int[] arr) {\n boolean isSorted = true;\n // zero length and 1 length arrays can be\n // considered already sorted by default\n if (arr.length > 1) {\n // keep the first value as an edge\n int edge = arr[0];\n // if the array is sorted then it should be either ascending(true)\n // or descending(false)\n boolean ascending = arr[0] <= arr[arr.length-1];\n for (int a : arr) {\n // check if the relation between the edge and the current element\n // complies with ascending or descending\n if ((ascending == (edge < a))\n || edge == a) {\n edge = a;\n } else {\n isSorted = false;\n break;\n }\n }\n }\n return isSorted;\n }\n}\n</code></pre>\n\n<p>In order to test the above code I wrote the below test cases:</p>\n\n<pre><code>public static void main(String[] args) {\n Assert.assertTrue(isSorted(new int[]{}));\n Assert.assertTrue(isSorted(new int[]{1}));\n\n Assert.assertTrue(isSorted(new int[]{0,1}));\n Assert.assertTrue(isSorted(new int[]{1,2,3,4,5}));\n Assert.assertTrue(isSorted(new int[]{2,2,3,4,5}));\n Assert.assertTrue(isSorted(new int[]{2,2,2,2,2}));\n\n Assert.assertTrue(isSorted(new int[]{1,0}));\n Assert.assertTrue(isSorted(new int[]{5,4,3,2,1}));\n Assert.assertTrue(isSorted(new int[]{5,4,3,2,2}));\n Assert.assertTrue(isSorted(new int[]{5,4,4,4,4}));\n\n Assert.assertFalse(isSorted(new int[]{1,2,3,4,1}));\n Assert.assertFalse(isSorted(new int[]{5,3,1,2,4}));\n Assert.assertFalse(isSorted(new int[]{5,4,3,2,4}));\n\n Assert.assertTrue(isSorted(new int[]{5,3,3,3,1}));\n Assert.assertTrue(isSorted(new int[]{5,5,3,3,1}));\n Assert.assertTrue(isSorted(new int[]{15,11,11,3,3,3,1}));\n}\n</code></pre>\n\n<h1>Additional remarks</h1>\n\n<p>We should always have in mind that when importing libraries to do part of the work, we should be very careful because we may introduce performance penalties.</p>\n\n<p>If the library can do exactly what we want, with some configuration, then we should prefer doing it using the library, because someone has already worked to tune the implemented algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T19:11:39.613",
"Id": "449808",
"Score": "1",
"body": "Deducing the direction of sorting by comparing the first and last elements up front is so much better. +1."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T16:29:42.930",
"Id": "230766",
"ParentId": "230715",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230733",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T17:35:27.953",
"Id": "230715",
"Score": "7",
"Tags": [
"java",
"sorting"
],
"Title": "Checking an array is sorted in either order efficiently"
}
|
230715
|
<p>Here is my implementation: the goal of the algorithm is to find the kth smallest element in a BST.</p>
<pre><code>class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
count = 1
stack = []
while True:
if root:
#keep traversing until we hit leftmost node in tree
stack.append(root)
root = root.left
else:
curr = stack.pop()
if count == k:
return curr.val
count+=1
root = curr.right
</code></pre>
<p>I am having a hard time analyzing the complexity. The solution states how it is O(k+h) for both time and space, where h is the height of tree. For example, I do not understand why the space complexity isn't just O(h), assuming h is the height of the entire tree. Once you find the smallest item, its nodes right subtree could contain be of height>=height previously found between the smallest node and the root, so shouldn't the space be O(h*k), where h is the max depth between a subtrees leftmost child(smallest value) and its root?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T06:52:05.720",
"Id": "449736",
"Score": "0",
"body": "`The solution states how [complexity] is O(k+h) for both time and space` this seems to contradict `my implementation [for leetcode 230] `: if you are neither author nor maintainer of this code, your question is [off-topic here](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T07:03:27.230",
"Id": "449739",
"Score": "0",
"body": "(`I [don't understand why] space complexity isn't just O(h)` *all* of O(h) is O(k+h) for 0≤k. And, *please*, **do not use one and the same symbol with different interpretations in a single context** as you do with `h`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:51:30.273",
"Id": "449769",
"Score": "0",
"body": "@greybeard It's possible Leetcode gives the complexity of the optimal solution, but OP didn't reach it? I don't think this question is really off-topic, even though it seems to ask a lot of questions regarding the big O which isn't really within scope."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T20:44:28.310",
"Id": "230722",
"Score": "1",
"Tags": [
"python",
"algorithm",
"tree",
"complexity"
],
"Title": "leetcode 230: kth smallest element in a Binary Search Tree"
}
|
230722
|
<p><a href="https://leetcode.com/problems/diameter-of-binary-tree/" rel="nofollow noreferrer">https://leetcode.com/problems/diameter-of-binary-tree/</a></p>
<blockquote>
<p>Given a binary tree, you need to compute the length of the diameter of
the tree. The diameter of a binary tree is the length of the longest
path between any two nodes in a tree. This path may or may not pass
through the root.</p>
<pre><code>Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
</code></pre>
<p>Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].</p>
<p>Note: The length of path between two nodes is represented by the
number of edges between them.</p>
</blockquote>
<pre><code> [TestClass]
public class DiameterOfBinaryTreeTest
{
[TestMethod]
public void DiameterOfBinaryTreeTest1()
{
/* Constructed binary tree is
1
/ \
2 3
/ \
4 5
*/
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right = new TreeNode(3);
DiameterOfBinaryTreeClass diam = new DiameterOfBinaryTreeClass();
int result = diam.DiameterOfBinaryTree(root);
Assert.AreEqual(3, result);
}
}
//https://leetcode.com/problems/diameter-of-binary-tree/
public class DiameterOfBinaryTreeClass
{
public int DiameterOfBinaryTree(TreeNode root)
{
if (root == null)
{
return 0;
}
int leftDiameter = DiameterOfBinaryTree(root.left);
int rightDiameter = DiameterOfBinaryTree(root.right);
int leftHeight = Height(root.left);
int rightHeight = Height(root.right);
return Math.Max(leftHeight + rightHeight, Math.Max(leftDiameter,rightDiameter));
}
private int Height(TreeNode root)
{
if (root == null)
{
return 0;
}
return Math.Max(Height(root.left) ,Height(root.right)) + 1;
}
}
</code></pre>
<p>Please review for performance.</p>
|
[] |
[
{
"body": "<p>According to letcode submissions tab:</p>\n\n<pre><code> Runtime Memory\nOriginal solution form the question 108 ms 25 MB\nSolution from this answer (no recursion) 104 ms 26 MB\nSolution form Martin R answer 100 ms 25.3 MB\nSolution from this answer (recursive) 84 ms 24.7 MB\n</code></pre>\n\n<p><strong>Solution recursive</strong></p>\n\n<pre><code>public class DiameterOfBinaryTreeClass\n {\n private int MaxD = 0;\n\n public int DiameterOfBinaryTree(TreeNode root)\n {\n Height(root);\n return MaxD;\n }\n\n private int Height(TreeNode root)\n {\n if (root == null)\n {\n return 0;\n }\n\n int l = Height(root.left);\n int r = Height(root.right);\n int d = l + r;\n if (d > MaxD)\n MaxD = d;\n\n return Math.Max(l, r) + 1;\n }\n }\n</code></pre>\n\n<p><strong>No recursion solution:</strong></p>\n\n<pre><code>private int MaxD = 0;\n\npublic int DiameterOfBinaryTree(TreeNode root) {\n Solve(root);\n return MaxD;\n}\n\nclass CalcNode {\n public sbyte Direction;\n public int Left;\n public int Right;\n public TreeNode TreeNode;\n}\n\nprivate void Solve(TreeNode root) {\n if (root == null)\n return;\n\n var stack = new Stack < CalcNode > ();\n\n stack.Push(new CalcNode() {\n Direction = 0, Left = 0, Right = 0, TreeNode = root\n });\n HashSet < TreeNode > usedTreeNodes = new HashSet < TreeNode > ();\n\n while (stack.Count != 0) {\n TreeNode cur = stack.Peek().TreeNode;\n if (cur.left != null && !usedTreeNodes.Contains(cur.left)) {\n stack.Push(new CalcNode() {\n Direction = -1, Left = 0, Right = 0, TreeNode = cur.left\n });\n continue;\n }\n\n if (cur.right != null && !usedTreeNodes.Contains(cur.right)) {\n stack.Push(new CalcNode() {\n Direction = 1, Left = 0, Right = 0, TreeNode = cur.right\n });\n continue;\n }\n\n CalcNode removedNode = stack.Pop();\n usedTreeNodes.Add(removedNode.TreeNode);\n int d = removedNode.Left + removedNode.Right;\n if (d > MaxD)\n MaxD = d;\n\n if (removedNode.Direction == 0)\n continue;\n\n CalcNode curCalcNode = stack.Peek();\n int removedNodeHeight = Math.Max(removedNode.Left, removedNode.Right) + 1;\n if (removedNode.Direction == 1)\n curCalcNode.Right += removedNodeHeight;\n else\n curCalcNode.Left += removedNodeHeight;\n }\n}\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T11:24:33.107",
"Id": "449759",
"Score": "0",
"body": "Maybe, generally iteration is preferred over recursion. Can you show that/if iteration is feasible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T11:43:19.690",
"Id": "449761",
"Score": "0",
"body": "the code would be more complex, but the question was about peformance (not about a code simplisity) sure i can provide an example. Will do it in the next few days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T07:58:38.420",
"Id": "449845",
"Score": "0",
"body": "@JAD i decided to write recursive version first. With the next update I will unfold the recursion - it would be interesting to see the performance impact :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T14:51:41.610",
"Id": "450159",
"Score": "0",
"body": "My not recursive solution turned out to be slower as the recursive version"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T07:31:04.723",
"Id": "230737",
"ParentId": "230724",
"Score": "1"
}
},
{
"body": "<p>Your method visits mosts nodes <em>twice:</em> Here</p>\n\n<pre><code>int leftDiameter = DiameterOfBinaryTree(root.left);\nint rightDiameter = DiameterOfBinaryTree(root.right);\n\nint leftHeight = Height(root.left);\nint rightHeight = Height(root.right);\n</code></pre>\n\n<p>calling <code>DiameterOfBinaryTree</code> on the left and right subtree determines the height of both subtrees, and then calling <code>Height</code> on the subtrees computes those heights again.</p>\n\n<p>This can be improved by defining a helper function which (recursively) computes <em>both</em> height and diameter of a tree rooted at a node:</p>\n\n<pre><code>private (int height, int diam) HeightAndDiameter(TreeNode root)\n{\n if (root == null)\n {\n return (0, 0);\n }\n\n var (leftHeight, leftDiam) = HeightAndDiameter(root.left);\n var (rightHeight, rightDiam) = HeightAndDiameter(root.right);\n\n return (Math.Max(leftHeight, rightHeight) + 1,\n Math.Max(Math.Max(leftDiam, rightDiam), leftHeight + rightHeight));\n}\n</code></pre>\n\n<p>C# <em>(named) tuples</em> are used here to return both values to the caller. The main function then becomes</p>\n\n<pre><code>public int DiameterOfBinaryTree(TreeNode root)\n{\n return HeightAndDiameter(root).diam;\n}\n</code></pre>\n\n<p>Each node is visited exactly once now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T08:32:45.307",
"Id": "230738",
"ParentId": "230724",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230738",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T21:16:07.440",
"Id": "230724",
"Score": "3",
"Tags": [
"c#",
"programming-challenge",
"tree"
],
"Title": "LeetCode: Diameter of Binary Tree"
}
|
230724
|
<p>I'm using a <code>NamedTuple</code> to represent the state of my game while it's running. The user can alter these settings using key presses, so in my PyGame key handler, I'm writing things like:</p>
<pre><code>if key_code == 273: # Up arrow
return game_settings._replace(fps=game_settings.fps + 5)
</code></pre>
<p>Each key press transforms the settings state by using the old value and <code>_replace</code>.</p>
<p>I decided to try and emulate <a href="https://clojuredocs.org/clojure.core/update" rel="nofollow noreferrer">Clojure's <code>update</code> function</a> as an exercise, and because it may actually make more code more readable. It takes a function and a key, and updates the value at that key using the function. Example usage:</p>
<pre><code>>>> sett = GameSettings(fps=30, is_running=True)
>>> sett.update(lambda x: not x, "is_running")
GameSettings(fps=30, is_running=False)
>>> sett.update2(lambda x: not x, is_running=None)
GameSettings(fps=30, is_running=False)
</code></pre>
<p>I created two different versions that each behave similarly but are slightly different. Version one accepts a string key. Version two accepts kwargs with a dummy value. I'm not super happy with either though. Having to pass a String to Version one fells messy any error prone. If I typo the String, I'll get an <code>AttributeError</code> at runtime. Version two accepting a dummy value also feels off and is also error prone; although I do think it reads nicer without the quotes. The code for each is also quite ugly and dense.</p>
<p>The methods don't actually <em>need</em> to accept more than one key (I'll probably never pass more than one at a time), but I figured it barely changes the algorithm and it mirrors <code>_replace</code>, so I decided why not.</p>
<p>I'd appreciate any thoughts here on how to set this up better or make the code cleaner.</p>
<pre><code>from __future__ import annotations
from typing import NamedTuple, Callable, TypeVar
from functools import reduce
T = TypeVar("T")
class GameSettings(NamedTuple):
fps: int
is_running: bool = True
def update(self, f: Callable[[T], T], *keys) -> GameSettings:
return reduce(lambda acc, k: acc._replace(**{k: f(getattr(acc, k))}), keys, self)
def update2(self, f: Callable[[T], T], **kwargs) -> GameSettings:
return self._replace(**{k: f(getattr(self, k)) for k, _ in kwargs.items()})
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T05:26:41.850",
"Id": "449729",
"Score": "0",
"body": "I'm skeptical that any of this (using an immutable `NamedTuple` and a `lambda`) is a good idea at all. I wish you had shown the rest of the key handler function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T11:10:30.097",
"Id": "449756",
"Score": "0",
"body": "@200_success I used an immutable tuple here just because I like representing things as transformations of an immutable state. I come from a mostly FP background, so that's the thought process that I'm used to. Ya, I could have used a dataclass here and it would have been much simpler. The rest of the key handler is just dispatching onto the keys (more of what I posted at the top)."
}
] |
[
{
"body": "<p>I decided that since I'll likely never need to associate the same function with multiple keys, I might as well just associate the keys with a function directly:</p>\n\n<pre><code>def update3(self, **kwargs: Callable[[T], T]) -> GameSettings:\n return self._replace(**{k: f(getattr(self, k)) for k, f in kwargs.items()})\n\n>>> sett = GameSettings(fps=30, is_running=True)\n\n>>> sett.update3(is_running=lambda x: not x)\nGameSettings(fps=30, is_running=False)\n</code></pre>\n\n<p>The code still isn't beautiful, but it makes a lot more sense when calling now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T00:32:54.777",
"Id": "230729",
"ParentId": "230725",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T22:10:21.907",
"Id": "230725",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Updating NamedTuple members based on a function and previous value"
}
|
230725
|
<p>After getting a CR from @pacmaninbw and @ALX23z <a href="https://codereview.stackexchange.com/questions/230672/program-options-from-command-line-initialize">here</a>, I want to share my new code, and to ask for better ways (which always exist) to improve the code, even with new libraries. The only thing that important to me, is the way of receiving the parameters have to be the command line [I am using Linux OS, so it's highly common to use command line params].</p>
<p>So, to separate the main to smaller functions, alongside avoiding messy functions' parameters handling, I created a class to handle the whole initialize part of the cmd params:</p>
<hr>
<h2>Edit:</h2>
<ul>
<li>I changed the flags implementation so the user won't need to set the flag value (<code>true</code>/<code>false</code>). If the flag exists the value is <code>true</code>, otherwise it'll be set to <code>false</code>.</li>
<li><a href="https://github.com/korelkashri/ComputerActivityLogReading" rel="nofollow noreferrer">The project in GitHub</a>.</li>
<li><a href="https://github.com/korelkashri/ComputerActivityLogReading/tree/fe473409b5f10a25a3f78c4565c424b319bacfc5" rel="nofollow noreferrer">Relative revision at post creation time in GitHub</a>.</li>
<li>Please note the updated code after @pacmaninbw CR: <a href="https://codereview.stackexchange.com/questions/230930/program-options-from-command-line-initialize-v3-after-cr">program options from command line initialize [v3 - after CR]</a></li>
</ul>
<p><strong>cmd_options.h</strong></p>
<pre><code>#ifndef COMPUTERMONITORINGSTATISTICSPARSER_CMD_OPTIONS_H
#define COMPUTERMONITORINGSTATISTICSPARSER_CMD_OPTIONS_H
#include <iostream>
#include <boost/program_options.hpp>
struct cmd_options_data {
explicit cmd_options_data(const std::string &options_description) :
visible_options(options_description) {}
bool help = false; // Show help message
bool verbose = false; // Display login/logout details
bool anomaly_detection = false; // Show anomalies details if found
bool analyze_activity = true; // Analyze login/logout total/summarize times
std::string week_start_day;
std::string log_file_path;
std::string normal_login_word;
boost::program_options::options_description visible_options;
boost::program_options::variables_map variables_map;
};
class cmd_options {
public:
explicit cmd_options(int ac, char* av[]);
cmd_options_data get_data();
private:
boost::program_options::options_description init_cmd_po_generic_options();
boost::program_options::options_description init_cmd_po_calender_options();
boost::program_options::options_description init_cmd_po_logger_options();
boost::program_options::options_description init_cmd_po_hidden_options();
boost::program_options::options_description init_cmd_po_mode_options();
boost::program_options::positional_options_description init_cmd_positional_options();
boost::program_options::options_description group_cmd_options() {
return boost::program_options::options_description();
}
template<class... Args>
boost::program_options::options_description group_cmd_options(const boost::program_options::options_description &option, Args&... options);
void apply_program_options(int ac, char* av[]);
void update_flags();
cmd_options_data _options_data;
boost::program_options::options_description full_options;
boost::program_options::positional_options_description positional_options;
};
template<class... Args>
boost::program_options::options_description cmd_options::group_cmd_options(const boost::program_options::options_description &option, Args&... options) {
boost::program_options::options_description group;
group.add(option);
group.add(group_cmd_options(options...));
return group;
}
#endif //COMPUTERMONITORINGSTATISTICSPARSER_CMD_OPTIONS_H
</code></pre>
<p><strong>cmd_options.cpp</strong></p>
<pre><code>#include "cmd_options.h"
namespace boost_cmd_po = boost::program_options;
cmd_options::cmd_options(int ac, char* av[]) : _options_data("Usage: program [options] [path/]logger_filename") {
auto generic_options = init_cmd_po_generic_options();
auto calender_options = init_cmd_po_calender_options();
auto logger_options = init_cmd_po_logger_options();
auto mode_options = init_cmd_po_mode_options();
auto hidden_options = init_cmd_po_hidden_options();
_options_data.visible_options.add(
group_cmd_options(
generic_options,
calender_options,
logger_options,
mode_options
)
);
full_options.add(
group_cmd_options(
generic_options,
calender_options,
logger_options,
mode_options,
hidden_options
)
);
positional_options = init_cmd_positional_options();
apply_program_options(ac, av);
update_flags();
}
boost_cmd_po::options_description cmd_options::init_cmd_po_generic_options() {
auto group = boost_cmd_po::options_description("Generic options");
group.add_options()
("help,h", "produce help message")
//("verbose", boost_cmd_po::value<bool>(&_options_data.verbose)->default_value(false), "Show detailed times of login.");
("verbose", "Show detailed times of login.");
return group;
}
boost_cmd_po::options_description cmd_options::init_cmd_po_calender_options() {
auto group = boost_cmd_po::options_description("Calender options");
group.add_options()
("week-start-day,d", boost_cmd_po::value<std::string>(&_options_data.week_start_day)->default_value("Monday"), "Week starting day ('--week-start-day help' for a list).");
return group;
}
boost_cmd_po::options_description cmd_options::init_cmd_po_logger_options() {
auto group = boost_cmd_po::options_description("Logger options");
group.add_options();
return group;
}
boost_cmd_po::options_description cmd_options::init_cmd_po_hidden_options() {
auto group = boost_cmd_po::options_description("Logger options");
group.add_options()
("log-path,l", boost_cmd_po::value<std::string>(&_options_data.log_file_path)->default_value( "/home/sherlock/message_from_computer"), "Path to login/logout logger.");
return group;
}
boost_cmd_po::options_description cmd_options::init_cmd_po_mode_options() {
auto group = boost_cmd_po::options_description("Mode options");
group.add_options()
//("analyze-log", boost_cmd_po::value<bool>(&_options_data.analyze_activity)->default_value(true), "Analyze activity - show activity times and summarise activity.")
("no-analyze", "Disable activity analyzing - don't show activity times/summarise.")
//("anomaly-detection", boost_cmd_po::value<bool>(&_options_data.anomaly_detection)->default_value(false), "Check for anomalies in logger.")
("anomaly-detection", "Check for anomalies in logger.")
("normal-login-word", boost_cmd_po::value<std::string>(&_options_data.normal_login_word)->default_value("login"), "For anomaly detector- word that should symbol a login line in login/logout logger (after '+' sign).");
return group;
}
boost_cmd_po::positional_options_description cmd_options::init_cmd_positional_options() {
boost_cmd_po::positional_options_description pd;
pd.add("log-path", -1);
return pd;
}
void cmd_options::apply_program_options(int ac, char **av) {
boost_cmd_po::store(
boost_cmd_po::command_line_parser(ac, av)
.options(full_options)
.positional(positional_options)
.run(), _options_data.variables_map);
boost_cmd_po::notify(_options_data.variables_map);
}
void cmd_options::update_flags() {
_options_data.help = (bool) _options_data.variables_map.count("help");
_options_data.verbose = (bool) _options_data.variables_map.count("verbose");
_options_data.analyze_activity = !(bool) _options_data.variables_map.count("no-analyze");
_options_data.anomaly_detection = (bool) _options_data.variables_map.count("anomaly-detection");
}
cmd_options_data cmd_options::get_data() {
return _options_data;
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/date_time.hpp>
#include "core/day.h"
#include "core/log_handler.h"
#include "utilities/design_text.h"
#include "cmd_options.h"
int main(int ac, char* av[]) {
cmd_options command_line_options(ac, av);
cmd_options_data cmd_data = command_line_options.get_data();
/// --help / -h option handler
if (cmd_data.help) {
std::cout << cmd_data.visible_options << "\n";
return EXIT_SUCCESS;
}
/// --log-path / -l option handler
if (!boost::filesystem::exists(cmd_data.log_file_path))
throw std::runtime_error("Log file path doesn't exist.");
/// --week-start-day / -d option handler
/// Initialize available days list
auto available_days = std::vector<day>{{"sunday", boost::date_time::weekdays::Sunday},
{"monday", boost::date_time::weekdays::Monday},
{"tuesday", boost::date_time::weekdays::Tuesday},
{"wednesday", boost::date_time::weekdays::Wednesday},
{"thursday", boost::date_time::weekdays::Thursday},
{"friday", boost::date_time::weekdays::Friday},
{"saturday", boost::date_time::weekdays::Saturday}};
if (auto selected_day = std::find(available_days.begin(), available_days.end(), boost::to_lower_copy(cmd_data.week_start_day)); selected_day != available_days.end()) { // Selected day exists
log_handler::week_start_day = selected_day->day_symbol;
} else { // Selected day doesn't exists
if (cmd_data.week_start_day == "help") { // Produce help days message
std::cout << "Available days:" << std::endl;
std::cout << "\tSun [Sunday]" << std::endl;
std::cout << "\tMon [Monday]" << std::endl;
std::cout << "\tTue [Tuesday]" << std::endl;
std::cout << "\tWed [Wednesday]" << std::endl;
std::cout << "\tThu [Thursday]" << std::endl;
std::cout << "\tFri [Friday]" << std::endl;
std::cout << "\tSat [Saturday]" << std::endl;
return EXIT_SUCCESS;
}
throw std::runtime_error("Unfamiliar day, for options list use '-d [ --week-start-day ] help'.");
}
// Anomalies detector
auto anomaly_detected = log_handler::anomalies_detector(cmd_data.log_file_path, cmd_data.normal_login_word, cmd_data.anomaly_detection);
if (cmd_data.analyze_activity) // Analyze logger times
log_handler::analyze(cmd_data.log_file_path, cmd_data.verbose);
if (anomaly_detected) // Produce anomalies warning if needed
std::cout << "\n\n" << design_text::make_colored(std::stringstream() << "*** Anomaly detected! ***", design_text::Color::NONE, design_text::Color::RED, true) << std::endl;
return EXIT_SUCCESS;
}
</code></pre>
<h2>Update:</h2>
<p>After @pacmaninbw review, new updated post: <a href="https://codereview.stackexchange.com/questions/230930/program-options-from-command-line-initialize-v3-after-cr">program options from command line initialize [v3 - after CR]</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T00:35:59.337",
"Id": "449712",
"Score": "2",
"body": "This is definitely an improvement, main()'s dependency on `boost::program_options` has been reduced, the implementation can be changed without altering the code in `main()`. I suggest that you add code to main that tests cmd_options and cmd_options_data. Show how they are used within the program, and use the 3 flags that have been created. Test with and without `verbose`, with and without `anomaly_detection` and with and without `analyze_activity`. After this test with 2 of each of the options and then finally test with all 3 options at once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T01:30:00.413",
"Id": "449713",
"Score": "0",
"body": "@pacmaninbw Thanks! I added the full main function with the params process. After a check, all the flags are working correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T03:16:12.100",
"Id": "449827",
"Score": "0",
"body": "Wait tow or three days before going another round. Get more of your application ready. Post more of the program next time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T02:03:00.313",
"Id": "450080",
"Score": "0",
"body": "@pacmaninbw thanks! I would like to continue the CR of the updated version: https://codereview.stackexchange.com/questions/230930/program-options-from-command-line-initialize-v3-after-cr"
}
] |
[
{
"body": "<p>First, thank you for providing the link to your GitHub repository, it allowed a more complete review.</p>\n\n<p>I've noticed a real tendency in the code to avoid creating classes and to use procedural programming rather than object oriented programming. Namespaces are used instead of creating classes. The use of classes and objects can be very powerful, for one thing it allows inheritance and polymorphism. The use of classes can also decouple modules and reduce dependencies, right now the modules are strongly coupled and this has a tendency to prevent necessary changes to the architecture as the program matures and grows.</p>\n\n<p>I've also noticed a rather strong tendency to use <code>auto</code> rather than declaring the proper types. While the <code>auto</code> type is very useful in some cases such as ranged for loops maintaining this code can be more difficult. Personally types help me to understand the code better. I would almost say this code is abusing the use of <code>auto</code>.</p>\n\n<h2>Avoid Using Namespace <code>std</code></h2>\n\n<p>One or more of the source files in the <code>core</code> directory and the <code>utilities</code> directory still contain the <code>using namespace std;</code> statement.</p>\n\n<h2>Complexity</h2>\n\n<p>Once again the function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>This code should probably a function be in <code>day.cpp</code> and the function prototype should be in <code>day.h</code>:</p>\n\n<pre><code> auto available_days = std::vector<day>{{\"sunday\", boost::date_time::weekdays::Sunday},\n {\"monday\", boost::date_time::weekdays::Monday},\n {\"tuesday\", boost::date_time::weekdays::Tuesday},\n {\"wednesday\", boost::date_time::weekdays::Wednesday},\n {\"thursday\", boost::date_time::weekdays::Thursday},\n {\"friday\", boost::date_time::weekdays::Friday},\n {\"saturday\", boost::date_time::weekdays::Saturday}};\n</code></pre>\n\n<p>The function should return a type of <code>std::vector<day></code>;</p>\n\n<p>Or perhaps the function should perform the ensuing search for the day and return the day itself.</p>\n\n<pre><code> auto selected_day = get_selected_day_of_the_week()\n</code></pre>\n\n<h2>Try Catch Throw Blocks</h2>\n\n<p>The code in <code>main()</code> currently contains a <code>throw exception</code> but there is no <code>try{} catch{}</code> code to catch the exception, this will result in the program terminating without reporting the problem. At best in the debugger it will report <code>unhandled exception</code>. The <code>main()</code> code should contain a <code>try</code> block and a <code>catch</code> block to handle any exceptions, the <code>throw</code> statement should probably be called in one of the sub functions that <code>main()</code> calls. If this code stays in <code>main()</code> it might be better to change the throw to std::cerr << \"MESSAGE\" << std::endl.</p>\n\n<h2>Prefer <code>\\n</code> Over <code>std::endl;</code></h2>\n\n<p>For performance reasons <code>\\n</code> is preferred over <code>std::endl</code>, especially in loops where more than one <code>std::cout</code> is expected. <code>std::endl</code> calls a system routine to flush the output buffer. Calling a system function means that the program will be swapped out while the system function is executing.</p>\n\n<pre><code> if (cmd_data.week_start_day == \"help\") { // Produce help days message\n std::cout << \"Available days:\" << std::endl;\n std::cout << \"\\tSun [Sunday]\" << std::endl;\n std::cout << \"\\tMon [Monday]\" << std::endl;\n std::cout << \"\\tTue [Tuesday]\" << std::endl;\n std::cout << \"\\tWed [Wednesday]\" << std::endl;\n std::cout << \"\\tThu [Thursday]\" << std::endl;\n std::cout << \"\\tFri [Friday]\" << std::endl;\n std::cout << \"\\tSat [Saturday]\" << std::endl;\n return EXIT_SUCCESS;\n }\n</code></pre>\n\n<p>was refactored to </p>\n\n<pre><code> if (cmd_data.week_start_day == \"help\") { // Produce help days message\n std::cout << \"Available days:\\n\";\n std::cout << \"\\tSun [Sunday]\\n\";\n std::cout << \"\\tMon [Monday]\\n\";\n std::cout << \"\\tTue [Tuesday]\\n\";\n std::cout << \"\\tWed [Wednesday]\\n\";\n std::cout << \"\\tThu [Thursday]\\n\";\n std::cout << \"\\tFri [Friday]\\n\";\n std::cout << \"\\tSat [Saturday]\" << std::endl;\n return EXIT_SUCCESS;\n }\n</code></pre>\n\n<p>to flush all the output at the end.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T23:36:07.220",
"Id": "449820",
"Score": "0",
"body": "Thanks a lot! Do you think it'll be fine if we go to another round, or just publish here my current state?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T18:25:25.130",
"Id": "230779",
"ParentId": "230728",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230779",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T23:50:09.403",
"Id": "230728",
"Score": "6",
"Tags": [
"c++",
"boost"
],
"Title": "program options from command line initialize [v2 - after CR]"
}
|
230728
|
<p>I recently made this game for rock, paper, scissors in Python 3. Everything works as intended, but I am sure this is not an optimal way of accomplishing this task. Wondering if there is any beginner friendly advice on how to improve upon this. Thank you!</p>
<pre><code>def main():
import random
game_active = True
options = ['Rock', 'Paper', 'Scissors']
print("\nWelcome to Rock, Paper, Scissors!\n\nPlease choose one:\nR for Rock\nP for Paper\nS for Scissors\n")
choice = input("Enter your choice: ")
cpu_choice = random.choice(options)
if choice != 'R' or 'P' or 'S':
print("Invalid choice!")
elif choice == 'R' or 'P' or 'S':
if choice == 'R':
choice = "Rock"
elif choice == 'P':
choice = "Paper"
elif choice == 'S':
choice = "Scissors"
while choice != cpu_choice:
if choice == "Rock":
if cpu_choice == "Paper":
print("\nYou chose rock and the computer chose paper.\nYou lose!")
elif cpu_choice == "Scissors":
print("\nYou chose rock and the computer chose scissors.\nYou win!")
elif choice == "Paper":
if cpu_choice == "Rock":
print("\nYou chose paper and the computer chose rock. \nYou win!")
elif cpu_choice == "Scissors":
print("\nYou chose paper and the computer chose scissors. \nYou lose!")
elif choice == "Scissors":
if cpu_choice == "Rock":
print("\nYou chose scissors and the computer chose rock. \nYou lose!")
elif cpu_choice == "Paper":
print("\nYou chose scissors and the computer chose paper. \nYou win!")
break
while cpu_choice == choice:
print("You chose", choice + "!")
print("Computer chooses", cpu_choice + "!")
break
cont = input("Play again? (Y/N): ")
if cont == 'Y':
main()
else:
print("Thank you for playing!")
main()
</code></pre>
<p>(This is also my first time using a function)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T02:25:26.200",
"Id": "449721",
"Score": "2",
"body": "This code does not work properly, it does not produce errors however, it's not working correctly(all choices entered by the user are 'Invalid choice') and as per rules of this website, it should be working and doing what it's intended to do or it might be considered as an off-topic."
}
] |
[
{
"body": "<h1>Welcome to Python!</h1>\n\n<hr>\n\n<h1>Choosing Rock/Paper/Scissors/</h1>\n\n<p>This</p>\n\n<pre><code>if choice == 'R':\n choice = \"Rock\"\nelif choice == 'P':\n choice = \"Paper\"\nelif choice == 'S':\n choice = \"Scissors\"\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>choice = [option for option in options if option.startswith(choice)][0]\n</code></pre>\n\n<p>Since you're grabbing only the first letter, you can make this comparison, instead of checking each option with its own if statement. This also takes advantage of list comprehension. The array is filled for every value that starts with <code>choice</code>. Since only one value will be in this list, you can simply grab the first value in the list <code>[0]</code>.\n<hr></p>\n\n<h1>Utilizing <code>in</code></h1>\n\n<p>This</p>\n\n<pre><code>if choice != 'R' or 'P' or 'S':\n</code></pre>\n\n<p>can be this</p>\n\n<pre><code>if choice not in \"RPS\":\n</code></pre>\n\n<p>This simply checks if the choice is within the string, reducing the need to check each individual character separately.\n<hr></p>\n\n<h1>Unnecessary <code>while</code></h1>\n\n<p>This</p>\n\n<pre><code>while cpu_choice == choice:\n print(\"You chose\", choice + \"!\")\n print(\"Computer chooses\", cpu_choice + \"!\")\n break\n</code></pre>\n\n<p>is basically an if statement, since it's a check and only run once</p>\n\n<pre><code>if cpu_choice == choice:\n print(\"You chose\", choice + \"!\")\n print(\"Computer chooses\", cpu_choice + \"!\")\n</code></pre>\n\n<p>We can make it even neater using <a href=\"https://cito.github.io/blog/f-strings/\" rel=\"nofollow noreferrer\"><code>string formatting</code></a></p>\n\n<pre><code>if cpu_choice == choice:\n print(f\"You chose {choice}!\")\n print(f\"Computer chooses {cpu_choice}!\")\n</code></pre>\n\n<p>Also this</p>\n\n<pre><code>while choice != cpu_choice:\n</code></pre>\n\n<p>should be this</p>\n\n<pre><code>if choice != cpu_choice:\n</code></pre>\n\n<p><hr></p>\n\n<h1>Imports</h1>\n\n<p>Imports should go outside of functions, and at the top of the module</p>\n\n<pre><code>import random\n\ndef main():\n ... code ...\n</code></pre>\n\n<p><hr></p>\n\n<h1>Better Input Validation</h1>\n\n<p>Right now, you check if the input is valid. If it isn't, you print \"Invalid choice!\". But you don't stop the program. It keeps running with that choice. You can simplify this by using a <code>while</code> loop here, only breaking if the input is valid:</p>\n\n<pre><code>choice = input(\"Enter your choice: \")\nwhile choice not in \"RPS\":\n print(\"Invalid choice!\")\n choice = input(\"Enter your choice: \")\n</code></pre>\n\n<p><hr></p>\n\n<h1>Unused Variables</h1>\n\n<p>This</p>\n\n<pre><code>game_active = True\n</code></pre>\n\n<p>is never used in your program. You should remove this to avoid confusion, as I initially thought this was the flag that determined if the game was to be run again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T01:58:13.553",
"Id": "449715",
"Score": "0",
"body": "Thank you so much! This is exactly the help I was hoping for. I appreciate it very much"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T02:27:28.070",
"Id": "449722",
"Score": "0",
"body": "@Linny The Op's code is not working properly, I don't know whether this might be an off-topic or not however, all inputs entered by the user are 'Invalid choice' which implies this is not working correctly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T01:22:52.027",
"Id": "230731",
"ParentId": "230730",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230731",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T01:03:11.060",
"Id": "230730",
"Score": "2",
"Tags": [
"python",
"beginner",
"rock-paper-scissors"
],
"Title": "Rock Paper Scissors Beginner Python Game"
}
|
230730
|
<p>I've created a simple C++ logging class. It outputs various loglevels, and adjusts output color accordingly. I'm interested in any tips to improve my coding style.</p>
<p>I am especially concerned with my use of <code>#define</code>'s in the bottom of Logger.hpp. I was unable to find another way to pass <code>__FILE__</code> and <code>__LINE__</code> to the function (aside from doing it manually ofcourse), but I would not be suprised if this approach is bad practise.</p>
<p><strong>ConsoleColor.hpp</strong></p>
<pre><code>#include <Windows.h>
namespace AGE
{
enum class BackgroundColor : int
{
Black = 0,
Blue = 16,
Green = 32,
Cyan = 48,
Red = 64,
Magenta = 80,
Brown = 96,
White = 112,
};
enum class ForegroundColor : int
{
Black = 0,
Blue,
Green,
Cyan,
Red,
Magenta,
Brown,
White,
Gray,
Intense_blue,
Intense_green,
Intense_Cyan,
Intense_red,
Intense_magenta,
Yellow,
Intense_white,
};
// Used to combine background and foreground colors
WORD operator &(const BackgroundColor& left, const ForegroundColor& right)
{
return static_cast<WORD>(static_cast<int>(left) + static_cast<int>(right));
}
}
</code></pre>
<p><strong>LoggerSettings.hpp</strong></p>
<pre><code>#pragma once
namespace AGE
{
struct LoggerSettings
{
explicit LoggerSettings(bool should_print_level = true, bool should_print_file_and_line = true,
bool should_print_color = true, bool should_print_time = true) :
print_level(should_print_color),
print_file_and_line(should_print_file_and_line),
print_color(should_print_color),
print_time(should_print_time)
{}
// TODO add ability to display time in Logger.hpp/cpp
bool print_level;
bool print_file_and_line;
bool print_color;
bool print_time;
};
}
</code></pre>
<p><strong>Logger.hpp</strong></p>
<pre><code>#pragma once
#include "LoggerSettings.hpp"
#include <Windows.h>
#include <string>
namespace AGE
{
enum class LogLevel
{
Trace,
Info,
Warn,
Error,
Fatal
};
class Logger
{
public:
Logger();
void set_log_level(const LogLevel level);
LoggerSettings& get_settings();
void explicit_trace(const std::string_view message, const char* file, int line);
void explicit_info (const std::string_view message, const char* file, int line);
void explicit_warn (const std::string_view message, const char* file, int line);
void explicit_error(const std::string_view message, const char* file, int line);
void explicit_fatal(const std::string_view message, const char* file, int line);
private:
void log(const LogLevel level, const std::string_view message, const char* file, int line);
WORD get_color(const LogLevel level);
std::string get_error_string(const LogLevel level);
std::string get_file_name(const char* filepath);
const HANDLE m_console_handle;
LogLevel m_current_log_level;
LoggerSettings m_settings;
};
}
#define trace(message) AGE::Logger::explicit_trace(message, __FILE__, __LINE__)
#define info(message) AGE::Logger::explicit_info(message, __FILE__, __LINE__)
#define warn(message) AGE::Logger::explicit_warn(message, __FILE__, __LINE__)
#define error(message) AGE::Logger::explicit_error(message, __FILE__, __LINE__)
#define fatal(message) AGE::Logger::explicit_fatal(message, __FILE__, __LINE__)
</code></pre>
<p><strong>Logger.cpp</strong></p>
<pre><code>#include "Logger.hpp"
#include "ConsoleColor.hpp"
#include <iostream>
#include <cstdint>
namespace AGE
{
Logger::Logger() :
m_console_handle (GetStdHandle(STD_OUTPUT_HANDLE)),
m_current_log_level(LogLevel::Trace)
{
m_settings = LoggerSettings();
}
void Logger::set_log_level(LogLevel level)
{
m_current_log_level = level;
}
LoggerSettings& Logger::get_settings()
{
return m_settings;
}
void Logger::explicit_trace(const std::string_view message, const char* file, int line)
{
if (m_current_log_level > LogLevel::Trace)
{
return;
}
log(LogLevel::Trace, message, file, line);
}
void Logger::explicit_info(const std::string_view message, const char* file, int line)
{
if (m_current_log_level > LogLevel::Info)
{
return;
}
log(LogLevel::Info, message, file, line);
}
void Logger::explicit_warn(const std::string_view message, const char* file, int line)
{
if (m_current_log_level > LogLevel::Warn)
{
return;
}
log(LogLevel::Warn, message, file, line);
}
void Logger::explicit_error(const std::string_view message, const char* file, int line)
{
if (m_current_log_level > LogLevel::Error)
{
return;
}
log(LogLevel::Error, message, file, line);
}
void Logger::explicit_fatal(const std::string_view message, const char* file, int line)
{
if (m_current_log_level > LogLevel::Fatal)
{
return;
}
log(LogLevel::Fatal, message, file, line);
}
void Logger::log(const LogLevel level, const std::string_view message, const char* file, int line)
{
if (m_settings.print_color)
{
WORD color = get_color(level);
SetConsoleTextAttribute(m_console_handle, color);
}
if (m_settings.print_level)
{
std::cout << "[" << get_error_string(level) << "]";
}
if (m_settings.print_file_and_line)
{
std::cout << "(" << "In " << get_file_name(file) << " at line " << line << ") ";
}
std::cout << message << std::endl;
SetConsoleTextAttribute(m_console_handle, BackgroundColor::Black & ForegroundColor::White);
}
WORD Logger::get_color(const LogLevel level)
{
switch (level)
{
default:
return BackgroundColor::Black & ForegroundColor::White;
break;
case LogLevel::Trace:
return BackgroundColor::Black & ForegroundColor::Intense_white;
break;
case LogLevel::Info:
return BackgroundColor::Black & ForegroundColor::Intense_green;
break;
case LogLevel::Warn:
return BackgroundColor::Black & ForegroundColor::Intense_red;
break;
case LogLevel::Error:
return BackgroundColor::Black & ForegroundColor::Intense_Cyan;
break;
case LogLevel::Fatal:
return BackgroundColor::Black & ForegroundColor::Intense_magenta;
break;
}
}
std::string Logger::get_error_string(const LogLevel level)
{
switch (level)
{
default:
return std::string();
break;
case LogLevel::Trace:
return std::string("Trace");
break;
case LogLevel::Info:
return std::string("Info");
break;
case LogLevel::Warn:
return std::string("Warning");
break;
case LogLevel::Error:
return std::string("Error");
break;
case LogLevel::Fatal:
return std::string("Fatal");
break;
}
}
std::string Logger::get_file_name(const char* filepath)
{
std::string path = std::string(filepath);
int index = 0;
for (int i = static_cast<int>(path.size()) - 1; i > 0; i--)
{
if (path.at(i) == '\\')
{
index = i;
break;
}
}
// For some reason the compiler complains if i dont cast to 64bit int
return std::string(path, static_cast<int64_t>(index) + 1, path.size() - 1);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You lack several features:</p>\n\n<ul>\n<li>logging to files, not just CMD; to this end you'd better make an interface class for logger and pass only pointer to the interface. Otherwise you'll end up with too many if/else and hard-to-maintain code.</li>\n<li>option for printing the time of the message. Even the C++ style support isn't available in C++17 there is a C-style version you can use.</li>\n<li>your logger is not suitable for multi-threading environment (std::cout thread safe but won't necessarily print characters in the order you desire).</li>\n<li>consider switching <code><< std::endl;</code> with <code><< \"\\n\";</code></li>\n<li>functionality that helps user to write the input parameter <code>std::string_view message</code>; since it isn't C++20 and <code>std::format</code> isn't available... current standard methods aren't very convenient. Though, it doesn't have to be a part of the logger and you can just use, say, the same fmt library. Also you might want to avoid making the message at all if logger is going to filtrate it anyways.</li>\n<li>The functionality that determines whether to print the message: add verbose level, don't just rely on the message type. At times you don't care if a low-level function returns a warning or an error, but if you'd still want to print info from a high level function. </li>\n<li>Current version is not portable. Consider making an interface that is portable, even if the implementation isn't - at most make a different class for other platforms when the time comes. Changing interface will be much harder.</li>\n<li><code>Logger::get_error_string</code> why return a <code>std::string</code> and not a <code>std::string_view</code> or <code>const char*</code>? Though, it won't matter much if you have short-string-optimization.</li>\n<li>You don't want every method to be in <code>.cpp</code> consider moving quick ones in the header. This way optimizer has more freedom and will be able to inline them if it chooses to. Though, you shouldn't move everything to header as then compilation times will increase. </li>\n<li><p>Also no need for declaring default constructor, you can just declare default initialization of the class members when you declare the variables</p>\n\n<pre><code>const HANDLE m_console_handle = GetStdHandle(STD_OUTPUT_HANDLE); \nLogLevel m_current_log_level = LogLevel::Trace;\nLoggerSettings m_settings = {};\n</code></pre></li>\n<li><p>About <code>Logger::get_file_name</code> - just use <code>size_t</code> instead of <code>int</code> for <code>index</code> and <code>i</code> to avoid awkward casting. (Though this way you'll have a bug when <code>pathfile</code> is an empty string...) Also, your error/warning configuration is too strict, checkout where you can configure it. It shouldn't be an error but a warning without the casting. Moreover, why not use <code>std::string</code> or <code>std::string_view</code> functions? And this method should be static.</p>\n\n<pre><code>static std::string_view Logger::get_file_name(std::string_view filepath)\n{\n auto index = filepath.find_last_of('\\\\');\n\n if(index != std::string::npos)\n {\n return filepath.substr(0,index);\n }\n\n return {};\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T09:56:32.673",
"Id": "230742",
"ParentId": "230735",
"Score": "3"
}
},
{
"body": "<p>I have a number of suggestions which might help you improve your program.</p>\n\n<h2>Rethink the name</h2>\n\n<p>The name <code>Logger</code> makes me think of creating a log which is a record of something that can be reviewed later. However, that's not what this does. It emits color coded messages to the console instead, so perhaps <code>Logger</code> is not the best term, since there isn't any record created. Maybe <code>Tracer</code> would be a better name.</p>\n\n<h2>Fix the bug</h2>\n\n<p>There is an error in the constructor of <code>LoggerSettings</code>:</p>\n\n<pre><code>print_level(should_print_color),\n</code></pre>\n\n<p>I'm betting that should be <code>should_print_level</code> as the intializer.</p>\n\n<h2>Avoid function-like macros</h2>\n\n<p>In modern C++, there is not much use any more for function-like <code>#define</code> macros. They lack type checking and are prone to error, so I'd avoid using them. In this particular case, they can't really work anyway since they don't allow for a way to specify a particular instance of the <code>Logger</code> class. Bite the bullet and just use <code>__FILE__</code> and <code>__LINE__</code> explicitly as needed. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-macros2\" rel=\"nofollow noreferrer\">ES.31</a> for details.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>get_settings()</code> function doesn't and shouldn't alter the underlying <code>Logger</code> class instance, so it should be declared <code>const</code>. One could make the same argument for the various log functions.</p>\n\n<h2>Make sure you have all required <code>#include</code>s</h2>\n\n<p>The code uses <code>std::string_view</code> but doesn't <code>#include <string_view></code>. It should.</p>\n\n<h2>Use classes to better advantage</h2>\n\n<p>If you defined a <code>Color</code> class, this code might be simplified by relegating color handling functions and data to just that one class. Also, the <code>LoggerSettings</code> class seems rather pointless. I'd just put those member variables directly into the <code>Logger</code> class.</p>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>There is a separate function for each log level and a corresponding color function for each. That is a lot of repeated code. What I'd suggest is that you create a class within the <code>Logger.cpp</code> file something like this:</p>\n\n<pre><code>struct LogLevelData {\n LogLevel level;\n std::string_view name;\n Color color;\n void log(bool print_color, bool print_level, bool print_file_and_line, const std::string_view message, const char* file, int line) const;\n};\n\nstatic constexpr LogLevelData logdata[5]{\n { LogLevel::Trace, \"Trace\", BackgroundColor::Black & ForegroundColor::Intense_white },\n { LogLevel::Info, \"Info\", BackgroundColor::Black & ForegroundColor::Intense_green},\n { LogLevel::Warn, \"Warn\", BackgroundColor::Black & ForegroundColor::Intense_red},\n { LogLevel::Error, \"Error\", BackgroundColor::Black & ForegroundColor::Intense_Cyan},\n { LogLevel::Fatal, \"Fatal\", BackgroundColor::Black & ForegroundColor::Intense_magenta},\n};\n</code></pre>\n\n<p>Now we can delegate most of the work and eliminate duplication:</p>\n\n<pre><code>void Logger::log(const LogLevel level, const std::string_view message, const char* file, int line) {\n if (level >= m_current_log_level) {\n logdata[static_cast<int>(level)].log(print_color, print_level, print_file_and_line, message, file, line);\n }\n}\n</code></pre>\n\n<h2>Use include guards</h2>\n\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n\n<pre><code>#ifndef LOGGER_H\n#define LOGGER_H\n// file contents go here\n#endif // LOGGER_H\n</code></pre>\n\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a></p>\n\n<h2>Streamline the interface</h2>\n\n<p>One way to rewrite your <code>Logger.hpp</code> file is like this:</p>\n\n<pre><code>#ifndef LOGGER_H\n#define LOGGER_H\n#include <string_view>\n\nnamespace AGE\n{\n enum class LogLevel\n {\n Trace,\n Info,\n Warn,\n Error,\n Fatal\n };\n\n class Logger\n {\n public:\n void set_log_level(const LogLevel level);\n void log(const LogLevel level, const std::string_view message, const char* file, int line);\n\n private:\n LogLevel m_current_log_level = LogLevel::Trace;\n bool print_level = true;\n bool print_file_and_line = true;\n bool print_color = true;\n bool print_time = true;\n };\n}\n#endif // LOGGER_H\n</code></pre>\n\n<p>Note that there is no longer any need for an explicit constructor, any macros, references to anything in <code>Windows.h</code> or the <code>LoggerSettings</code> class. It's useful to try for a minimal but sufficient interface that hides as many of the implementation details as practical.</p>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used. Here's the code I eventually used to exercise a rewrite of your class:</p>\n\n<pre><code>#include \"Logger.hpp\"\nint main() {\n AGE::Logger log;\n log.log(AGE::LogLevel::Trace, \"The merest trace\", __FILE__, __LINE__);\n log.log(AGE::LogLevel::Info, \"Some information\", __FILE__, __LINE__);\n log.log(AGE::LogLevel::Warn, \"A warning\", __FILE__, __LINE__);\n log.log(AGE::LogLevel::Error, \"This is an error\", __FILE__, __LINE__);\n log.log(AGE::LogLevel::Fatal, \"Catastrophe!\", __FILE__, __LINE__);\n}\n</code></pre>\n\n<h2>Consider the user</h2>\n\n<p>The colors actually used are, of course, up to you, but I'd suggest that using red for a warning and magenta for a fatal error is rather counterintuitive. Red is traditionally used for the thing that means \"stop\" and in this case, I'd say that's probably a fatal error.</p>\n\n<h2>Be consistent with capitalization</h2>\n\n<p>Of the foreground color list, only <code>Intense_Cyan</code> has the second word capitalized. It's a minor point but inconsistency in the interface is annoying to anyone who later uses this code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T15:28:28.453",
"Id": "230760",
"ParentId": "230735",
"Score": "2"
}
},
{
"body": "<p>One more thing I'd want to add. I don't think you want to use the whole <code>(__FILE__, __LINE__)</code> mess.</p>\n\n<p>In a small codebase, you should be able to easily find the file and line via a simple search while in large codebase file/line info is just not sufficient.\nSay, you have a file used in many places, then printing that an error occurs in this file is not very informative - you'd want the whole callstack or at least some partial ownership information.</p>\n\n<p>So consider adding a second layer over the logger class - one that classes tend to keep a copy of. One that keeps a pointer to the interface; provides the functionality for composing the message from multitude of data; filtrates on-the-root messages that aren't going to be printed; and keeps an \"owner\" or \"callstack\" string and automatically adds it to the message so you can identify who actually prints the message, and not just file/line info.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T12:28:50.057",
"Id": "230953",
"ParentId": "230735",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T05:51:37.687",
"Id": "230735",
"Score": "5",
"Tags": [
"c++",
"logging",
"c++17"
],
"Title": "C++ logging class"
}
|
230735
|
<p>I wanted to create a script that will perform the k_nearest_neighbors algorithm on the well-known iris dataset. This was mainly for me to better understand the algorithm and process. I think it works, but it could definitely use some tuning up. One thing that has me worried was incorporating multiple features into the calculations.</p>
<p>The process that I have utilized:</p>
<ol>
<li>Read the iris.csv into a pandas dataframe</li>
<li>Split the dataframe into a train/test set (0.75/0.25)</li>
<li>Create an instance of the k_nearest_neighbor class and "fit" the training set as a numpy array</li>
<li>In the prediction phase, I first make sure the testing set is a numpy array</li>
<li>Loop through each testing point in the test set</li>
<li>Loop through each training point in the train set</li>
<li>Append the distances to a list using the euclidean distance formula of each training point to the testing point in question. </li>
<li>Sort the list from smallest to largest based on the distances</li>
<li>Slice the list up to k that was chosen (default k is set to 1)</li>
<li>Count the number of classes found in the neighbors and either return the most found class, or a random class if multiple classes have the same counts (only of the classes with the same counts). </li>
<li>Then I simply return a numpy array of the testing dataset but I replace the class it originally had with the predicted one.</li>
</ol>
<p>major concerns:</p>
<ol>
<li>I did not handle multiple features correctly in the calculations</li>
<li>Predictions are coming up a bit less than other sources. </li>
</ol>
<p>I checked the amount that was accurately predicted and it seems to come a bit short compared to other sites and a book I am going through. However, I have noticed that the algorithm does predict a bit better when I split the data by 0.65/0.35. The last bit was me just trying the check the accuracy. I am hoping another pair of eyes could let me know what I may have missed or done wrong, thanks for any help!</p>
<p>iris dataset -> <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" rel="nofollow noreferrer">https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data</a></p>
<pre class="lang-py prettyprint-override"><code>import random
from operator import itemgetter
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def read_dataset_csv(dataset_path: str):
"""
This is a function that will read a csv and return a pandas dataframe
TODO: add functionality to accept other formats
:param dataset_path:
:return:
"""
return pd.read_csv(dataset_path)
def split_train_test(dataframe,split=0.75, random_state=0):
"""
This is a function that will split a pandas dataframe into a testing/training dataset.
:param dataframe: pandas dataframe
:param random_state: random state seed, set to 0 by default
:return: training dataframe and a testing dataframe
"""
dataframe_copy = dataframe.copy()
train_set = dataframe_copy.sample(frac=split, random_state=random_state)
test_set = dataframe_copy.drop(train_set.index)
return train_set, test_set
def convert_class_str_to_class_int(classes):
"""
This is a function that will take a set of classes and return a dictionary where the class name is the key
and the index of the class found within the set is the value.
:param classes:
:return:
"""
classes_dict = dict()
for index, class_str in enumerate(classes):
classes_dict[class_str] = int(index)
return classes_dict
class k_nearest_neighbors():
"""
This is a class that houses methods and variables for the k_nearest_neighbor algorithm.
TODO: Add pairplots
"""
def fit(self, training_dataframe):
"""
This is a function that will fit a training set of data to the class. It accepts a pandas dataframe and pulls
the data, classes, and features from the dataframe.
:param training_dataframe: pandas dataframe
:return: None
"""
self.classes = set(training_dataframe["class"].tolist())
self.features = list(training_dataframe.columns.values)
classes_dict = convert_class_str_to_class_int(self.classes)
training_dataframe = training_dataframe.replace(classes_dict)
self.data = training_dataframe.to_numpy()
def plot(self, x_feature, y_feature):
"""
This is a function that will plot two features of a given dataset.
:param x_feature: name of the desired x feature
:param y_feature: name of the desired y feature
:return: None
"""
x_index = self.features.index(x_feature)
y_index = self.features.index(y_feature)
plt.scatter(self.data[:, x_index], self.data[:, y_index], c=self.data[:, -1], cmap="brg")
plt.xlabel(x_feature)
plt.ylabel(y_feature)
plt.show()
def predict(self, test_data, factor_length, k):
"""
This is a function that will predict what a series of points are based on training data that was already
fitted to the k_nearest_neighbors instance.
:param test_data: test dataset
:param factor_length: number of factors to consider
:param k: number of neighbors to consider
:return: numpy array of test data points with predicted classes
"""
try:
classes_dict = convert_class_str_to_class_int(self.classes)
test_data = test_data.replace(classes_dict)
test_data = test_data.to_numpy()
except AttributeError:
pass
def aggregate_neighbors(neighbors: list):
"""
This function takes all the neighbors found closest to the test data point of interest and takes a count of
the number of classes found from each neighbor. If multiple classes have the same counts, then those classes
are chosen at random.
:param neighbors: neighbors found closest to the test data point
:return: most counted class (or randomly selected from multiple classes)
"""
class_list = list()
class_dict = dict()
for neighbor in neighbors:
class_list.append(neighbor[1])
unique_classes = set(class_list)
for unique_class in unique_classes:
count = class_list.count(unique_class)
class_dict[unique_class] = count
largest_class_value = 0
largest_class = None
multiple_classes_list = list()
for key, value in class_dict.items():
if largest_class is None or value > largest_class_value:
largest_class_value = value
largest_class = key
multiple_classes_list = [key]
elif value == largest_class_value:
multiple_classes_list.append(key)
if len(multiple_classes_list) > 1:
choice = random.choice(multiple_classes_list)
return choice
return largest_class
def euclidean_distance(test_point, train_point, length):
"""
This is a function that will calculate the euclidean distance for each factor.
:param test_point: the test point of interest
:param train_point: the train point of interest
:param length: number of factors to consider
:return: distance between the test_point and train_point
"""
distance = 0
for x in range(length):
distance += pow(test_point[x] - train_point[x], 2)
return math.sqrt(distance)
predicted_points = list()
for index, testing_point in enumerate(test_data):
neighbors = list()
for training_point in self.data:
distance = euclidean_distance(testing_point, training_point, factor_length)
neighbors.append([distance, training_point[-1]])
neighbors = sorted(neighbors, key=itemgetter(0))
final_k_neighbors = neighbors[:k]
prediction = aggregate_neighbors(final_k_neighbors)
predicted_point = list(testing_point[:-1])
predicted_point.append(prediction)
predicted_points.append(predicted_point)
return np.array(predicted_points)
if __name__ == "__main__":
dataset_path = "iris.csv"
df = read_dataset_csv(dataset_path)
train_set, test_set = split_train_test(df)
knn = k_nearest_neighbors()
knn.fit(train_set)
classes_dict = convert_class_str_to_class_int(knn.classes)
test_set_nump = test_set.replace(classes_dict)
test_set_nump = test_set_nump.to_numpy()
predictions = knn.predict(test_set_nump, 4, 1)
misclassed = 0
correct_classed = 0
for test_point, predict_point in zip(test_set_nump, predictions):
if test_point[-1] == predict_point[-1]:
correct_classed += 1
else:
misclassed += 1
print(f"correctly classed: {correct_classed}\nmisclassed: {misclassed}")
print(f"test prediction: {correct_classed/len(test_set)}")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:41:43.240",
"Id": "449768",
"Score": "1",
"body": "Does this code work to the best of your knowledge? If the answer is no then I suggest you post your question in stack overflow which might be more suitable for non-working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T01:52:42.050",
"Id": "450364",
"Score": "0",
"body": "Welcome to Code Review! We don't review code unless it accomplishes the goal for which it was written. unfortunately we also don't allow for changing the code after answers were given if they invalidate the answers that were given. Please feel free to post a new question when you have fully working code."
}
] |
[
{
"body": "<h1>Order your imports</h1>\n\n<p>Imports should be ordered alphabetically in groups of standard library imports, third-party imports and local project imports:</p>\n\n<pre><code>import math\nfrom operator import itemgetter\nimport random\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n</code></pre>\n\n<h1>Make use of comprehensions</h1>\n\n<p>You can rewrite</p>\n\n<pre><code>def convert_class_str_to_class_int(classes):\n \"\"\"\n This is a function that will take a set of classes and return a dictionary where the class name is the key\n and the index of the class found within the set is the value. \n :param classes:\n :return:\n \"\"\"\n classes_dict = dict()\n for index, class_str in enumerate(classes):\n classes_dict[class_str] = int(index)\n\n return classes_dict\n</code></pre>\n\n<p>as </p>\n\n<pre><code>def get_class_id_mapping(classes):\n \"\"\"\n This is a function that will take a set of classes and return a dictionary where the class name is the key\n and the index of the class found within the set is the value. \n :param classes:\n :return:\n \"\"\"\n return {class_str: index for index, class_str in enumerate(classes)}\n</code></pre>\n\n<p>Note that you do not need to cast for <code>int()</code>, since <code>enumerate()</code> will always yield <code>int</code>s. Also the original name was a bit misleading, as it did not reflect, what the function actually does.<br>\nAlso beware, that <code>set</code>s do not have indices. If the input value is actually a <code>set</code>, the corresponding indices given upon iteration will be in random order.</p>\n\n<h1>Be specific about your error handling</h1>\n\n<p>In this block</p>\n\n<pre><code>try:\n classes_dict = convert_class_str_to_class_int(self.classes)\n test_data = test_data.replace(classes_dict)\n test_data = test_data.to_numpy()\nexcept AttributeError:\n pass\n</code></pre>\n\n<p>it is not clear at which line you'll expect the <code>AttributeError</code> to occur. At the first line? At the last line? At any of the three lines?</p>\n\n<h1>Use a main() function</h1>\n\n<p>Put the stuff, that you have under the <code>if __name__ = '__main__'</code> guard into a <code>def main():</code> function and place its call there.</p>\n\n<p>Other than that, your code looks pretty good. The docstrings are informative, the methods mostly named feasibly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T13:52:04.350",
"Id": "230754",
"ParentId": "230740",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T09:09:50.087",
"Id": "230740",
"Score": "2",
"Tags": [
"python",
"numpy",
"pandas",
"machine-learning"
],
"Title": "K_nearest_neighbors from scratch"
}
|
230740
|
<p>I currently got into coding and I am completely self taught. Since I know that my code is far from being perfect, I am asking for advice and tips on how to improve. Feel free to drop in any comments related to the topic - any helpful advice and food for thought is highly appreciated.
It doesn't matter if the advice is regarded to my html file, my JavaScript syntax or my css skills. I really want to improve and every help is great!</p>
<p>Edit: I uploaded a demo to my workspace that you can visit under: <a href="https://cedricjansen.com" rel="nofollow noreferrer">https://cedricjansen.com</a></p>
<p>Here is an image so that you can better understand about what i am talking:
<a href="https://i.stack.imgur.com/AbLiS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AbLiS.png" alt="MeadowJS in Chrome Browser"></a></p>
<p>So let my try to explain my concept.
I created a <strong>div</strong> with the <strong>id="meadow"</strong> where you can specify an interval as attribute as well as the width and the height of the div.
All images are later 'drawn' to this div, so it acts as a container and wrapper.</p>
<p>Then I created a <strong>tab container</strong> with the <strong>id="meadow-tabs"</strong> which contains all tabs. Tabs are little dots, which are shown at the bottom of the main div and each dot refers to one image. The dot with the image that is currently displayed is highlighted and marked with the class <strong>active-tab</strong>.</p>
<p>When the html file is loaded, all images get preloaded and then the first image ( depends on which tab is active on start ) gets displayed. Now you can either wait the specified interval until the image changes itself or you can click one of the tabs to jump to a certain image immediately.</p>
<p>The pause button can stop and resume the interval.</p>
<p><strong>INDEX.HTML</strong></p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="meadow.css">
</head>
<body >
<!-- The image container to which the images are drawn -->
<div id="meadow" class="meadow demo banner" interval="5000" m-width="100%" m-height="100%">
<!-- The loader which is hidden after the images are preloaded -->
<div id="meadow-load" class="meadow-loader"></div>
<!-- Pause Button -->
<div id="meadow-pause" class="pause-tab"></div>
<!-- The Tab Container -->
<div id="meadow-tabs" class="tabs-bottom" show>
<!-- The single tabs which contain the image paths and an index -->
<div class="meadow-tab active-tab"
image="./images/img1.jpg"
index="0">
</div>
<div class="meadow-tab"
image="./images/img2.jpg"
index="1">
</div>
<div class="meadow-tab"
image="./images/img3.jpg"
index="2" >
</div>
</div>
</div>
<script src="meadow.js" type="text/javascript"></script>
</body>
</html>
</code></pre>
<p><strong>MEADOW.JS</strong></p>
<pre><code>var tabs = [];
var fetchedImages = [];
var imageUrls = [];
var images = [];
var carouselIndex = [];
var meadow;
var pauseTab = document.getElementsByClassName('pause-tab')[0];
pauseTab.addEventListener("click", pausePlay);
const meadowDom = document.getElementById('meadow');
//Gets the interval time.
const interval = meadowDom.getAttribute('interval');
const banner = document.getElementsByClassName('banner')[0];
//Grabs the attributes from the html file for width and height
const width = meadowDom.getAttribute('m-width');
const height = meadowDom.getAttribute('m-height');
//Looks if the the attribute show is present;
const showTabs = document.getElementById("meadow-tabs").hasAttribute('show');
//If the attribute show is not present, hide the tabs
if(!showTabs)
{
document.getElementById("meadow-tabs").style.display = "none";
}
//Set the custom height and width of the banner container, to which the images are drawn.
banner.style.height = height;
banner.style.width = width;
var loader = document.getElementById("meadow-load");
//Get all Tabs
var fetchedTabs = document.getElementById("meadow-tabs").querySelectorAll('.meadow-tab');
for( var i = 0; i < fetchedTabs.length; i++ )
{
//Push all Image Links from the tabs to the ImageUrls array to preload them
imageUrls.push(fetchedTabs[i].getAttribute('image'));
}
//Preloads the images
preload(imageUrls);
// Shows the first image of the active tab
initImage();
for( var i = 0; i < fetchedTabs.length; i++)
{
fetchedTabs[i].addEventListener("click", toggleTab);
}
// Function used then pause button is clicked. Toggles between
// pausing and resuming the carousel.
function pausePlay()
{
if(pauseTab.classList.contains('active'))
{
pauseTab.classList.remove('active');
meadow = setInterval(play, interval);
}
else
{
pauseTab.classList.add('active');
clearInterval(meadow);
}
}
// Used when a certain tab is clicked. If the tab is not activated,
// activate it and deactive the current activated tab.
// Checks if the carousel is paused. If yes, keep it paused, if no
// continue from there with the given interval time.
function toggleTab()
{
if( event.target.classList.contains('.active-tab'))
{
return;
}
var activeTab = document.getElementsByClassName('active-tab');
console.log(activeTab);
activeTab[0].classList.remove('active-tab');
event.target.classList.add('active-tab');
console.log("EVENT: " + event.target);
changeImage(event.target);
clearInterval(meadow);
if(!pauseTab.classList.contains('active'))
{
meadow = setInterval(play, interval);
}
}
// Function which removes the active tab.
function removeActiveTab()
{
var activeTab = document.getElementsByClassName('active-tab');
activeTab[0].classList.remove('active-tab');
}
//Function to change the image.
function changeImage( tabToChangeTo )
{
var imageToChangeTo = tabToChangeTo.getAttribute('image');
banner.style.backgroundImage = "url('" + imageToChangeTo + "')" ;
}
//Used in the play function to continue to the next tab and change the image.
function changeInPlay( indexToChangeTo )
{
var tab = document.querySelectorAll('[index="'+ indexToChangeTo + '"]')[0];
changeImage(tab);
removeActiveTab();
tab.classList.add('active-tab');
}
//Display the first image of the first active tab.
function initImage()
{
var activeTab = document.getElementsByClassName('active-tab')[0];
var activeImage = activeTab.getAttribute('image');
banner.style.backgroundImage = "url('" + activeImage + "')" ;
}
// Used in setInterval to iterate over the tabs and show the different images.
function play()
{
var activeTab = document.getElementsByClassName('active-tab')[0];
var activeIndex = activeTab.getAttribute('index');
var nextIndex;
if( activeIndex == (fetchedTabs.length - 1))
{
nextIndex = 0;
}
else
{
nextIndex = +activeIndex + 1;
}
changeInPlay(nextIndex);
}
function preload( urls ) {
for (var i = 0; i < urls.length; i++) {
//Preload the images from the passed urls and keep them in a reference
// so that they aren't erased from storage.
images[i] = new Image();
images[i].src = urls[i];
}
//Hide the carousel loader after images are preloaded.
loader.style.display = 'none';
}
//Set the initial interval for images to change.
meadow = setInterval(play, interval);
</code></pre>
<p><strong>MEADOW.CSS</strong> </p>
<pre class="lang-css prettyprint-override"><code>html
{
width: 100%;
height: 100%;
}
html body
{
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
.meadow.demo.banner
{
width: 100%;
height: 100%;
min-height: 100px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: black;
position: relative;
background-size: cover;
}
.meadow.demo.banner .meadow-loader
{
position: absolute;
width: 20px;
height: 20px;
border-radius: 10px;
background-color:white;
animation: meadow-pulse 2s infinite;
}
@keyframes meadow-pulse
{
0%
{
opacity: 0;
}
50%
{
opacity: 0.8;
}
100%
{
opacity: 0;
}
}
.meadow.demo.banner .pause-tab
{
position: absolute;
width: 20px;
height: 20px;
border-radius: 20px;
background-color: white;
left: 10px;
bottom: 10px;
opacity: 0.5;
}
.meadow.demo.banner .pause-tab:hover
{
cursor: pointer;
}
.meadow.demo.banner .pause-tab.active
{
opacity: 1;
}
.meadow.demo.banner .tabs-bottom
{
width: auto;
min-width: 45px;
max-width: 100px;
position: absolute;
min-height: 15px;
height: 5%;
display: flex;
justify-content: center;
align-items: center;
bottom: 5px;
background-color: rgba(152, 152, 152, 0.5);
border-radius: 10px;
}
.meadow.demo.banner .tabs-bottom .meadow-tab
{
min-width: 7px;
min-height: 7px;
border-radius: 5px;
margin-left: 2px;
margin-right: 2px;
background-color: black;
}
.meadow.demo.banner .tabs-bottom .meadow-tab:hover
{
cursor: pointer;
}
.meadow.demo.banner .tabs-bottom .meadow-tab.active-tab
{
background-color: white;
}
.meadow.demo.cover
{
width: 100%;
height: 100%;
background-color: black;
}
</code></pre>
<p>If anyone finds this post and wants to build their own carousel/ image slider, feel free to use any of this code and rebuild it to your needs.</p>
<p>FYI: I called it meadow because I was sitting by a meadow when I came up with the idea to try to build a image slider thingy.</p>
<p>Thank you for your help!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T10:31:15.103",
"Id": "449751",
"Score": "1",
"body": "[Code REPL](https://jsitor.com/zWNSgj2ZB)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T09:12:42.937",
"Id": "230741",
"Score": "3",
"Tags": [
"javascript",
"html",
"css",
"image"
],
"Title": "Simple vanilla JavaScript Carousel with tabs and pause button"
}
|
230741
|
<p>I've seen variations of this assignment where you reverse a string to match it to the original to find out if it is a palindrome, but this version I made only iterates through half of the string comparing it in reverse and would terminate the loop as soon as it notices a difference between the mirrored char and the current one in the index loop. This causes fewer loops than a reversal of the string.</p>
<ul>
<li>There is a statement with a ternary operator and a modulus that could be perceived as hard to read.</li>
</ul>
<p>Is there a better way than comparing chars?
If you saw this in a code test as an answer, what would you assess this as?
Is the more complex line with the ternary operator showing a more advanced knowledge of options or is it only hard to read?</p>
<p>Any other comments are welcome!</p>
<pre class="lang-java prettyprint-override"><code>public boolean checkPalindrome(String word) {
boolean palindrome = true;
int wordLength = word.length() - 1;
// If the word is dividable by 2 return half else return half including the middle char
int halfWord = word.length() % 2 == 0? (word.length()/2) : ((int) word.length()/2) + 1 ;
for(int i = 0; i < halfWord; i++) {
char first = word.toLowerCase().charAt((wordLength - i));
char last = word.toLowerCase().charAt(i);
if(!(first == last)) {
palindrome = false;
break;
}
}
return palindrome;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T10:41:42.033",
"Id": "449752",
"Score": "0",
"body": "IMHO the speed increase is so small and it is not really worth the reduction in code readability. This is also evident in that you have had to comment the code to describe what it is doing."
}
] |
[
{
"body": "<p>Your basic approach looks good. However I noticed a few things:</p>\n\n<p>You're not checking for strings with 0 characters.</p>\n\n<p>The ternary statement adjusting for odd or even length is unnecessary. Simply dividing by 2 and adding 1 will work for both odd or even lengths.</p>\n\n<p>Inside the loop, you're calling <code>toLower()</code> twice on each iteration. This is quite inefficient. Storing the word converted to lower case in a variable and using that instead of the passed string would be much more efficient.</p>\n\n<p>When testing for inequality it is usually better to use the inequality operator(<code>!=</code>) instead of not(!) and equals(==). It's more concise and easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T11:06:45.990",
"Id": "449755",
"Score": "1",
"body": "Simply dividing by 2 as the middle letter is its own 1 letter \"palindrome\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T11:15:38.653",
"Id": "449757",
"Score": "0",
"body": "@JoopEggen - noted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T11:22:02.987",
"Id": "449758",
"Score": "0",
"body": "Thank you, these were some good pointers!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T11:03:10.623",
"Id": "230748",
"ParentId": "230743",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code> boolean palindrome = true;\n</code></pre>\n</blockquote>\n\n<p>While there are some who swear by this formulation, I find it just makes things more complicated. You don't need a variable to track whether it is a palindrome. If you find a pair of letters that don't match, you can return false immediately. If your method is so long that this is confusing, then it should probably be broken into multiple methods anyway. </p>\n\n<p>I find this easier and more readable with two variables. Putting this advice together with the suggestion to use lower case once rather than twice per iteration (see the <a href=\"https://codereview.stackexchange.com/a/230748/71574\">@tinstaafl answer</a>): </p>\n\n<pre><code> String normalized = word.toLower();\n for (int i = 0, j = normalized.length() - 1; i < j; i++, j--) {\n if (normalized.charAt(i) != normalized.charAt(j)) {\n return false;\n }\n }\n\n return true;\n</code></pre>\n\n<p>This assumes that zero length strings are supposed to be palindromes. If not, you could check for that condition at the beginning of the method. </p>\n\n<p>This code is both shorter and simpler, which makes it easier to read. </p>\n\n<p>You can do other normalizations to the string. For example, it would be reasonable to remove whitespace and punctuation. E.g. this code would currently fail on the input \"Madam, I'm Adam.\" Because the spaces and punctuation won't match (and the capitalization, but you fix that). Of course, it's possible that the task requirements will only give you strings without such extraneous characters. But then why is it giving you a mix of upper and lower case? </p>\n\n<pre><code> String normalized = word.toLower().replaceAll(\"[^\\\\pL]+\", \"\");\n</code></pre>\n\n<p>This will remove everything but letters from the string. So the previous example would become \"madamimadam\" which would match as a palindrome. Which makes sense, as it is one of the classic examples of a <a href=\"https://en.wikipedia.org/wiki/Palindrome\" rel=\"nofollow noreferrer\">palindrome</a>. </p>\n\n<h3>See also</h3>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/9872002/6660678\">Keep only alphabet characters</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T12:34:37.300",
"Id": "230750",
"ParentId": "230743",
"Score": "2"
}
},
{
"body": "<p>A common problem for \"western\" programmers is the inability to process letters that consist of <a href=\"https://stackoverflow.com/questions/5903008/what-is-a-surrogate-pair-in-java\">multiple characters</a>. Your approach will fail if it encounters one of those.</p>\n\n<p>Unfortunately, the String class does not contain a reverse operation so once you have stripped the original string from punctuation and whitespace and converted it to upper or lower case, you have to go through StringBuilder:</p>\n\n<pre><code>final StringBuilder reverse = new StringBuilder(original).reverse();\nreturn reverse.toString().equals(original);\n</code></pre>\n\n<p>There is no point in reinventing the wheel and making it square. :)</p>\n\n<p>If this was an assignment in array or string manipulation, you can give this as a feedback to your professor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:43:00.390",
"Id": "449849",
"Score": "0",
"body": "Reinventing the wheel in this case is for fun, but it's a good point if you want to do the reverse string version to just use a SB. I will keep that in mind, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:05:27.967",
"Id": "230809",
"ParentId": "230743",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230748",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T10:19:08.013",
"Id": "230743",
"Score": "0",
"Tags": [
"java",
"palindrome"
],
"Title": "Basic Palindrome check comparing chars"
}
|
230743
|
<h2>Problem explanation</h2>
<p>I've written a function to validate sudoku. Given a two-dimensional 9×9 array of numbers:</p>
<ul>
<li>Each <strong>row</strong> should have each of the numbers 1–9 exactly once.</li>
<li>Each <strong>column</strong> should have each of the numbers 1–9 exactly once.</li>
<li>Each <strong>square</strong> should have each of the numbers 1–9 exactly once.</li>
</ul>
<pre><code> · · · | · · · | · · ·
· · · | · · · | · · ·
· · · | · · · | · · ·
-------+-------+-------
· · · | · · · | · · ·
· · · | · · · | · · ·
· · · | · · · | · · ·
-------+-------+-------
· · · | · · · | · · ·
· · · | · · · | · · ·
· · · | · · · | · · ·
</code></pre>
<h2>Queries</h2>
<ul>
<li>Is there a better way to approach the problem than creating arrays for columns and squares and validating those individually?</li>
<li>Is there a better way of creating the column arrays than running a neste loop and using the loop indices as co-ordinates?</li>
<li>Is there a better way of creating the square arrays than using the <code>squareAnchors</code> and running a nested loop, using the indices as offsets?</li>
</ul>
<p>If they are more succinct/readable, functional approaches are also welcome.</p>
<h2>Code</h2>
<pre><code>function isValidSudoku(sudoku: sudoku): boolean {
const rows = sudoku;
const columns = [];
const squares = [];
for (let r = 0; r < 9; r++) {
const column = [];
for (let c = 0; c < 9; c++) {
column.push(rows[c][r]);
}
columns.push(column);
}
// Co-ordinates of top-left elements of squares
const squareAnchors = [
[0, 0], [3, 0], [6, 0],
[0, 3], [3, 3], [6, 3],
[0, 6], [3, 6], [6, 6]
];
for (const anchor of squareAnchors) {
const square = [];
const [x, y] = anchor;
for (let offsetX = 0; offsetX < 3; offsetX++) {
for (let offsetY = 0; offsetY < 3; offsetY++) {
square.push(rows[x + offsetX][y + offsetY]);
}
}
squares.push(square);
}
const rowsValid = rows.every(isArrayValid);
const columnsValid = columns.every(isArrayValid);
const squaresValid = squares.every(isArrayValid);
if (rowsValid && columnsValid && squaresValid) {
return true;
}
return false;
}
</code></pre>
<hr>
<p><code>isArrayValid</code>:</p>
<pre><code>function isArrayValid(array: row): boolean {
const oneThroughNine = [1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.sort();
for (let i = 0; i < 9; i++) {
if (array[i] !== oneThroughNine[i]) return false;
}
return true;
}
</code></pre>
<p><code>types/sudoku.ts</code>:</p>
<pre><code>import row from './row';
type sudoku = [
row, row, row, row, row, row, row, row, row
];
export default sudoku;
</code></pre>
<p><code>types/row.ts</code>:</p>
<pre><code>type row = [number, number, number, number, number, number, number, number, number];
export default row;
</code></pre>
<h2>Examples</h2>
<pre><code>const validSudoku: sudoku = [
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]
];
</code></pre>
<pre><code>const invalidSudoku: sudoku = [
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 0, 3, 4, 9],
[1, 0, 0, 3, 4, 2, 5, 6, 0],
[8, 5, 9, 7, 6, 1, 0, 2, 0],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 0, 1, 5, 3, 7, 2, 1, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 0, 0, 4, 8, 1, 1, 7, 9]
];
</code></pre>
|
[] |
[
{
"body": "<h2>Inefficient</h2>\n\n<p>Your code has two major inefficiencies due to poor logic order and design </p>\n\n<h2>Unneeded sort</h2>\n\n<p>The sort in <code>isArrayValid</code> will be rather slow and not needed if you write to the <code>oneThroughNine</code> to mark numbers found. Before you mark the number found check if its been marked, if so then the game is invalid.</p>\n\n<pre><code>function isArrayValid(array: row): boolean {\n const mustInclude = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; // except for 0\n\n for (const val of array) {\n if (!mustInclude[val]) { return false }\n mustInclude[val] = 0; // mark the position as found\n }\n return true; \n}\n</code></pre>\n\n<h3>Processing when the result is known</h3>\n\n<p>At the bottom of the main function you check rows, columns, and squares. The problem is that if one of the rows is invalid you will still end up checking the columns and squares even though you know that the game is invalid.</p>\n\n<p>If you place the rows, columns, and squares in an array and test it with Array.every you can exit on the first bad set.</p>\n\n<pre><code>return [rows, columns, squares].every(set => set.every(isArrayValid));\n</code></pre>\n\n<p>However...</p>\n\n<h3>Don't create data before you need it,</h3>\n\n<p>You create and hold the columns and square before you check rows, they may not be needed as rows may find an invalid game.</p>\n\n<p>Nor do you need to keep each column and square. Check them as you create them, no point creating 9 columns if the first of them is invalid. Same with the squares</p>\n\n<p>I also changed the name of <code>isArrayValid</code> to <code>isInvalid</code> to avoid having to use <code>!</code> each time the set is tested</p>\n\n<pre><code>function isValidSudoku(sudoku: sudoku): boolean {\n if (sudoku.some(isInvalid)) { return false }\n\n for (let r = 0; r < 9; r++) {\n const column = [];\n for (let c = 0; c < 9; c++) { column.push(sudoku[c][r]) }\n if (isInvalid(column)) { return false }\n\n }\n const squareAnchors = [[0, 0], [3, 0], [6, 0], [0, 3], [3, 3], [6, 3], [0, 6], [3, 6], [6, 6]];\n\n for (const [x, y] of squareAnchors) {\n const square = [];\n for (let ix = 0; ix < 3; ix++) {\n const row = sudoku[x + ix];\n for (let iy = 0; iy < 3; iy++) { square.push(row[y + iy]) }\n }\n if (isInvalid(square)) { return false }\n }\n return true;\n}\nfunction isInvalid(set: row): boolean {\n const mustInclude = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; // except for 0\n\n for (const val of set) {\n if (!mustInclude[val]) { return true }\n mustInclude[val] = 0; // mark the position as found\n }\n return false; \n} \n</code></pre>\n\n<p>There are many other things that could be done to improve the code like</p>\n\n<ul>\n<li>Checking each value as you create the column and square arrays.</li>\n<li>Using a bitfield rather than an array to mark of included values.</li>\n<li>Have the input array as a single dimension (flat) so you don`t have to do all the double indexing and nested loops.</li>\n</ul>\n\n<p>But you would only do that if you had millions of games to check and needed every ounce of performance. The further optimizations are only going to give you a few percentage point improvement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T13:49:29.080",
"Id": "230753",
"ParentId": "230745",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230753",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T10:36:03.013",
"Id": "230745",
"Score": "1",
"Tags": [
"typescript",
"sudoku"
],
"Title": "Sudoku validation"
}
|
230745
|
<p>My task is to write a simple shop. The requirements are : </p>
<ul>
<li>It can have multiple items</li>
<li>Each item its own price and quantity</li>
<li>Each customer basic identifier such as full name</li>
<li>Each customer receives clear receipt</li>
<li>Shop keeps the shopping history </li>
</ul>
<p>It's meant to be flexible, easy to expand, high performance considered. I'd be grateful if someone could review it and point out what can/should be improved or changed. Thanks!</p>
<pre><code>#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <list>
using namespace std;
class receipt {
private:
string prodName;
int quant;
public:
receipt(const string& prdNm, int qnt)
: prodName(prdNm), quant(qnt)
{}
string getProdName() const { return prodName; }
int getQuant() const { return quant; }
};
class client {
private:
string name;
vector<receipt> receipts;
public:
client(const string& n): name(n) {}
string getName() const { return name; }
void takeReceipt (const string& prodName, int quant){
receipts.push_back( receipt(prodName, quant) );
}
void printReceipts(int num) const {
// printing receipts
}
bool operator< (const client& c) const {
return name < c.name;
}
};
class product {
private:
string name;
int price;
public:
product(const string& n, int p): name(n), price(p) {}
string getName() const { return name; }
int getPrice() const { return price; }
bool operator< (const product& p) const {
return name < p.name;
}
};
class record {
private:
string clientName;
string prodName;
int quant;
public:
record(const string& clNm, const string& prdNm, int qnt)
: clientName(clNm), prodName(prdNm), quant(qnt)
{}
string getClientName() const { return clientName; }
string getProdName() const { return prodName; }
int getQuant() const { return quant; }
};
class shop {
private:
set<client> clients;
map<product, int> products;
list<record> records;
public:
void addClient(const client& cli) {
clients.insert(cli);
}
void removeClient(const client& cli) {
clients.erase(cli);
}
void addProduct(const product& pr, int quant) {
products[pr] += quant;
}
void removeProduct(const product& pr, int quant) {
if (products[pr] <= quant)
products[pr] = 0;
else
products[pr] -= quant;
}
void doTransaction(client& cli, const product& prod, int quant) {
if ( clients.find(cli.getName()) == clients.end() )
{
// client is not on the list of valid clients.
return;
}
if (products[prod] >= quant)
{
// client is buying
products[prod] -= quant;
records.push_back( record(cli.getName(), prod.getName(), quant) );
cli.takeReceipt(prod.getName(), quant);
}
else
{
// product not available in the quantity
}
}
void printClients() const {
// printing all the clients
}
void printRecords(int num) const {
// Printing last records of previous transactions
}
void printProducts() const {
// Printing all the available products
}
};
int main(){
shop s;
client cm("Mike"), cj("John"), ca("Andy");
product pot("potatoe", 5), app("apple", 7), nut("nut", 3);
s.addClient(cm);
s.addClient(cj);
s.addClient(ca);
s.addProduct(pot, 100);
s.addProduct(app, 50);
s.addProduct(nut, 20);
s.removeClient(ca);
s.removeProduct(pot, 20);
s.removeProduct(nut, 20);
s.doTransaction(cm, pot, 30);
s.doTransaction(cj, app, 10);
s.doTransaction(cm, nut, 5);
s.doTransaction(cm, app, 5);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T15:38:14.897",
"Id": "449790",
"Score": "1",
"body": "I am confused about some of the naming and ownership. For example, I would think a Receipt would have a Client and vector of Product, and that a Product would have name, price, and quantity. Also, I think that Receipt will need to store price, so that the records can be accurate if the price changes over time."
}
] |
[
{
"body": "<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't do <code>using namespace std;</code></a></p>\n\n<p>Qualify names properly with <code>std::</code> where necessary.</p>\n\n<hr>\n\n<pre><code>string getProdName() const { return prodName; }\nint getQuant() const { return quant; }\n</code></pre>\n\n<p>Avoid abbreviations as they harm code clarity. Most IDE's provide auto-completion, so abbreviations don't save typing anyway.</p>\n\n<hr>\n\n<pre><code>receipt(const string& prdNm, int qnt)\n : prodName(prdNm), quant(qnt)\n{}\n</code></pre>\n\n<p>The initializer list allows you to use the same name for the function argument as for the member variable, so this would be fine:</p>\n\n<pre><code>receipt(std::string productName, int quantity)\n : productName(std::move(productName)), quantity(quantity)\n{}\n</code></pre>\n\n<p>(Since the product name is a \"sink argument\" (we want to copy and store it locally), we can take it by value and move it into place).</p>\n\n<hr>\n\n<p>I don't think it's a good idea to overload <code>operator<</code> for these classes. These aren't mathematical types, so there's no inherent ordered relationship. It would make just as much sense to sort by product price as by name.</p>\n\n<p>We're using the <code>operator<</code> for sorting in a particular structure, so we want to associate the ordering with that structure, not with the type itself. We can do that using a \"functor\" class to define comparison, and specifying it as a template argument:</p>\n\n<pre><code>struct ProductLessThanByName\n{\n bool operator()(const Product& a, const Product& b) const {\n return a.getName() < b.getName();\n }\n};\n\n...\n\n std::map<Product, int, ProductLessThanByName> products;\n</code></pre>\n\n<hr>\n\n<p><code>record</code> is a rather ambiguous name. Maybe <code>client_purchases</code> or <code>purchase_record</code> or something might be better.</p>\n\n<p>Since we already have the <code>receipt</code> class, that stores product and quantity, we could perhaps use that internally.</p>\n\n<hr>\n\n<p>Although encapsulation is important, people often interpret it as \"make all member variables private and add getter / setter functions\". This is fine for classes that have associated logic in member functions, or where we can't change a member without extra work (we must adhere to the class invariants).</p>\n\n<p>However, it's unnecessary for simple data containers. If we don't want to allow the user to change a member of the <code>product</code> or <code>receipt</code> classes, we can enforce that by giving them a <code>const&</code> to the class. So we can save a lot of work and use plain structs. e.g.:</p>\n\n<pre><code>struct receipt\n{\n std::string productName;\n int quantity;\n};\n</code></pre>\n\n<hr>\n\n<p>It's probably better to use unsigned types for the quantity and price. We don't expect these to ever be negative, and it's easier to rule out invalid values.</p>\n\n<hr>\n\n<p>As far as the design goes, I'm not sure we need to add clients outside of a transaction. I don't think it really makes sense to \"remove\" a client either. We have to keep the transaction history intact.</p>\n\n<p>I think it would be helpful to separate the idea of \"adding a product-type to the database\" from \"adding stock (actual items of a product-type) to the shop\".</p>\n\n<p>As Kyy13 notes in the comments, we need to store the price at which we sold an item in the transaction history.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T01:06:35.143",
"Id": "449823",
"Score": "0",
"body": "Did you mean `operator<` instead of `operator()`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T16:31:02.833",
"Id": "230767",
"ParentId": "230746",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T10:49:51.827",
"Id": "230746",
"Score": "6",
"Tags": [
"c++"
],
"Title": "simple and extendable shop"
}
|
230746
|
<p>I'm trying to write unit tests code for a java class. <a href="/q/230715/9357">The class</a> tests an array for sorted (either way) or not.</p>
<p><strong>Here is the Unit Tests code:</strong></p>
<pre><code>public class SortedOrNotTest
{
@Test
public void test()
{
int[] A = { 32, 32, 32, 32, 32, 32, 32, 32, 34 };
assertEquals(true, SortedOrNot.isSorted(A));
int[] B = { 32, 32, 34, 33 };
assertEquals(false, SortedOrNot.isSorted(B));
int[] C = { 32 };
assertEquals(true, SortedOrNot.isSorted(C));
int[] D = {};
assertEquals(true, SortedOrNot.isSorted(D));
int[] E = { 32, 32, 31, 30, 32 };
assertEquals(false, SortedOrNot.isSorted(E));
}
}
</code></pre>
<p><strong>Here is the Class, it checks an array is sorted or not in either way:</strong></p>
<pre><code>public class SortedOrNot
{
public static boolean isSorted(int[] arr)
{
int n = arr.length;
if(n<2) return true;
int i = 0;
while (i < n - 1 && arr[i] == arr[i + 1]) // same elements at the beginning
{
i++;
}
if (i == n - 1)
return true; // all same elements considered as sorted.
if (arr[i] < arr[i + 1]) // candidate for ascending, non-decreasing
{
i++;
for (; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
else // candidate for descending, non-increasing
{
i++;
for (; i < n - 1; i++)
{
if (arr[i] < arr[i + 1])
return false;
}
return true;
}
}
}
</code></pre>
<p>Tests works, need to make sure that I'm doing in correct way.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:18:54.967",
"Id": "449847",
"Score": "0",
"body": "Since you didn't include the include statements (in what was supposed to be a working code example), are we safe to assume that these are unit tests implemented using the JUnit testing framework? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T11:49:19.293",
"Id": "449868",
"Score": "0",
"body": "What are \"include statements\"? Yes, these tests were implemented using the JUnit testing framework. @TorbenPutkonen"
}
] |
[
{
"body": "<p>I don't see anything wrong with the way you are testing.</p>\n\n<p>You may want to include negative numbers in your test cases. </p>\n\n<p>I prefer to have test cases broken up. It's easier to track down failing tests:</p>\n\n<pre><code>@Test\npublic void testIsSortedSingleNode()\n{\n int[] C = { 32 };\n assertEquals(true, SortedOrNot.isSorted(C));\n}\n</code></pre>\n\n<p>Even in tests you should follow naming standards. Names such as <code>A</code>, <code>B</code> <code>C</code> are not very descriptive. Also they should start with a lower-case letter. <code>result</code> would be a better name. You use the same variable throughout.</p>\n\n<p>Use <code>assertTrue</code> and <code>assertFalse</code> instead of <code>assertEquals(true/false, x)</code>.</p>\n\n<p>IMO <code>arrayLength</code> would be a better name then <code>n</code>. Or you could use <code>arr.length</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T15:44:22.727",
"Id": "230761",
"ParentId": "230751",
"Score": "3"
}
},
{
"body": "<p>Tests like these often involve a lot of copy-pasted boilerplate and that increases tremendously the effort required to maintain the tests. Instead of writing an assert statement for each array or a separate test method for each case, you could store the arrays into two lists; those that should be detected as sorted and those that should not be and process each array in a common test method.</p>\n\n<pre><code>private static final List<int[]> SHOULD_BE_SORTED = Arrays.asList(\n new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE },\n new int[] { Integer.MIN_VALUE, Integer.MIN_VALUE },\n new int[] { Integer.MAX_VALUE, 1 },\n ...\n );\n\n@Test\npublic void shouldBeSorted() {\n for (int i; i < SHOULD_BE_SORTED.size(); i++) {\n final int[] arr = SHOULD_BE_SORTED.get(i);\n final int[] orig = (int[]) arr.clone();\n\n assertTrue(\"Array \" + i + \" should have been sorted \" + Arrays.toString(arr), \n SortedOrNot.isSorted(arr));\n assertArrayEquals(orig, arr);\n }\n}\n</code></pre>\n\n<p>Algorithms that deal with numbers should always be tested with the limits of the allowed value space. The algorithm must work with max and min values and fail with max+1 etc. When the numeric algorithm uses the natural limits of the primitive types, the tests must take into account possible overflows and the ways they may affect the calculations (e.g. adding one to Integer.MAX_VALUE making the result negative).</p>\n\n<p>If the target code processes arrays and is not documented to modify the input, the tests should ensure that the array stays intact.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T04:23:05.743",
"Id": "230935",
"ParentId": "230751",
"Score": "2"
}
},
{
"body": "<p>There isn't anything inherently wrong with repeating assertions in the same test, and for few test case values like yours this is perfectly fine. But if you need to test a large set of values, consider using a parameterized test like the following:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@RunWith(org.junit.runners.Parameterized.class)\npublic class SortedOrNotTest {\n\n @Parameterized.Parameter(0)\n public static boolean expectedResult;\n\n @Parameterized.Parameter(1)\n public static int[] array;\n\n @Parameterized.Parameters\n public static Object[][] test() {\n return new Object[][]{\n {true, new int[] {32, 32, 32, 32, 32, 32, 32, 32, 34} },\n {false, new int[] {32, 32, 34, 33} },\n {true, new int[] {32} },\n {true, new int[] {} },\n {false, new int[] {32, 32, 31, 30, 32} }\n };\n }\n\n\n @Test\n public void paramTest() {\n assertEquals(expectedResult, SortedOrNot.isSorted(array));\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T09:07:44.383",
"Id": "230942",
"ParentId": "230751",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230942",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T13:15:55.433",
"Id": "230751",
"Score": "2",
"Tags": [
"java",
"unit-testing"
],
"Title": "Unit tests code for a Java class that that checks whether an array is sorted"
}
|
230751
|
<p>I read a book about OS development and faced with a simple exercise: <em>write a function that prints a hexadecimal value stored at a register</em>. The program runs as a boot sector.</p>
<p>I would really appreciate suggestions and help for size optimization and functionality.</p>
<pre class="lang-lisp prettyprint-override"><code>[BITS 16]
[ORG 0x7C00]
EntryPoint:
; Setup the stack:
xor AX, AX ; First of all set SS to 0x0000.
mov SS, AX ;
mov BP, 0x7BFF ; BIOS memory map description found on the Internet states that
; address space from 0x500 to 0x7BFF is guaranteed free for use.
mov SP, BP ; We will use it for our stack.
; Test of the PrintHex procedure:
mov BX, 0x2019 ; Load some number into BX.
call PrintHex ; Print it.
; Hang:
jmp $
;==============================================================================
; PROCEDURE PrintHex
;
; Description:
; Prints content of BX in form "0x0000" in teletype mode.
; Inputs:
; BX: number to print.
; Outputs:
; No.
;==============================================================================
PrintHex:
pusha
mov CX, BX ; Save the original number to CX.
mov SI, .alphabet ; Use SI as base for .alphabet array.
shr BX, 12 ; Get the first 4 bits of the original number (0x[1]234).
mov AL, [BX + SI] ; Use it as index in the array of hexadecimal digits. Thus get the appropriate character.
mov [.result + 2], AL ; Copy the character to the output array.
; In other words, these instuctions mean result[2] = alphabet[BX].
mov BX, CX ; Restore the original number.
shr BX, 8 ; Get the second 4 bits of the original number (0x1[2]34).
and BX, 0x0F ; We have to apply mask 0x0F to the value in order to get exactly 4 bits.
mov AL, [BX + SI] ; AL = alphabet[BX].
mov [.result + 3], AL ; result[3] = AL.
mov BX, CX ; Restore the original number.
shr BX, 4 ; Get the third 4 bits of the original number (0x12[3]4).
and BX, 0x0F ;
mov AL, [BX + SI] ; AL = alphabet[BX].
mov [.result + 4], AL ; result[4] = AL.
mov BX, CX ; Restore the original number.
and BX, 0x0F ; Get the last 4 bits of the original number (0x123[4]).
mov AL, [BX + SI] ; AL = alphabet[BX].
mov [.result + 5], AL ; result[5] = AL.
mov BX, .result ; Print the result.
call WriteString ;
popa
ret
.alphabet:
db '0123456789ABCDEF', 0x0
.result:
db '0x0000', 0x0
;==============================================================================
; PROCEDURE WriteString
;
; Description:
; Writes a null-terminated string to the screen using BIOS teletype mode text
; writing.
; Inputs:
; BX: address of the string.
; Outputs:
; No.
;==============================================================================
WriteString:
pusha
mov SI, 0 ; Use SI as index in the string.
.loop:
mov AL, [BX + SI] ; Move the current character at the string into AL.
cmp AL, 0x0 ; If the current character is null-terminator, then
je .break ; break the loop.
call WriteCharInTeletypeMode ; Otherwise print it.
inc SI ; Increment index and
jmp .loop ; jump to the beginning.
.break:
popa
ret
;==============================================================================
; PROCEDURE WriteCharInTeletypeMode
;
; Description:
; Writes a character in teletype mode using BIOS interrupts.
; Inputs:
; AL: character.
; Outputs:
; No.
;==============================================================================
WriteCharInTeletypeMode:
pusha
mov AH, 0xE ; Select BIOS function teletype mode text writing.
int 0x10
popa
ret
;==============================================================================
; Padding and the Bootloader Signature
;==============================================================================
times 510 - ($ - $$) db 0x0 ; Fill the rest of the file by zeroes.
db 0x55 ; The bootloader signature. Required by some BIOSes.
db 0xAA ;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T14:25:11.930",
"Id": "449779",
"Score": "0",
"body": "Optimization for size? Or speed? A bit of both?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T14:36:08.743",
"Id": "449783",
"Score": "1",
"body": "@harold, for size, I guess."
}
] |
[
{
"body": "<p>When setting up the SS:SP registers, there is a slight chance that an interrupt might happen between setting SS and SP. The interrupt handler would then write to an unintended memory address. To prevent this, enclose the code between cli and sti.</p>\n\n<p>I'd rather set SP to 07FEh, to align memory reads to 2-byte boundaries.</p>\n\n<p>Instead of <code>jmp $</code> you should not waste energy by replacing it with:</p>\n\n<pre><code>forever:\n hlt\n jmp short forever\n</code></pre>\n\n<p>Since you are programming in assembly and not in C, you don't have to use the inefficient C-style strings. You can also use the <code>(start, length)</code> format, which does not need a trailing null character.</p>\n\n<p>I'd allocate the output buffer on the stack instead of using a static buffer, so that you can put something else in that section.</p>\n\n<p>I dimly remember that I initialized CS, DS and ES as well in the boot sector. I don't remember if they have guaranteed values at startup, or maybe that was the common sequence in <code>.com</code> files.</p>\n\n<p>\"Found on the internet\" is an inappropriate citation. Just mention the URL where you found that information.</p>\n\n<p>Instead of the complicated <code>times</code> expression, can you just say <code>[org 7CFEh]</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T04:45:47.317",
"Id": "230801",
"ParentId": "230755",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code>mov SS, AX ;\nmov BP, 0x7BFF\nmov SP, BP \n</code></pre>\n</blockquote>\n\n<p>This is a dangerous construct! To maintain a consistent <code>SS:SP</code> pair of registers you should always set these back to back (No instruction(s) in between).</p>\n\n<p>The code uses <code>pusha</code>, <code>popa</code>, <code>shr bx, 12</code>, ...<br>\nSo your code is clearly targetting x86 (and not the infamous 8086). Then you don't need to use <code>CLI</code> nor <code>STI</code> around this code.</p>\n\n<p>To optimize the stack access, setting the stackpointer offset <code>SP</code> to an even address is best and since you want to place the stack beneath the bootloader, I suggest you write:</p>\n\n<pre><code>xor ax, ax\nmov ss, ax\nmov sp, 0x7C00\n</code></pre>\n\n<p>Your program depends on a correct <code>DS</code> segment register. You can't trust this to be so when BIOS starts your program. For good measure this applies to <code>ES</code> also, so make it happen:</p>\n\n<pre><code>xor ax, ax\nmov ds, ax\nmov es, ax\nmov ss, ax\nmov sp, 0x7C00\n</code></pre>\n\n<hr>\n\n<p>The BIOS Teletype function uses <code>BH</code> to specify the display page and you will want this to be zero. Therefore it's not a good idea to use <code>BX</code> for addressing the text.</p>\n\n<p>In your program it works because the label <em>.result</em> has a very small address, meaning <code>BH=0</code>.</p>\n\n<p>These are the necessary changes to <em>WriteString</em> and <em>WriteCharInTeletypeMode</em>:</p>\n\n<pre><code>WriteString:\n pusha\n .loop:\n mov al, [si]\n cmp al, 0\n je .break\n call WriteCharInTeletypeMode\n inc si\n jmp .loop\n .break:\n popa\n ret\n\nWriteCharInTeletypeMode:\n pusha\n mov bh, 0 ;Displaypage\n mov ah, 0x0E\n int 0x10\n popa\n ret\n</code></pre>\n\n<hr>\n\n<h3>You want to optimize for code size</h3>\n\n<p>(1) Then at least use a loop to convert to hexadecimal instead of using an unrolled approach.</p>\n\n<pre><code> mov di, .result+6\nMore:\n mov si, bx\n and si, 15\n mov al, [.alphabet + si] \n dec di\n mov [di], al\n shr bx, 4\n cmp di, .result+2\n ja More\n mov si, .result ;Using SI here!!\n call WriteString\n</code></pre>\n\n<p>(2) Do you really need a separate <em>WriteCharInTeletypeMode</em>?<br>\nYou save a lot of bytes if you inline this code:</p>\n\n<pre><code>WriteString:\n pusha\n .loop:\n mov al, [si]\n cmp al, 0\n je .break\n\n mov bh, 0 ;Displaypage\n mov ah, 0x0E\n int 0x10\n\n inc si\n jmp .loop\n .break:\n popa\n ret\n</code></pre>\n\n<p>(3) You don't need a terminating zero with that <em>.alphabet</em> string.</p>\n\n<pre><code>.alphabet:\n db '0123456789ABCDEF'\n</code></pre>\n\n<p>(4) A conversion that doesn't use this 16 characters string is probably shorter, code-wise. Should not be too difficult to find an example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:26:50.477",
"Id": "450141",
"Score": "0",
"body": "So great answer! More than I expected. Thanks you :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:28:13.540",
"Id": "450142",
"Score": "0",
"body": "Can you please explain this moment: \"*So your code is clearly targetting x86 (and not the infamous 8086). Then you don't need to use CLI nor STI around this code*\". Why I don't need use `CLI` and `STI` around this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:32:03.107",
"Id": "450143",
"Score": "0",
"body": "@eanmos The instructions that I mention (and that you used) didn't exist on the original 8086. That's why I can say that you wrote a program for an architecture later than 8086. We refer to this as x86. All x86 processors protect the instruction following a write to `SS` from interruption __but__ some old 8086's had an error in them requiring us to use `cli` / `sti` as a protection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:39:52.187",
"Id": "450145",
"Score": "0",
"body": "We do not care about another 8086's segment register (`DS`, `ES`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:41:47.903",
"Id": "450147",
"Score": "0",
"body": "@eanmos I don't get this question. Segment registers are __always__ important in real address programming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:43:45.857",
"Id": "450149",
"Score": "0",
"body": "I meant, are we need `cli`/`sti` as a protection when setting up `DS` and `ES`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:45:52.933",
"Id": "450150",
"Score": "0",
"body": "@eanmos No. The cpu's interruptions don't harm these like `SS:SP`. Neither `DS` nor `ES` form an unbreakable pair with some other register."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:47:01.280",
"Id": "450151",
"Score": "0",
"body": "I understood. Thanks you a lot again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T20:52:52.673",
"Id": "450199",
"Score": "0",
"body": "Just for reference: [AMD manual](https://www.amd.com/system/files/TechDocs/24594.pdf), search for \"When the MOV instruction is used to load the SS register\"."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:23:37.980",
"Id": "230958",
"ParentId": "230755",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "230801",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T13:52:56.417",
"Id": "230755",
"Score": "5",
"Tags": [
"io",
"assembly",
"x86"
],
"Title": "Display hexadecimal value stored at a register"
}
|
230755
|
<p>Factorial base - representation of numbers not as sums of base_number^digit_number, but as sums of digit_number! (factorial).<br>
So 7 (decimal) is represented as 101_! in factorial base, because 7 = 6+1 = 3! x <strong>1</strong> + 2! x <strong>0</strong> + 1! x <strong>1</strong>.</p>
<p>Left-truncatable primes are primes that stay primes if you get rid of any left (most significant) digits - 647, 47 and 7 are primes, so 647 and 47 are left-truncatable primes (in base 10).</p>
<p>In factorial base, 1-digit numbers are only 0 and 1 (which are neither prime nor not-prime), so there we count those that end in "10" (2), "11" (3) or "21" (5)</p>
<hr>
<p>I'm interested in amount of left-truncatable primes in factorial base per each length. </p>
<p>By hand you can find that there are 3 such numbers of length 3, maybe get that length 4 contains 8 of such.</p>
<p>32-bit representation can hold up to high 12-length numbers.<br>
64-bit can go up to middle 20-length.</p>
<p>To get higher I needed optimized number representation - I chose GMP library.</p>
<p>At length 20 there are ~60kk such numbers, so to compute them all I decided to try multithreading (I never tried it before).</p>
<hr>
<p>Here's the code:</p>
<pre><code>#define STORAGE_SIZE 160'000'000
#define THREAD_NUM 1
#define PRIME_REP 1
#define ARRAY_LENGTH 2
#include <iostream>
#include <gmp.h>
#include <thread>
#include <atomic>
#include <array>
#include <vector>
#include <chrono>
using namespace std;
mpz_t g_fact[FACT_NUM_LENGTH+1]; //from 0 factorial to FACT_NUM_LENGTH factorial
array<atomic<int>, 2> Atom{2, 0}; //we start from 3 numbers in input storage and 0 in output storage
char debug_buff[1000];
void Setting_mpz(mpz_t& HugeNum, const array<unsigned long, ARRAY_LENGTH>& Array)
{
const auto Internals = mpz_limbs_write(HugeNum, ARRAY_LENGTH); //get address of mpz storage
for (int i=0; i < ARRAY_LENGTH; i++)
{
Internals[i] = Array[i]; //write from array into mpz
}
mpz_limbs_finish(HugeNum, ARRAY_LENGTH); //Hugenum is set to decoded number
}
void Reading_mpz(const mpz_t& HugeNum, array<unsigned long, ARRAY_LENGTH>& Output_Array)
{
const auto Output_Internals = mpz_limbs_read(HugeNum); //get address of mpz storage
for(int i=0; i < ARRAY_LENGTH; i++)
{
Output_Array[i] = Output_Internals[i]; //read from mpz into array
}
}
void Thread_Foo (vector<array<unsigned long, ARRAY_LENGTH>>* Main_Storage, int Digit, bool flip)
{
mpz_t HugeNum;
mpz_init(HugeNum); //initialization
int I_input, I_output;
do
{
I_input = Atom[flip].fetch_sub(1);
if (I_input < 0) break; //we get number of safe array to read from
Setting_mpz(HugeNum, Main_Storage[flip][I_input]); //Hugenum is set to decoded number
for (int i=1; i <= Digit; i++) //changing left-most digit from 1 to Digit
{
mpz_add(HugeNum, HugeNum, g_fact[Digit]);
if (!mpz_probab_prime_p(HugeNum, PRIME_REP)) continue; //skipping composite numbers
I_output = Atom[!flip].fetch_add(1); //we get number of safe array to store prime in
auto& Output_Array = Main_Storage[!flip][I_output];
Reading_mpz(HugeNum, Output_Array); //Output_Array is set to number from mpz
}
}while(I_input);
mpz_clear(HugeNum); //destruction of mpz
}
int main()
{
mpz_init_set_ui(g_fact[0], 1); //zero factorial set
for (int i=1; i <= FACT_NUM_LENGTH; i++)
{
mpz_init(g_fact[i]);
mpz_mul_ui(g_fact[i], g_fact[i-1], i); // i factorial set
} //Factorials are set
vector<array<unsigned long, ARRAY_LENGTH>> Main_Storage[2]; //creating storage
Main_Storage[0].resize(STORAGE_SIZE, array<unsigned long, ARRAY_LENGTH>{0,0});
Main_Storage[1].resize(STORAGE_SIZE, array<unsigned long, ARRAY_LENGTH>{0,0}); //filling storage with zeros
Main_Storage[0][0] = array<unsigned long, ARRAY_LENGTH> {2,0};
Main_Storage[0][1] = array<unsigned long, ARRAY_LENGTH> {3,0};
Main_Storage[0][2] = array<unsigned long, ARRAY_LENGTH> {5,0}; //setting starting numbers
int Digit;
bool flip;
for (Digit = 3, flip = 0; Digit <= FACT_NUM_LENGTH; Digit++, flip = !flip) //starting from 3rd Digit from the right, up to FACT_NUM_lENGTH-th digit
{
auto Start = chrono::steady_clock::now();
thread Thread_Stack[THREAD_NUM];
for (int i=0; i < THREAD_NUM; i++)
{
Thread_Stack[i] = thread(Thread_Foo, Main_Storage, Digit, flip);
}
for (int i=0; i < THREAD_NUM; i++)
{
Thread_Stack[i].join();
}
Atom[flip].store(0); //reseting counter of soon-to-be-output storage (fetch_sub can push it below 0)
Atom[!flip].fetch_sub(1); //last output pushed value of atomic above itself
auto End = chrono::steady_clock::now();
cout << Digit << ' ' << Atom[!flip].load()+1 << ' ' << chrono::duration_cast<chrono::microseconds>(End - Start).count();
getchar();
}
return 0;
}
</code></pre>
<p>I use following algorithm: </p>
<ul>
<li>I store all such numbers of length N-1, </li>
<li>then for each such number I keep adding N! whole N times to check all candidates of length N. </li>
<li><code>mpz_probab_prime_p</code> checks number for being prime.</li>
</ul>
<p>To parallelize computation, I centralize storage and access it via atomic variables - each request increments (or decrements) atomic variable, thus every time you get storage place only for you alone.</p>
<hr>
<p>I need advice on how to move forward.<br>
On one hand, I'm running out of memory for centralized storage (21-length is ~153kk, so about 6-8 GB, that's all of my RAM).<br>
On the other, length-21 took me ~20 minutes, so I wonder if I can feather disconnect threads from each other (I don't understand how much atomics and non-sequential access slow me down).</p>
<p>And I want to try more complex ways of writing parallel computations, but I don't know what ways are there.</p>
<p>And of course, it would be nice to have general code review for readability.</p>
<p>Thanks in advance and comment if I can help clarify anything.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T14:06:10.853",
"Id": "230756",
"Score": "1",
"Tags": [
"c++",
"multithreading",
"primes",
"gmp"
],
"Title": "Find parallel-base left-truncatable primes"
}
|
230756
|
<p>I have if statement with many checks. There must be a better way to implement this.
Does someone have an idea on how to improve this method?
I have many similar methods in production. I would like to do the refactoring.</p>
<pre><code> private void CheckWorkingHoursValidity(WorkingDayRequestDto workingDayDto)
{
if (!workingDayDto.MondayEnd.HasValue && workingDayDto.MondayStart.HasValue ||
workingDayDto.MondayEnd.HasValue && !workingDayDto.MondayStart.HasValue ||
!workingDayDto.TuesdayEnd.HasValue && workingDayDto.TuesdayStart.HasValue ||
workingDayDto.TuesdayEnd.HasValue && !workingDayDto.TuesdayStart.HasValue ||
!workingDayDto.WednesdayEnd.HasValue && workingDayDto.WednesdayStart.HasValue ||
workingDayDto.WednesdayEnd.HasValue && !workingDayDto.WednesdayStart.HasValue ||
!workingDayDto.ThursdayEnd.HasValue && workingDayDto.ThursdayStart.HasValue ||
workingDayDto.ThursdayEnd.HasValue && !workingDayDto.ThursdayStart.HasValue ||
!workingDayDto.FridayEnd.HasValue && workingDayDto.FridayStart.HasValue ||
workingDayDto.FridayEnd.HasValue && !workingDayDto.FridayStart.HasValue ||
!workingDayDto.SaturdayEnd.HasValue && workingDayDto.SaturdayStart.HasValue ||
workingDayDto.SaturdayEnd.HasValue && !workingDayDto.SaturdayStart.HasValue ||
!workingDayDto.SundayEnd.HasValue && workingDayDto.SundayStart.HasValue ||
workingDayDto.SundayEnd.HasValue && !workingDayDto.SundayStart.HasValue)
{
throw new ValidationException("Both start and end time must be set or empty");
}
if (workingDayDto.MondayEnd.HasValue && workingDayDto.MondayStart.HasValue &&
TimeSpan.Compare(workingDayDto.MondayEnd.Value, workingDayDto.MondayStart.Value) <= 0 ||
workingDayDto.TuesdayEnd.HasValue && workingDayDto.TuesdayStart.HasValue &&
TimeSpan.Compare(workingDayDto.TuesdayEnd.Value, workingDayDto.TuesdayStart.Value) <= 0 ||
workingDayDto.WednesdayEnd.HasValue && workingDayDto.WednesdayStart.HasValue &&
TimeSpan.Compare(workingDayDto.WednesdayEnd.Value, workingDayDto.WednesdayStart.Value) <= 0 ||
workingDayDto.ThursdayEnd.HasValue && workingDayDto.ThursdayStart.HasValue &&
TimeSpan.Compare(workingDayDto.ThursdayEnd.Value, workingDayDto.ThursdayStart.Value) <= 0 ||
workingDayDto.FridayEnd.HasValue && workingDayDto.FridayStart.HasValue &&
TimeSpan.Compare(workingDayDto.FridayEnd.Value, workingDayDto.FridayStart.Value) <= 0 ||
workingDayDto.SaturdayEnd.HasValue && workingDayDto.SaturdayStart.HasValue &&
TimeSpan.Compare(workingDayDto.SaturdayEnd.Value, workingDayDto.SaturdayStart.Value) <= 0 ||
workingDayDto.SundayEnd.HasValue && workingDayDto.SundayStart.HasValue &&
TimeSpan.Compare(workingDayDto.SundayEnd.Value, workingDayDto.SundayStart.Value) <= 0)
{
throw new ValidationException("End time cannot be before or same as start time");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T07:36:53.863",
"Id": "449838",
"Score": "0",
"body": "This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)."
}
] |
[
{
"body": "<p>How about you made a list for EndForDays and StartForDays and do loop?</p>\n\n<p>For example, I made a code snippet by Java.</p>\n\n<pre><code>List<Boolean> EndForDays = Arrays.asList(true, false, false);\nList<Boolean> StartForDays = Arrays.asList(true, true, true);\n\nfor(int i = 0; i < EndForDays.size(); i++) {\n if(!EndForDays.get(i) && StartForDays.get(i)) {\n // throw\n }\n\n if(EndForDays.get(i) && !StartForDays.get(i)) {\n // throw\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T16:25:48.127",
"Id": "230765",
"ParentId": "230757",
"Score": "0"
}
},
{
"body": "<blockquote>\n <p><code>WorkingDayRequestDto workingDayDto</code></p>\n</blockquote>\n\n<p>The name of this object is IMO misleading because it seems to represent a whole week. I would call it <code>WorkWeek</code>.</p>\n\n<hr>\n\n<p>If it's possible to change the data model, I would invent a <code>WorkDay</code> object with a <code>Start</code> and <code>End</code> time:</p>\n\n<pre><code>public class WorkDay\n{\n public WorkDay(DateTime? start, DateTime? end)\n {\n Start = start;\n End = end;\n }\n\n public DayOfWeek? DayOfWeek => Start != null ? (DayOfWeek?)Start.Value.DayOfWeek : null;\n public DateTime? Start { get; }\n public DateTime? End { get; }\n\n public bool IsValid\n {\n get\n {\n return Start != null && End != null && Start <= End && Start.Value.DayOfWeek == End.Value.DayOfWeek || Start == null && End == null;\n }\n }\n\n // And/Or\n\n public void CheckIsValid()\n {\n if (Start == null && End != null || Start != null && End == null)\n throw new WorkDayNullCheckException(this);\n if (Start != null && End != null && (Start > End || Start.Value.Date != End.Value.Date)\n throw new WorkDayInvalidStateException(this);\n }\n\n}\n</code></pre>\n\n<p>and then <code>WorkWeek</code> could be defined as something like:</p>\n\n<pre><code>public class WorkWeek\n{\n public WorkDay Monday { get; set; }\n public WorkDay Tuesday { get; set; }\n public WorkDay Wednesday { get; set; }\n public WorkDay Thursday { get; set; }\n public WorkDay Friday { get; set; }\n public WorkDay Saturday { get; set; }\n public WorkDay Sunday { get; set; }\n\n public WorkDay[] Days => new WorkDay[] { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };\n\n public bool IsValid => Days.All(d => d.IsValid);\n\n // And/Or\n\n public void CheckValidity()\n {\n foreach (var day in Days.Where(d => d != null))\n {\n day.CheckIsValid();\n }\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T16:31:39.490",
"Id": "230768",
"ParentId": "230757",
"Score": "4"
}
},
{
"body": "<p>I'm not that great at C#, however in other languages when I come across something like this, I usually write a private or helper function to iterate through the object so my code doesn't look like large blocks of checks.</p>\n\n<p>Something like </p>\n\n<pre><code>private void checkDays(WorkingDayRequestDto dayObject){\n string [] days = new string[] { \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\",\"Saturday\", \"Sunday\" };\n foreach(string x in days){\n DayType start = typeof(DayType).GetProperty( days[x] + \"Start\");\n DayType end = typeof(DayType).GetProperty( days[x] + \"End\");\n if(!end.HasValue && start.HasValue || end.HasValue && !start.HasValue){\n throw new ValidationException(\"Both start and end time must be set or empty\");\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T22:08:20.557",
"Id": "449819",
"Score": "1",
"body": "I don't speak C#, but you could probably simplify the code somewhat by using the exclusive or operator ^ . `if(end.HasValue ^ start.HasValue ){\n throw new ValidationException(\"Both start and end time must be set or empty\");`\n }"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T16:37:54.277",
"Id": "230771",
"ParentId": "230757",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "230768",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T14:38:32.603",
"Id": "230757",
"Score": "-1",
"Tags": [
"c#"
],
"Title": "IF statement with multiple AND/OR conditions"
}
|
230757
|
<p>I frequently use MathJax, and often I need to write matrices. Since writing matrices using MathJax is very tiresome task, I decided to automate it.</p>
<p>Code:</p>
<pre><code>import numpy as np
import pyperclip
class Conversion():
def __init__(self, matrix, n = None, m = None):
if matrix == None:
self.matrix = np.random.randint(-10,10, size = [n,m])
else:
'''If variable "matrix", for example, contains [1,2,3,4], instead of [[1,2,3,4]], functions below
will throw error, hence we need to make sure that the data type is correct.'''
if type(matrix[0]) in (str,int,float):
self.matrix = np.array([matrix,])
else:
self.matrix = np.array(matrix)
self.rows = len(self.matrix)
self.cols = len(self.matrix[0])
def single(self, choosen_brackets = ')'):
available_brackets = {' ' : 'matrix',
')' : 'pmatrix',
']' : 'bmatrix',
'}' : 'Bmatrix',
'|' : 'vmatrix',
'||': 'Vmatrix' }
choosen_brackets = available_brackets[choosen_brackets]
body = '<span class="math-container">$$\\begin {} \n'.format('{' + choosen_brackets + '}')
for row in self.matrix:
row = [str(x) for x in row]
body += ' & '.join(row) + '\\\\' + '\n'
body +='\end {} $$</span>'.format('{' + choosen_brackets + '}')
print(body)
pyperclip.copy(body)
def augmented(self, choosen_brackets = '[]'):
'''We are assuming that the last column of the given matrix is a vector.'''
pos_of_the_verticar_bar = '{' + 'c'*(self.cols-1) + '|' + 'c' + '}'
body = '<span class="math-container">$$\\left [ \\begin {array} %s \n' % (pos_of_the_verticar_bar)
for row in self.matrix:
row = [str(x) for x in row]
body += ' & '.join(row) + '\\\\' + '\n'
body +='\end {array} \\right ]$$</span>'
print(body)
pyperclip.copy(body)
</code></pre>
<p>Notes:</p>
<ol>
<li><p>Since function <code>augmented</code> is quite similar to <code>single</code>, I could've merged them into one. However, I think that keeping them separate makes the code a little bit more readable.</p></li>
<li><p>On MSE, mathjax equations are enclosed with <code>$$</code> instead of <code>\$</code></p></li>
<li><p>"<code>single</code>" is a bad name for a function, I admit. I haven't found any better options. Feel free to offer suggestions.</p></li>
</ol>
<p>What can be improved?</p>
<p>Written for Python 3.6.5.</p>
|
[] |
[
{
"body": "<p>This looks like a handy tool to have around, maybe we can make it even better.</p>\n\n<h1>Style</h1>\n\n<p>As per the official Python Style Guide (often known by his nickname PEP8), keyword-arguments of functions should have no whitespace around the <code>=</code>.</p>\n\n<h1>Matrix size</h1>\n\n<p>numpy arrays have a property called <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html\" rel=\"nofollow noreferrer\"><code>.shape</code></a> which describes their number of rows and number of cols (in case of a 2D array at least). So</p>\n\n<pre><code>self.rows = len(self.matrix)\nself.cols = len(self.matrix[0])\n</code></pre>\n\n<p>could become</p>\n\n<pre><code>self.rows, self.cols = self.matrix.shape\n</code></pre>\n\n<p>Since your code only works for 2D matrices, it's maybe also a good idea to check for that. The <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ndim.html\" rel=\"nofollow noreferrer\"><code>.ndim</code></a> attribute can be of help here.</p>\n\n<h1>Type checking</h1>\n\n<p><code>type(matrix[0]) in (str,int,float)</code> should instead be <code>isinstance(matrix[0], (str, int, float))</code>.</p>\n\n<h1>Checking <code>None</code></h1>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">official recommendation</a> is to always use <code>if sth is None:</code> when checking for <code>None</code>.</p>\n\n<h1>String joining</h1>\n\n<blockquote>\n<pre><code>row = [str(x) for x in row]\nbody += ' & '.join(row) + '\\\\\\\\' + '\\n'\n</code></pre>\n</blockquote>\n\n<p>could be done in a single line:</p>\n\n<pre><code>body += ' & '.join(str(x) for x in row) + '\\\\\\\\' + '\\n'\n</code></pre>\n\n<p>This means you also don't have to reassign <code>row</code> to be something different than it was before.</p>\n\n<h1>String formatting</h1>\n\n<p>Since you said you're using Python 3.6, maybe have a look at <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a> for even more concise string formatting syntax. No matter if you choose to do this, maybe at least get rid of the old-style <code>%</code> formatting in <code>augmented(...)</code> by escaping <code>{</code> and <code>}</code> using a leading <code>\\</code>.</p>\n\n<h1>Function output</h1>\n\n<p>I find it preferable if you'd let the user decide what he wants to do with what your function returns. So instead of printing and copying the formatted matrix code, maybe just return <code>body</code> and let the caller decide how to proceed from here. You could even define a \"convenience\" function (<code>to_clipboard</code>) that basically only does <code>pyperclip.copy(...)</code>, although this is likely not necessary. Another idea would be to make at least the <code>copy</code> part opt-in via a \"flag\" bool parameter.</p>\n\n<h1>Class</h1>\n\n<p>Maybe a class is not the right tool here. A possible alternative would be to move what's done in <code>__init__</code> into a \"private\" (read name starts with <code>_</code>) helper function and get rid of the class.</p>\n\n<hr>\n\n<h1>Missing backslash</h1>\n\n<p>There seems to be a little bug in both of your functions (see how bad code duplication is ;-)): <code>body +='\\end ...</code> is likely missing an additional <code>\\</code>.</p>\n\n<h1>Unused argument</h1>\n\n<p>If I'm not mistaken, the <code>choosen_brackets</code> argument of <code>augmented</code> is not used in the function.</p>\n\n<h1>Typo</h1>\n\n<p><code>choosen_brackets</code> should likely be <code>chosen_brackets</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T02:19:34.510",
"Id": "449825",
"Score": "0",
"body": "Thank you for your review! May I ask why it is recommended to use `is None` instead of `== None`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T07:47:05.310",
"Id": "449842",
"Score": "0",
"body": "Strictly speaking, `is` checks if both variables point to the exact same object in memory and not just that they compare equal. Since `None` is a singleton, this is likely the more natural operation to use. But to be honest, there are probably not a lot of (other) hard facts why you should use `is None` over `== None`. Both variants will give you the desired result here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T16:34:30.680",
"Id": "230769",
"ParentId": "230758",
"Score": "12"
}
},
{
"body": "<p>Python's string formatting has come a long way from the <code>\"%s\"</code> formatting days. Nowadays classes can even determine on their own how to handle format specifiers. Therefore I would write a matrix class that can be pretty printed with different format options determining the matrix style.</p>\n\n<pre><code>class MathJaxMatrix:\n brackets = {'': 'matrix', \n 'p': 'pmatrix', \n 'b': 'bmatrix', \n 'B': 'Bmatrix', \n 'v': 'vmatrix',\n 'V': 'Vmatrix'}\n e_msg = \"unsupported format string passed to MathJaxMatrix.__format__\"\n\n def __init__(self, m):\n if m.ndim == 1:\n m = m.reshape(len(m), 1)\n self.m = m\n self.rows, self.cols = m.shape\n\n def __str__(self):\n return \"\\\\\\\\ \\n\".join(\" & \".join(str(x) for x in row) for row in self.m)\n\n def __format__(self, format_spec=None):\n if format_spec is None:\n return str(self)\n if format_spec == \"a\":\n format_spec = '{' + 'c'*(self.cols-1) + '|c}'\n start = rf'<span class=\"math-container\">$$\\left[ \\begin{{array}}{format_spec}'\n end = r'\\end{array} \\right]$$</span>'\n else:\n try:\n brackets = self.brackets[format_spec]\n except KeyError as e:\n raise TypeError(self.e_msg) from e\n start = f'<span class=\"math-container\">$$ \\\\begin{{{brackets}}}'\n end = f'\\end{{{brackets}}} $$</span>'\n return \"\\n\".join([start, str(self), end])\n</code></pre>\n\n<p>Which you can use like this:</p>\n\n<pre><code>In [40]: x = np.random.rand(4, 5)\n\nIn [41]: m = MathJaxMatrix(x)\n\nIn [42]: print(m)\n0.35170079706 & 0.903087473471 & 0.748996998207 & 0.741200595894 & 0.771233795397\\\\\n0.251204439922 & 0.40876741255 & 0.101668325527 & 0.738733484611 & 0.3052742949\\\\\n0.448079803976 & 0.273533142438 & 0.368031240997 & 0.34312026244 & 0.587809084934\\\\\n0.0192109217812 & 0.334069285732 & 0.644616319752 & 0.648226279564 & 0.307678962448\n\nIn [43]: print(f\"{m}\")\n<span class=\"math-container\">$$\\begin{matrix}\n0.35170079706 & 0.903087473471 & 0.748996998207 & 0.741200595894 & 0.771233795397\\\\\n0.251204439922 & 0.40876741255 & 0.101668325527 & 0.738733484611 & 0.3052742949\\\\\n0.448079803976 & 0.273533142438 & 0.368031240997 & 0.34312026244 & 0.587809084934\\\\\n0.0192109217812 & 0.334069285732 & 0.644616319752 & 0.648226279564 & 0.307678962448\n\\end{matrix} $$</span>\n\nIn [44]: print(f\"{m:p}\")\n<span class=\"math-container\">$$\\begin{pmatrix}\n0.35170079706 & 0.903087473471 & 0.748996998207 & 0.741200595894 & 0.771233795397\\\\\n0.251204439922 & 0.40876741255 & 0.101668325527 & 0.738733484611 & 0.3052742949\\\\\n0.448079803976 & 0.273533142438 & 0.368031240997 & 0.34312026244 & 0.587809084934\\\\\n0.0192109217812 & 0.334069285732 & 0.644616319752 & 0.648226279564 & 0.307678962448\n\\end{pmatrix} $$</span>\n\nIn [45]: print(f\"{m:a}\")\n<span class=\"math-container\">$$ \\left[ \\begin{array}{cccc|c}\n0.35170079706 & 0.903087473471 & 0.748996998207 & 0.741200595894 & 0.771233795397\\\\\n0.251204439922 & 0.40876741255 & 0.101668325527 & 0.738733484611 & 0.3052742949\\\\\n0.448079803976 & 0.273533142438 & 0.368031240997 & 0.34312026244 & 0.587809084934\\\\\n0.0192109217812 & 0.334069285732 & 0.644616319752 & 0.648226279564 & 0.307678962448\n\\end{array} \\right] $$</span>\n\nIn [62]: print(f\"{m:e}\")\n---------------------------------------------------------------------------\nKeyError Traceback (most recent call last)\n...\nKeyError: 'e'\n\nThe above exception was the direct cause of the following exception:\n\nTypeError Traceback (most recent call last)\n...\nTypeError: unsupported format string passed to MathJaxMatrix.__format__\n</code></pre>\n\n<p>Note that this removes the repeated code for getting a string representation of the actual matrix, uses <code>np.ndarray.ndim</code> and <code>np.reshape</code> to ensure it is a proper 2D matrix. I used the first letter of the different <code>*matrix</code> options to distinguish them because <code>}</code> is not allowed in format specifications.</p>\n\n<p>The actual convenience function is then quite short:</p>\n\n<pre><code>def format_matrix(m, format_spec):\n m = MathJaxMatrix(m)\n s = f\"{m:{format_spec}}\"\n print(s)\n pyperclip.copy(s)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T18:07:59.200",
"Id": "230776",
"ParentId": "230758",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "230769",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T14:46:33.943",
"Id": "230758",
"Score": "12",
"Tags": [
"python",
"python-3.x",
"matrix",
"formatting",
"latex"
],
"Title": "Python algorithm that converts array-like data into MathJax"
}
|
230758
|
<blockquote>
<p>Create a class called <code>Stack</code> for storing integers. The data members are
an integer array for storing the integers and an integer for storing
the top of stack (<code>tos</code>). Include member functions for initializing <code>tos</code>
to 0, pushing an element to the stack and for popping an element from
the stack. The <code>push()</code> function should check for “stack overflow” and
<code>pop()</code> should check for “stack underflow”.</p>
</blockquote>
<pre><code>#include<iostream>
using namespace std;
#define SIZE 50
class Stack {
int stackArray[SIZE];
int tos;
public:
Stack() {
tos = 0;
}
void push(int);
int pop();
void set(int);
};
void Stack::push(int value) {
if (tos < SIZE) {
stackArray[tos++] = value;
}
else
cout << "Stack overflow" << endl;
}
void Stack::set(int a) {
tos = a;
}
int Stack::pop() {
if (tos == 0) {
cout << "Stack underflow " << endl;
}
else {
return stackArray[--tos];
}
}
int main() {
Stack s;
for (int i = 0; i < 50; i++) {
s.push(i);
}
for (int i = 0; i < 51; i++) {
cout << s.pop() << " " << i << endl;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Overall, this looks pretty good. If it were me, I'd use a more descriptive name for the top of the stack such as <code>topOfStack</code> or just <code>top</code>. <code>tos</code> doesn't really mean anything, so without a comment describing it, I would be confused seeing that in code. (And if you need to write a comment to explain a variable name, you've probably named it incorrectly.)</p>\n\n<p>I'm not sure your <code>set()</code> method works correctly. From the description it sounds like it shouldn't take any arguments and should set <code>tos</code> to 0. But it's possible I misunderstood. If you set the top to some passed-in value, then you have a bunch of junk on the stack between its previous value and the current value, which probably isn't what you want.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T03:15:44.950",
"Id": "230798",
"ParentId": "230772",
"Score": "2"
}
},
{
"body": "<h1>Prefer constants to macros</h1>\n<p>Preprocessor macros are tricky to use correctly - they have no namespace, no type and global scope. We can replace <code>SIZE</code> with a private constant member:</p>\n<pre><code>#include <cstdint>\n\nclass Stack\n{\n // private\n constexpr std::size_t array_length = 50;\n}\n</code></pre>\n<p>I renamed it, because we might later want to creat <code>size()</code> and <code>capacity()</code> members to act like the standard containers.</p>\n<h1>Avoid <code>using namespace std;</code></h1>\n<p>The <code>std</code> namespace isn't one that's designed to be imported wholesale like that. Avoid surprises, and be clear where identifiers come from, by importing just the names you need, in the smallest reasonable scope - or just qualify them fully (<code>std::</code> is intentionally very short!).</p>\n<h1>Don't mix errors with output</h1>\n<p>Error messages should be streamed to <code>std::cerr</code> rather than <code>std::cout</code>.</p>\n<h1>Improve the error reporting</h1>\n<p>Do you see the problem with <code>pop()</code>?</p>\n<blockquote>\n<pre><code>int Stack::pop() {\n if (tos == 0) {\n cout << "Stack underflow " << endl;\n }\n else {\n return stackArray[--tos];\n }\n}\n</code></pre>\n</blockquote>\n<p>In the underflow case, there's no <code>return</code> statement. Silly errors like that suggest that you compiled without a good set of warnings enabled.</p>\n<p>We don't have any way to indicate to the program (rather than the end user) that overflow or underflow has occurred; the C++ way to do so is to throw an exception in those cases. Then the program can decide whether and how to inform the user about the problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T12:33:41.813",
"Id": "230833",
"ParentId": "230772",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T17:22:16.257",
"Id": "230772",
"Score": "2",
"Tags": [
"c++",
"reinventing-the-wheel",
"stack"
],
"Title": "Creating a stack class in C++"
}
|
230772
|
<p>My goal is to code the <a href="https://en.wikipedia.org/wiki/Knapsack_problem" rel="nofollow noreferrer">knapsack problem</a> algorithm. The problem is that a knapsack has a given weight limit, <code>W</code>. I have a collection of items which have a given <code>weight</code> and <code>value</code> in a file that looks like:</p>
<pre><code># test.txt
1234 4456
4321 7654
... ...
</code></pre>
<p>Where value is the first column, and weight is the second. My algorithm seeks to maximize the value of items in the knapsack while staying at or beneath the weight limit <code>W</code>. This is what I've come up with so far:</p>
<pre><code>import numpy as np
#reading the data:
values = []
weights = []
test = []
with open("test.txt") as file:
for line in file:
value, weight = line.split(" ")
values.append(int(value))
weights.append(int(weight.replace("\n","")))
W = values.pop(0)
weights
size = weights.pop(0) +1
weights = [0] + weights
values = [0] + values
#Knapsack Algorithm:
hash_table = {}
for x in range(0,W +1):
hash_table[(0,x)] = 0
for i in range(1,size):
for x in range(0,W +1):
if weights[i] > x:
hash_table[(i,x)] = hash_table[i - 1,x]
else:
hash_table[(i,x)] = max(hash_table[i - 1,x],hash_table[i - 1,x - weights[i]] + values[i])
</code></pre>
<p>My idea is to use a "hash table" as a part of a dynamic programming technique in order to speed up my code. But I have tried to run it on <a href="https://github.com/beaunus/stanford-algs/blob/master/testCases/course3/assignment4Knapsack/input_random_44_2000000_2000.txt" rel="nofollow noreferrer">a big input file</a> and I am out of RAM (and it works very slowly).</p>
<p>Can you review my code and give me some hints how can I speed up my program?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T18:55:17.787",
"Id": "449806",
"Score": "1",
"body": "in addition to the link to Wikipedia could you provide a brief description of the algorithm. Links sometimes get broken."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T17:54:34.790",
"Id": "449944",
"Score": "0",
"body": "You run out of RAM? With Python? What version are you running? How big is your file and how big is your RAM? Something smells fishy here. While your code is inefficient, you shouldn't be running out of RAM with it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T23:08:40.333",
"Id": "449980",
"Score": "0",
"body": "@Mast the file is relatively large, but it's really the implementation of the algorithm. The best thing OP can do is look at some of the better space-efficiency algorithms. It's not impossible to run out of memory with python, and benchmarking OP's code, I see about 64GB memory usage before the interpreter crashes"
}
] |
[
{
"body": "<p>Part of the reason you're running out of memory is that you are allocating all of your items into memory twice. Once in the two lists <code>weights</code> and <code>values</code>, and once again in <code>hash_table</code>.</p>\n\n<p>Looking at your program, I don't see a need for you to keep your weights and values allocated as you do. You iterate through them one at a time in your outer for loop. What I'd do is make use of a generator and wrap the file reading in a function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def read_file():\n with open('knapsack.txt') as fh:\n\n # these value names are a bit more descriptive, and\n # you can use a next() call on this generator\n # to extract these values\n WEIGHT, SIZE = map(int, next(fh).strip().split())\n yield WEIGHT, SIZE\n\n for line in fh:\n yield map(int, line.strip().split())\n</code></pre>\n\n<p>This way you can do tuple unpacking in a for loop:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>iterator = read_file()\n# here's that next call I mentioned\nWEIGHT, SIZE = next(iterator)\n\n# iterate over the remaining values\nfor weight, value in iterator:\n # do something\n\n</code></pre>\n\n<p>This will keep copies of your values from proliferating throughout the execution of your program when you really don't need them.</p>\n\n<p>I'd also look into <code>enumerate</code>, since you need the index for part of your <code>hash_table</code> keys, but you also need the <code>weight</code> and <code>value</code> as well. This eliminate repeated lookups that slow down your code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i, (w, v) in enumerate(read_file(), start=1):\n for x in range(WEIGHT + 1):\n ...\n</code></pre>\n\n<p>To show the effect:</p>\n\n<pre><code># repeated index lookup\npython -m timeit -s 'x = list(range(1, 10000))' 'for i in range(len(x)): a = x[i] + 2'\n500 loops, best of 5: 792 usec per loop\n\n# no repeated index lookup\npython -m timeit -s 'x = list(range(1, 10000))' 'for i, j in enumerate(x): a = j + 2'\n500 loops, best of 5: 536 usec per loop\n</code></pre>\n\n<p>It doesn't appear that you really need the leading <code>0 0</code> row on weights and columns, either, since you start the index at <code>1</code>, skipping it. Avoiding the addition of lists here cuts down on overhead, and you can specify <code>enumerate</code> to start at a given value with the <code>start</code> kwarg as I've done above.</p>\n\n<p>The goal here should be to iterate over a collection as little as possible, so a refactored version might look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def read_file():\n with open('knapsack.txt') as fh:\n\n # these value names are a bit more descriptive, and\n # you can use a next() call on this generator\n # to extract these values\n WEIGHT, SIZE = map(int, next(fh).strip().split())\n yield WEIGHT, SIZE\n\n for line in fh:\n yield map(int, line.strip().split())\n\n\niterator = read_file()\nWEIGHT, SIZE = next(iterator)\nhash_table = {(0, i): 0 for i in range(WEIGHT + 1)}\n\nfor i, (w, v) in enumerate(iterator, start=1):\n for j in range(WEIGHT + 1):\n if w > j:\n hash_table[(i, j)] = hash_table[(i - 1, j)]\n else:\n hash_table[(i, j)] = max(\n hash_table[(i - 1, j)],\n hash_table[(i - 1, j - w)] + v\n )\n</code></pre>\n\n<p>This doesn't avoid all of the memory issues, however. You are dealing with a relatively large file and housing that in a dictionary will lead to heavy memory usage. As noted in the Wikipedia article, the solution you have implemented will have a worst-case space complexity of O(nW), which for this file is approximately O(n * 2000000)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T21:33:00.810",
"Id": "230789",
"ParentId": "230773",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "230789",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T17:35:16.917",
"Id": "230773",
"Score": "0",
"Tags": [
"python",
"algorithm",
"time-limit-exceeded",
"dynamic-programming",
"knapsack-problem"
],
"Title": "Solution to knapsack problem exceeds time and RAM limits"
}
|
230773
|
<p>As part of a larger authentication/authorization system, I've developed a small .NET Core 3.0 service for hashing passwords using <a href="https://en.wikipedia.org/wiki/PBKDF2" rel="nofollow noreferrer">PBKDF2</a> (with a salt) and validating passwords against a stored hash/salt, for use as part of a larger authentication/authorization system. </p>
<p>Code organization:</p>
<ul>
<li><code>IPasswordService</code> is the main interface used by the larger system.</li>
<li><code>PasswordService</code> is the implementation, the heart of this body of code.</li>
<li><code>KeyDerivationParameters</code> and <code>CryptoRng</code> are used when configuring and loading the service (ideally through a DI container).</li>
<li><code>ICryptoRng</code> is used as an interface to stub out when unit testing <code>PasswordService</code>.</li>
<li><code>ValueTypes</code> contains domain-specific types wrapping primitives, using the <a href="https://github.com/mcintyre321/ValueOf/" rel="nofollow noreferrer">ValueOf</a> library.</li>
<li><code>HashedPassword</code> is a simple wrapper encapsulating both a hash and a salt.</li>
<li><code>PasswordServiceTests</code> contains my unit tests.</li>
</ul>
<p>My main concerns (though all feedback is welcome):</p>
<ul>
<li>Security - making sure there's no obvious attack I'm missing. I should note that I only chose PBKDF2 because it has an implementation in .NET; argon and bcrypt are only available in C# through third-party libraries in various states of maintenance. I also intend on using a larger iteration count in practice than the 10,000 iterations specified in the tests; I wanted to keep the unit tests fast.</li>
<li>Tests - I only have four unit tests for the <code>PasswordService</code>, and I'm not confident that they provide enough of a safety net.</li>
<li>The use of ValueOf to create meaningful domain-specific types instead of using primitives everywhere. In Haskell, using newtypes for this sort of thing is common, but I'm curious what C# developers think about it.</li>
</ul>
<p>The code is broken up into eight files across two projects; it's available on GitHub <a href="https://github.com/DylanSp/AuthSystemPasswordService/tree/45060af4ad7f931caba0bc55280440f34dcec246" rel="nofollow noreferrer">here</a>, as well as below. The projects are .NET Core 3.0, using </p>
<pre><code><PropertyGroup>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</code></pre>
<p>in the .csproj files to enable C# 8's nullable reference types.</p>
<p><strong>IPasswordService.cs</strong></p>
<pre><code>namespace AuthSystemPasswordService.Interfaces
{
public interface IPasswordService
{
HashedPassword GeneratePasswordHashAndSalt(PlaintextPassword password);
bool CheckIfPasswordMatchesHash(PlaintextPassword password, HashedPassword hash);
}
}
</code></pre>
<p><strong>ICryptoRng.cs</strong></p>
<pre><code>namespace AuthSystemPasswordService.Interfaces
{
public interface ICryptoRng
{
byte[] GetRandomBytes(int numBytes);
}
}
</code></pre>
<p><strong>ValueTypes.cs</strong></p>
<pre><code>using ValueOf;
namespace AuthSystemPasswordService
{
public class PlaintextPassword : ValueOf<string, PlaintextPassword>
{
}
public class Base64Hash : ValueOf<string, Base64Hash>
{
}
public class Base64Salt : ValueOf<string, Base64Salt>
{
}
public class IterationCount : ValueOf<int, IterationCount>
{
}
public class SaltLength : ValueOf<int, SaltLength>
{
}
public class KeyLength : ValueOf<int, KeyLength>
{
}
}
</code></pre>
<p><strong>HashedPassword.cs</strong></p>
<pre><code>namespace AuthSystemPasswordService
{
public struct HashedPassword
{
public Base64Hash Base64PasswordHash { get; }
public Base64Salt Base64Salt { get; }
public HashedPassword(Base64Hash passwordHash, Base64Salt salt)
{
Base64PasswordHash = passwordHash;
Base64Salt = salt;
}
}
}
</code></pre>
<p><strong>KeyDerivationParameters.cs</strong></p>
<pre><code>using Microsoft.AspNetCore.Cryptography.KeyDerivation;
namespace AuthSystemPasswordService
{
public struct KeyDerivationParameters
{
public KeyDerivationPrf DerivationFunction { get; }
public IterationCount IterationCount { get; }
public SaltLength SaltLength { get; }
public KeyLength KeyLength { get; }
public KeyDerivationParameters(KeyDerivationPrf derivationFunction, IterationCount iterationCount,
SaltLength saltLength, KeyLength keyLength)
{
DerivationFunction = derivationFunction;
IterationCount = iterationCount;
SaltLength = saltLength;
KeyLength = keyLength;
}
}
}
</code></pre>
<p><strong>CryptoRng.cs</strong></p>
<pre><code>using AuthSystemPasswordService.Interfaces;
using System.Security.Cryptography;
namespace AuthSystemPasswordService.Services
{
public class CryptoRng : ICryptoRng
{
private RandomNumberGenerator Generator { get; }
public CryptoRng()
{
Generator = RandomNumberGenerator.Create();
}
public byte[] GetRandomBytes(int numBytes)
{
var bytes = new byte[numBytes];
Generator.GetBytes(bytes);
return bytes;
}
}
}
</code></pre>
<p><strong>PasswordService</strong></p>
<pre><code>using AuthSystemPasswordService.Interfaces;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using System;
using System.Linq;
namespace AuthSystemPasswordService.Services
{
public class PasswordService : IPasswordService
{
private KeyDerivationParameters Parameters { get; }
private ICryptoRng Rng { get; }
public PasswordService(KeyDerivationParameters parameters, ICryptoRng rng)
{
Parameters = parameters;
Rng = rng;
}
public HashedPassword GeneratePasswordHashAndSalt(PlaintextPassword password)
{
var saltBytes = Rng.GetRandomBytes(Parameters.SaltLength.Value);
var salt = Convert.ToBase64String(saltBytes);
var hashBytes = KeyDerivation.Pbkdf2(password.Value, saltBytes, Parameters.DerivationFunction,
Parameters.IterationCount.Value, Parameters.KeyLength.Value);
var hash = Convert.ToBase64String(hashBytes);
return new HashedPassword(Base64Hash.From(hash), Base64Salt.From(salt));
}
public bool CheckIfPasswordMatchesHash(PlaintextPassword password, HashedPassword hash)
{
var passwordHash = KeyDerivation.Pbkdf2(password.Value, Convert.FromBase64String(hash.Base64Salt.Value), Parameters.DerivationFunction,
Parameters.IterationCount.Value, Parameters.KeyLength.Value);
return passwordHash.SequenceEqual(Convert.FromBase64String(hash.Base64PasswordHash.Value));
}
}
}
</code></pre>
<p><strong>PasswordServiceTests</strong></p>
<pre><code>using AuthSystemPasswordService.Interfaces;
using AuthSystemPasswordService.Services;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using System;
namespace AuthSystemPasswordService.Test
{
[TestClass]
public class PasswordServiceTests
{
[TestMethod]
[TestCategory("UnitTest")]
public void GenerateHashAndSalt_ReturnsSalt_WithNumberOfBytesEqualToSaltLengthParameter()
{
// Arrange
var iterationCount = 10_000;
var saltLength = 16;
var keyLength = 64;
var parameters = new KeyDerivationParameters(KeyDerivationPrf.HMACSHA512,
IterationCount.From(iterationCount), SaltLength.From(saltLength), KeyLength.From(keyLength));
var rng = Substitute.For<ICryptoRng>();
rng.GetRandomBytes(Arg.Any<int>()).Returns(args => new byte[args.Arg<int>()]);
var service = new PasswordService(parameters, rng);
// Act
var hash = service.GeneratePasswordHashAndSalt(PlaintextPassword.From("somePassword"));
// Assert
Assert.AreEqual(saltLength, Convert.FromBase64String(hash.Base64Salt.Value).Length);
}
[TestMethod]
[TestCategory("UnitTest")]
public void GenerateHashAndSalt_ReturnsHash_WithNumberOfBytesEqualToKeyLengthParameter()
{
// Arrange
var iterationCount = 10_000;
var saltLength = 16;
var keyLength = 64;
var parameters = new KeyDerivationParameters(KeyDerivationPrf.HMACSHA512,
IterationCount.From(iterationCount), SaltLength.From(saltLength), KeyLength.From(keyLength));
var rng = Substitute.For<ICryptoRng>();
rng.GetRandomBytes(Arg.Any<int>()).Returns(args => new byte[args.Arg<int>()]);
var service = new PasswordService(parameters, rng);
// Act
var hash = service.GeneratePasswordHashAndSalt(PlaintextPassword.From("somePassword"));
// Assert
Assert.AreEqual(keyLength, Convert.FromBase64String(hash.Base64PasswordHash.Value).Length);
}
[TestMethod]
[TestCategory("UnitTest")]
public void GenerateHashAndSalt_ThenCheckingSamePassword_ReturnsTrue()
{
// Arrange
var iterationCount = 10_000;
var saltLength = 16;
var keyLength = 64;
var parameters = new KeyDerivationParameters(KeyDerivationPrf.HMACSHA512,
IterationCount.From(iterationCount), SaltLength.From(saltLength), KeyLength.From(keyLength));
var rng = Substitute.For<ICryptoRng>();
rng.GetRandomBytes(Arg.Any<int>()).Returns(args => new byte[args.Arg<int>()]);
var service = new PasswordService(parameters, rng);
var password = PlaintextPassword.From("somePass");
// Act
var hash = service.GeneratePasswordHashAndSalt(password);
var checkResult = service.CheckIfPasswordMatchesHash(password, hash);
// Assert
Assert.IsTrue(checkResult);
}
[TestMethod]
[TestCategory("UnitTest")]
public void GenerateHashAndSalt_ThenCheckingOtherPassword_ReturnsFalse()
{
// Arrange
var iterationCount = 10_000;
var saltLength = 16;
var keyLength = 64;
var parameters = new KeyDerivationParameters(KeyDerivationPrf.HMACSHA512,
IterationCount.From(iterationCount), SaltLength.From(saltLength), KeyLength.From(keyLength));
var rng = Substitute.For<ICryptoRng>();
rng.GetRandomBytes(Arg.Any<int>()).Returns(args => new byte[args.Arg<int>()]);
var service = new PasswordService(parameters, rng);
var password = PlaintextPassword.From("somePass");
var otherPass = PlaintextPassword.From("otherPass");
// Act
var hash = service.GeneratePasswordHashAndSalt(password);
var checkResult = service.CheckIfPasswordMatchesHash(otherPass, hash);
// Assert
Assert.IsFalse(checkResult);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T18:53:49.890",
"Id": "449805",
"Score": "0",
"body": "Possibly use https://github.com/BcryptNet/bcrypt.net instead of PBKDF2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T04:32:12.733",
"Id": "450537",
"Score": "0",
"body": "What's your goal? I see a lot of code, but in the end it just performs PBKDF2 and base 64 encoding? Wrapper classes should not be a goal in itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T13:34:52.963",
"Id": "450582",
"Score": "0",
"body": "@MaartenBodewes Ultimately, the goal is to provide a mockable, easy-to-use interface for the rest of my authentication/authorization system to use that has a bit more type safety than throwing byte[]'s around."
}
] |
[
{
"body": "<p>One potential security issue, as mentioned in <a href=\"https://codereview.stackexchange.com/a/104911/95905\">this answer</a> to a similar piece of code, is that the use of <code>SequenceEqual()</code> in <code>CheckIfPasswordMatchesHash()</code> may open this up to timing attacks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T17:53:25.933",
"Id": "230775",
"ParentId": "230774",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T17:51:59.010",
"Id": "230774",
"Score": "1",
"Tags": [
"c#",
".net",
"security",
"cryptography",
".net-core"
],
"Title": "Small service for hashing and validating passwords, using PBKDF2"
}
|
230774
|
<p><a href="https://leetcode.com/problems/greatest-common-divisor-of-strings/" rel="nofollow noreferrer">https://leetcode.com/problems/greatest-common-divisor-of-strings/</a></p>
<blockquote>
<p>For strings S and T, we say "T divides S" if and only if S = T + ... +
T (T concatenated with itself 1 or more times)</p>
<p>Return the largest string X such that X divides str1 and X divides
str2.</p>
<pre><code>Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
Note:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1[i] and str2[i] are English uppercase letters.
</code></pre>
</blockquote>
<p>I had 30 minutes to solve this.
please review this as a real interview.</p>
<p>what is a red flag, remember code will not be prefect.</p>
<pre><code>using System;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StringQuestions
{
/// <summary>
/// https://leetcode.com/problems/greatest-common-divisor-of-strings/
/// </summary>
[TestClass]
public class GreatestCommonDivisorOfStringsTest
{
[TestMethod]
public void TestMethod1()
{
string str1 = "ABABAB";
string str2 = "ABAB";
string res = GCDOfStringsclass.GcdOfStrings(str1, str2);
Assert.AreEqual("AB", res);
}
[TestMethod]
public void TestMethod2()
{
string str1 = "ABCDEF";
string str2 = "ABC";
string res = GCDOfStringsclass.GcdOfStrings(str1, str2);
Assert.AreEqual(string.Empty, res);
}
}
public class GCDOfStringsclass
{
public static string GcdOfStrings(string str1, string str2)
{
int min = Math.Min(str1.Length, str2.Length);
StringBuilder build = new StringBuilder();
//build largest prefix
for (int i = 0; i < min; i++)
{
if (str1[i] != str2[i])
{
break;
}
build.Append(str1[i]);
}
// no common prefix
string prefix = build.ToString();
if (prefix.Length == 0)
{
return string.Empty;
}
while (str1.Length % prefix.Length != 0 || str2.Length % prefix.Length != 0)
{
prefix = prefix.Remove(prefix.Length - 1);
if (prefix.Length == 0)
{
return string.Empty;
}
}
for (int i = 0; i < str1.Length / prefix.Length; i++)
{
for (int j = 0; j < prefix.Length; j++)
{
if (str1[j + prefix.Length * i] != prefix[j])
{
return string.Empty;
}
}
}
for (int i = 0; i < str2.Length / prefix.Length; i++)
{
for (int j = 0; j < prefix.Length; j++)
{
if (str2[j + prefix.Length * i] != prefix[j])
{
return string.Empty;
}
}
}
return prefix;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The first step in your method is to determine the longest common prefix. Here it would be sufficient to determine the <em>length</em> of the longest common prefix. Building the prefix string itself is not necessary at this point.</p>\n\n<p>The next step is to decrease that length until it divides both string lengths. An explaining comment would be helpful here. We still don't need the prefix string itself, it suffices to decrease the previously determined prefix length.</p>\n\n<p>Finally you determine if the prefix “divides” both strings. At this point we can build the actual <code>prefix</code> string. Again a short comment could be helpful. Instead of the inner loop I would compare substrings (unless that turns out to be too slow):</p>\n\n<pre><code>var prefix = str1.Substring(0, prefixLength);\n\n// Verify that `str1` is a multiple of `prefix`:\nfor (int i = 1; i < str1.Length / prefixLength; i++)\n{\n if (prefix != str1.Substring(i * prefixLength, prefixLength))\n {\n return string.Empty;\n }\n}\n\n// Same for `str2` ...\n</code></pre>\n\n<p>Note that the loop can start with <code>i = 1</code> because we already now that both strings start with <code>prefix</code>. Since the same logic is applied to both strings I would also consider to move it to a separate <code>IsMultipleOf</code> function.</p>\n\n<p><strong>Performance:</strong> Consider the following example:</p>\n\n<pre><code>str1 = \"AAA......A\" // 999 characters\nstr2 = \"AAA......AA\" // 1000 characters\n</code></pre>\n\n<p>Your method builds a prefix string of 999 characters first, and then removes successively all but one character, because <code>1</code> is the only length that divides both string lengths.</p>\n\n<p>As mentioned above, this can be improved by updating the prefix length only, but one can still do better:</p>\n\n<p>It is not difficult to see that the length of <code>X</code> must be exactly the <a href=\"https://en.wikipedia.org/wiki/Greatest_common_divisor\" rel=\"nofollow noreferrer\">greatest common divisor</a> of the lengths of <code>str1</code> and <code>str2</code> – and that can be determined efficiently with the <a href=\"https://en.wikipedia.org/wiki/Euclidean_algorithm\" rel=\"nofollow noreferrer\">Euclidean algorithm</a>.</p>\n\n<p>The implementation would then look like this:</p>\n\n<pre><code>private static int gcd(int a, int b)\n{\n // Your favorite implementation of the Euclidean algorithm...\n}\n\npublic static string GcdOfStrings(string str1, string str2)\n{\n var prefixLength = gcd(str1.Length, str2.Length);\n var prefix = str1.Substring(0, prefixLength);\n\n // Is it a common prefix?\n if (prefix != str2.Substring(0, prefixLength)) {\n return \"\";\n }\n\n // Verify that `str1` is a multiple of `prefix` ...\n // Verify that `str2` is a multiple of `prefix` ...\n\n return prefix;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T21:11:20.320",
"Id": "449813",
"Score": "0",
"body": "cool man. FYI my answer is one of the fastest answers in LeetCode's site, but as I can see there is always room for improvement! thanks man"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T19:42:59.840",
"Id": "230783",
"ParentId": "230777",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230783",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T18:12:16.657",
"Id": "230777",
"Score": "2",
"Tags": [
"c#",
"programming-challenge",
"strings",
"interview-questions"
],
"Title": "LeetCode: Greatest Common Divisor of Strings C#"
}
|
230777
|
<p>I have a MediaWiki 1.33.0 website with only one external addon installed (external extension), which is <a href="https://mediawiki.org/wiki/Extension:ContactPage" rel="nofollow noreferrer">ContactPage</a>.<br>
I have created the following script with that logic:</p>
<blockquote>
<p><strong>if</strong> there is an upgrade to either MediaWiki core OR ContactPage these will be upgraded respectively;<br>
<strong>else</strong>, the script keeps the original state (that is, the state before the upgrade attempt).<br> <sub>Successful upgrading might
require further manual changes although I didn't have a case of
needing to make manual changes.</sub></p>
</blockquote>
<p>I tested the script and it seems to work as expected; if no new version was released, the current ones are kept.</p>
<h2>The script:</h2>
<pre><code># Declare MediaWiki download variables (ensure latest versions are downloaded because as of 08/10/19 there aren't version-agnostic download links):
latest_mediawiki_core="https://releases.wikimedia.org/mediawiki/1.33/mediawiki-1.33.0.tar.gz"
latest_contactpage_extension="https://extdist.wmflabs.org/dist/extensions/ContactPage-REL1_33-abdcab9.tar.gz"
# Declare other important variables:
current_date="$(date +%Y-%m-%d-%H-%M-%S)"
war="$HOME/public_html" # Web Application Root # Change to your Web Application Root if needed
domain="example.com" # Change to relevant domain
db-username_and_db-name="DB_CREDENTIALS" # Change to relevant DB credentials
# Create backup directories:
mkdir -p "${war}/mediawiki_general_backups"
mkdir -p "${war}/mediawiki_specific_backups"
# General backups:
zip -r "${war}/mediawiki_general_backups/${domain}-directory-backup-${current_date}.zip" "${war}/${domain}"
mysqldump \
-u "${db-username_and_db-name}" \
-p "${db-username_and_db-name}" \
> "${war}/mediawiki_general_backups/${db-username_and_db-name}-${current_date}.sql"
# Specific backups:
rm "${war}"/mediawiki_specific_backups/*
rm "${war}"/mediawiki_specific_backups/.* # If I won't run this, a specific backup of .htaccess, in that directory, won't get deleted;
cp "${war}/${domain}"/.htaccess* "${war}/mediawiki_specific_backups"/.htaccess*
cp "${war}/${domain}"/LocalSettings.php "${war}/mediawiki_specific_backups"/LocalSettings.php
cp "${war}/${domain}"/robots.txt "${war}/mediawiki_specific_backups"/robots.txt
cp "${war}/${domain}"/${domain}.png "${war}/mediawiki_specific_backups"/${domain}.png
cp "${war}/${domain}"/googlec69e044fede13fdc.html "${war}/mediawiki_specific_backups"/googlec69e044fede13fdc.html
# Downloads and configurations:
rm -rf "${war}/${domain}"
mkdir "${war}/${domain}"
wget "${latest_mediawiki_core}" -O - | tar -xzv --strip-components 1 -C "${war}/${domain}"
wget "${latest_contactpage_extension}" -O - | tar -xzv -C "${war}/${domain}"/extensions/
cp -a "${war}/mediawiki_specific_backups"/* "${war}/${domain}"
# Create a new sitemap:
mkdir -p "${war}/${domain}/sitemap"
php "${war}/${domain}"/maintenance/generateSitemap.php \
--memory-limit=50M \
--fspath=/"${war}/${domain}/sitemap" \
--identifier="${domain}" \
--urlpath=/sitemap/ \
--server=https://"${domain}" \
--compress=yes
# Update DB (One might need to change LocalSettings.php before doing so):
php "${war}/${domain}"/maintenance/update.php
</code></pre>
|
[] |
[
{
"body": "<p>The reading could be clearer using meaningful variable names. The concatenation of very long variable names does not improve the reading either. That is to say, the shell syntax is not suited to define several variables in a row: the code becomes more difficult to read.</p>\n\n<h2>Variables</h2>\n\n<p>Some variables seem necessary but you may remove or at least ignore some variables. The shell commands (or utilities) should stand out in the shell script. The command line should looks like the following one.</p>\n\n<pre><code>wget -q -O - \"http://wordpress.org/latest.tar.gz\" | tar -xzf - -C /var/www\n</code></pre>\n\n<p>Eventually, you may use some variables in replacement to avoid hard-coding values as in your snippet.</p>\n\n<pre><code>wget \"${latest_mediawiki_core}\" -O - | tar -xzv --strip-components 1 -C \"${war}/${domain}\"\n</code></pre>\n\n<p>Personally, I would have used macros instead of shell variables to improve the readability.</p>\n\n<pre><code>wget MEDIAWIKI -O - | tar -xzv --strip-components 1 -C DESTDIR\n</code></pre>\n\n<h2>Code factorization</h2>\n\n<p>You may replace several command invocations by only one or shorten the code.</p>\n\n<pre><code>cp \"${war}/${domain}\"/.htaccess* \"${war}/mediawiki_specific_backups\"/.htaccess*\ncp \"${war}/${domain}\"/LocalSettings.php \"${war}/mediawiki_specific_backups\"/LocalSettings.php\ncp \"${war}/${domain}\"/robots.txt \"${war}/mediawiki_specific_backups\"/robots.txt\ncp \"${war}/${domain}\"/${domain}.png \"${war}/mediawiki_specific_backups\"/${domain}.png\ncp \"${war}/${domain}\"/googlec69e044fede13fdc.html \"${war}/mediawiki_specific_backups\"/googlec69e044fede13fdc.html\n</code></pre>\n\n<p>In the above code snippet, you can see a lot of duplicated information.</p>\n\n<pre><code># move in the target directory\npushd DESTDIR >/dev/null\n# copy some configuration files\ncp -v .htaccess* LocalSettings.php robots.txt home.png googlec69e044fede13fdc.html NEWDIR\n# come back to the previous directory\npopd >/dev/null\n</code></pre>\n\n<p>Eventually, you may use a subshell to perform the directory change.</p>\n\n<pre><code>(cd DESTDIR || exit; \n cp -v .htaccess* LocalSettings.php robots.txt home.png googlec69e044fede13fdc.html NEWDIR) \n</code></pre>\n\n<p>Note: <code>pushd</code> and <code>popd</code> are Bash builtins. The comments made in the above code snippet are not particularly appropriate, it depends on your scripting knowledge.</p>\n\n<h2>Conclusion</h2>\n\n<p>Using a shell script to update your MediaWiki installation may be good enough by making the suited changes.</p>\n\n<hr>\n\n<h2>M4 macros</h2>\n\n<pre class=\"lang-none prettyprint-override\"><code>define(`MEDIAWIKI_SITE', `https://releases.wikimedia.org/mediawiki')dnl\ndefine(`MEDIAWIKI_VERSION', `1.33')dnl\ndefine(`MEDIAWIKI_RELEASE', `MEDIAWIKI_VERSION.1')dnl\ndefine(`MEDIAWIKI_SOURCE', `\"MEDIAWIKI_SITE/MEDIAWIKI_VERSION/mediawiki-core-MEDIAWIKI_RELEASE.tar.gz\"')dnl\ndefine(`MEDIAWIKI', defn(`MEDIAWIKI_SOURCE'))dnl\ndefine(`DESTDIR', `/tmp/some_directory')dnl\n</code></pre>\n\n<p>We may define some m4 macros (it is just an example).</p>\n\n<pre><code>#!/bin/bash\n\necho 'wget MEDIAWIKI -O - | tar -xzv --strip-components 1 -C DESTDIR'\n</code></pre>\n\n<p>M4 is then used to substitute the macros in the shell script.</p>\n\n<pre><code>cat macros.m4 mediawiki.bash | m4 | bash\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T17:07:48.200",
"Id": "455454",
"Score": "2",
"body": "Don't use `pushd` and `popd` in scripts. They are meant for interactive use. Prefer to use a subshell instead (and check that the `cd` succeeds): `( cd \"$SRCDIR\" && cp -v \"${FILES[@]}\" \"$DESTDIR\" )`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T17:16:09.647",
"Id": "455457",
"Score": "0",
"body": "Or avoid the directory change by using brace-expansion: `cp -t \"${war}/mediawiki_specific_backups/\" \"${war}/${domain}\"/.htaccess \"${war}/${domain}\"/{LocalSettings.php,robots.txt,${domain}.png,googlec69e044fede13fdc.html}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T20:20:47.843",
"Id": "455474",
"Score": "2",
"body": "They're not portable, and they always produce output, which then needs to be redirected (usually to `/dev/null`). They are a simple shortcut for interactive use, but cumbersome even in Bash-only scripts. It's easier and clearer to save location into a variable or to use a subshell. I don't think that the BashPitfalls item is strongly recommending `pushd`; it says, \"*The subshell version is simpler and cleaner*\"... I wouldn't say that using `pushd` and `popd` in scripts is \"incorrect\", but I think it's a poor practice."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T08:58:07.303",
"Id": "231182",
"ParentId": "230780",
"Score": "3"
}
},
{
"body": "<p>Repeating a bit what Fólkvangr said in <a href=\"https://codereview.stackexchange.com/a/231182/9452\">his excellent answer</a>.</p>\n\n<p><strong>More variables</strong></p>\n\n<p>The same expressions (with potentially hardcoded strings) are used many times in many places (most of them corresponding to paths). That makes things potentially hard to understand and to update.</p>\n\n<p>You should try to define more variables (actually used as constants).</p>\n\n<p>Taking this chance to rename them, reorder them, redocument them, we'd get:</p>\n\n<pre><code># Declare MediaWiki download variables (ensure latest versions are downloaded because as of 08/10/19 there aren't version-agnostic download links):\nMEDIAWIKI_CORE_URL=\"https://releases.wikimedia.org/mediawiki/1.33/mediawiki-1.33.0.tar.gz\"\nCONTACTPAGE_EXTENSION_URL=\"https://extdist.wmflabs.org/dist/extensions/ContactPage-REL1_33-abdcab9.tar.gz\"\n\n# Credentials\nDOMAIN=\"example.com\" # Change to relevant domain\nDB_USER_AND_DB_NAME=\"DB_CREDENTIALS\" # Change to relevant DB credentials\n\n# Constant paths\nWEB_APPL_ROOT=\"$HOME/public_html\" # Change to your Web Application Root if needed\nGENERAL_BACKUP_DIR=\"${WEB_APPL_ROOT}/mediawiki_general_backups\"\nSPECIFIC_BACKUP_DIR=\"${WEB_APPL_ROOT}/mediawiki_specific_backups\"\nDOMAIN_DIR=\"${WEB_APPL_ROOT}/${DOMAIN}\"\n\n# Date to be used in backup filenames\nDATE=\"$(date +%Y-%m-%d-%H-%M-%S)\"\n\n# Create backup directories:\nmkdir -p \"${GENERAL_BACKUP_DIR}\"\nmkdir -p \"${SPECIFIC_BACKUP_DIR}\"\n\n# General backups:\nzip -r \"${GENERAL_BACKUP_DIR}/${DOMAIN}-directory-backup-${DATE}.zip\" \"${DOMAIN_DIR}\"\nmysqldump -u \"${DB_USER_AND_DB_NAME}\" -p \"${DB_USER_AND_DB_NAME}\" \\\n > \"${GENERAL_BACKUP_DIR}/${DB_USER_AND_DB_NAME}-${DATE}.sql\"\n\n# Specific backups:\nrm \"${SPECIFIC_BACKUP_DIR}\"/*\nrm \"${SPECIFIC_BACKUP_DIR}\"/.* # If I won't run this, a specific backup of .htaccess, in that directory, won't get deleted;\n\ncp \"${DOMAIN_DIR}\"/.htaccess* \"${SPECIFIC_BACKUP_DIR}/\".htaccess*\ncp \"${DOMAIN_DIR}/LocalSettings.php\" \"${SPECIFIC_BACKUP_DIR}/LocalSettings.php\"\ncp \"${DOMAIN_DIR}/robots.txt\" \"${SPECIFIC_BACKUP_DIR}/robots.txt\"\ncp \"${DOMAIN_DIR}/${DOMAIN}.png\" \"${SPECIFIC_BACKUP_DIR}/${DOMAIN}.png\"\ncp \"${DOMAIN_DIR}/googlec69e044fede13fdc.html\" \"${SPECIFIC_BACKUP_DIR}/googlec69e044fede13fdc.html\"\n\n# Downloads and configurations:\nrm -rf \"${DOMAIN_DIR}\"\nmkdir \"${DOMAIN_DIR}\"\nwget \"${MEDIAWIKI_CORE_URL}\" -O - | tar -xzv --strip-components 1 -C \"${DOMAIN_DIR}\"\nwget \"${CONTACTPAGE_EXTENSION_URL}\" -O - | tar -xzv -C \"${DOMAIN_DIR}/extensions/\"\ncp -a \"${SPECIFIC_BACKUP_DIR}\"/* \"${DOMAIN_DIR}\"\n\n# Create a new sitemap:\nmkdir -p \"${DOMAIN_DIR}/sitemap\"\nphp \"${DOMAIN_DIR}/maintenance/generateSitemap.php\" \\\n--memory-limit=50M \\\n--fspath=\"/${DOMAIN_DIR}/sitemap\" \\\n--identifier=\"${DOMAIN}\" \\\n--urlpath=/sitemap/ \\\n--server=\"https://${DOMAIN}\" \\\n--compress=yes\n\n# Update DB (One might need to change LocalSettings.php before doing so):\nphp \"${DOMAIN_DIR}/maintenance/update.php\"\n</code></pre>\n\n<p><strong>Cleaning things the easy way</strong></p>\n\n<p>Instead of</p>\n\n<pre><code>mkdir -p \"${SPECIFIC_BACKUP_DIR}\"\n\n(...)\n\n# Specific backups:\nrm \"${SPECIFIC_BACKUP_DIR}\"/*\nrm \"${SPECIFIC_BACKUP_DIR}\"/.* # If I won't run this, a specific backup of .htaccess, in that directory, won't get deleted;\n</code></pre>\n\n<p>You could do:</p>\n\n<pre><code># Specific backups:\nrm -r \"${SPECIFIC_BACKUP_DIR}\"\nmkdir -p \"${SPECIFIC_BACKUP_DIR}\"\n</code></pre>\n\n<p>without having to worry about hidden files.</p>\n\n<p><strong>Copying the easy way</strong></p>\n\n<p>Instead of \"cp abcd/foo efgh/foo\", you can just \"cp abcd/foo efgh\"</p>\n\n<p>Thus, you get:</p>\n\n<pre><code>cp \"${DOMAIN_DIR}\"/.htaccess* \"${SPECIFIC_BACKUP_DIR}/\"\ncp \"${DOMAIN_DIR}/LocalSettings.php\" \"${SPECIFIC_BACKUP_DIR}/\"\ncp \"${DOMAIN_DIR}/robots.txt\" \"${SPECIFIC_BACKUP_DIR}/\"\ncp \"${DOMAIN_DIR}/${DOMAIN}.png\" \"${SPECIFIC_BACKUP_DIR}/\"\ncp \"${DOMAIN_DIR}/googlec69e044fede13fdc.html\" \"${SPECIFIC_BACKUP_DIR}/\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T17:03:24.557",
"Id": "455453",
"Score": "1",
"body": "Why did you use upper-case for variable names? That's normally only used for environment variables used to communicate between processes, and it loses that distinction if you name your ordinary variables like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T21:08:25.237",
"Id": "455476",
"Score": "0",
"body": "Oh I've seen that convention used in the past and thought it was normal. Now that I see your comment it makes a lot more sense to use lower case indeed. I'll try to update my answer. In the meantime, feel free to downvote"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T10:00:13.757",
"Id": "233054",
"ParentId": "230780",
"Score": "2"
}
},
{
"body": "<p>Many of the commands in the script only make sense if the previous commands were successful. But there's no checking.</p>\n\n<p>The simple way to get much of that checking for free, is to set the shell's <strong>exit on error</strong> flag:</p>\n\n<pre><code>set -e\n</code></pre>\n\n<p>I also recommend setting <strong>error on undefined</strong> to help pick up mistyped variable names:</p>\n\n<pre><code>set -eu\n</code></pre>\n\n<p>Make sure you understand the power and limitations of these options; in particular, it's important to know the contexts where failing commands won't cause the script to exit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T17:13:14.830",
"Id": "233079",
"ParentId": "230780",
"Score": "2"
}
},
{
"body": "<h3>Make the process <em>approach</em> atomic</h3>\n\n<p>The script first wipes out <code>${war}/${domain}</code>,\nthen populates it with content from <code>wget</code> commands,\nand restores content from backup.</p>\n\n<p>The <code>wget</code> commands are a serious risk here.\nIf any of the source sites is down or experiencing instability at the time the script runs,\nyour site can end up in an inconsistent state.</p>\n\n<p>At the minimum, it would be better to fetch all external resources before you start rewriting your content.</p>\n\n<p>An even better way would be to try to make the process as atomic as possible:\nbuild up the new content in a dedicated directory isolated from production,\nbut on the same partition,\nand when all is ready, make the switch in fast directory rename operations.</p>\n\n<h3>Separate your backups from your production environment</h3>\n\n<p>The <code>$war</code> directory looks clearly in the heart of the production environment.\nIn that directory, you create backup directories side by side with the <code>$domain</code> directory.\nI suggest to create the backups elsewhere.\nIdeally on a different filesystem partition.</p>\n\n<p>Closely related to this, the backup directories are somewhere in <code>$war/...</code>,\nand the original content is also somewhere in <code>$war/...</code>.\nI think this invites mistakes.\nIf you had distinct variable name prefixes such as <code>$backup_...</code> and <code>$content</code>,\nthat would reduce the risk of mistakes.</p>\n\n<h3>Syntax error</h3>\n\n<p>I don't understand what this is doing in a Bash script:</p>\n\n<blockquote>\n<pre><code>db-username_and_db-name=\"DB_CREDENTIALS\"\n</code></pre>\n</blockquote>\n\n<p>This is an invalid statement in all Bash versions that I know.</p>\n\n<h3>Bash scripts should have a shebang</h3>\n\n<p>The posted code has no shebang.\nSince the question is tagged <code>bash</code>,\nmaybe it's implied it's really there in your version,\nbut just for the record, every Bash script should start with a shebang.</p>\n\n<h3>Watch out for things that may go wrong</h3>\n\n<p>Toby already mentioned this in his review,\nbut I think it deserves to be stressed.\nMany things can go wrong in this script:</p>\n\n<ul>\n<li>If <code>mysqldump</code> fails for some reason, the script will keep going without a backup created. That can lead to data loss, and it's to be avoided.</li>\n<li>If any of the <code>wget</code> commands fail for some reason, the script will keep going and update the sitemap and the DB. That can lead to inconsistent state of your site that's difficult to debug.</li>\n</ul>\n\n<p>My suggestion is similar to Toby's:\nput <code>set -euo pipefail</code> near the top of the script,\nto make it stop executing when something goes wrong unexpectedly.</p>\n\n<h3>Double-quote variables used in command arguments</h3>\n\n<p>You did that correctly for the most part,\nyou missed just one here:</p>\n\n<blockquote>\n<pre><code>cp \"${war}/${domain}\"/${domain}.png \"${war}/mediawiki_specific_backups\"/${domain}.png\n</code></pre>\n</blockquote>\n\n<h3>Use more variables</h3>\n\n<p>The term <code>${war}/mediawiki_general_backups</code> comes up repeatedly.\nIt would be better if it was in a variable.\nEditors with Bash support will make it possible to rename, see, find easily all occurrences.</p>\n\n<h3>Make long pipelines easier to read and understand</h3>\n\n<p>Take for example this:</p>\n\n<blockquote>\n<pre><code>wget \"${latest_mediawiki_core}\" -O - | tar -xzv --strip-components 1 -C \"${war}/${domain}\"\n</code></pre>\n</blockquote>\n\n<p>I think it's better to write flags before arguments.\nThe text closer to the left is naturally easier to read.\nAnd the flags pack a lot of important details in little space,\nand the URL argument is long and not very interesting to read.</p>\n\n<p>Secondly, it's easier to understand code when there is a single statement per line.\nA good way to achieve that is by splitting the line at each command in the pipeline.</p>\n\n<p>That is, I suggest writing like this:</p>\n\n<pre><code>wget -O- \"${latest_mediawiki_core}\" \\\n| tar -xzv --strip-components 1 -C \"${war}/${domain}\"\n</code></pre>\n\n<h3>Simplify</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>rm \"${war}\"/mediawiki_specific_backups/*\nrm \"${war}\"/mediawiki_specific_backups/.* # If I won't run this, a specific backup of .htaccess, in that directory, won't get deleted;\n</code></pre>\n</blockquote>\n\n<p>Why not simply:</p>\n\n<pre><code>rm -r \"${war}\"/mediawiki_specific_backups\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-28T20:06:02.747",
"Id": "455604",
"Score": "0",
"body": "Hello, I saw you asked me questions inside the answer; I think clarification questions should be asked only in comments as it is unclear where I should answer... I invite you to comment on the question directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:03:47.943",
"Id": "455908",
"Score": "1",
"body": "@JohnDoea Sometimes I like to lead users to discover solutions by making them ask themselves questions. I removed these rhetorical questions to avoid ambiguity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:05:50.103",
"Id": "455909",
"Score": "0",
"body": "Thank you --- as I understand you mean there surly isn't any literal `if-else` but not surly a philosophical one..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:16:56.423",
"Id": "455922",
"Score": "0",
"body": "@JohnDoea When you write, \"the script keeps the original state\", my expectation is that the script doesn't modify the environment. The script does modify the environment, if the packages are the same version as before, the result *should be* identical, but that's not the same thing as not modifying the environment at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:24:32.597",
"Id": "455924",
"Score": "0",
"body": "I guess I would agree even though I miss the point --- maybe an edit of the question would be helpful when I control versions by the diff tool."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T10:23:17.557",
"Id": "469530",
"Score": "0",
"body": "Hello `cp \"${war}/${domain}\"/${domain}.png \"${war}/mediawiki_specific_backups\"/${domain}.png\n` where is the problem? both segments are double quoted. Please help me to understand you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T10:44:12.720",
"Id": "469532",
"Score": "0",
"body": "@JohnDoea Some variables are outside of double-quotes. It should be `cp \"${war}/${domain}/${domain}.png\" \"${war}/mediawiki_specific_backups/${domain}.png\"`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T11:00:37.493",
"Id": "469535",
"Score": "0",
"body": "oh I understand you now. I am working with VSCODE on a better script right now; thank you all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T02:51:09.793",
"Id": "469587",
"Score": "0",
"body": "Hello again janos; I humbly suggested an edit and did my best to give a detailed, accurate edit summary; I ask you in great plea to read the edit summary and kindly consider to reject or accept - I respect any consideration made, of course and will not further discuss it.With respect,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T05:52:14.957",
"Id": "469598",
"Score": "1",
"body": "@JohnDoea I accepted your edit."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T20:07:44.310",
"Id": "233085",
"ParentId": "230780",
"Score": "4"
}
},
{
"body": "<p>You should save all files that are downloaded by <code>wget</code> in a local directory, either called <code>distfiles</code>, or <code>download</code>, or even <code>cache</code>. This makes upgrading independent of the internet being available, and also prevents unnecessary duplicate downloads. Plus, it allows the downloaded files to be checked whether they are <a href=\"https://www.mediawiki.org/keys/keys.html\" rel=\"nofollow noreferrer\">cryptographically signed</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T10:08:16.200",
"Id": "469527",
"Score": "0",
"body": "Hello Roland, `This makes upgrading independent of the internet being available` ; I didn't understand this. I further misunderstood why the destination directory allows checking or not checking if a file is `cryptographically signed`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T18:13:02.523",
"Id": "469568",
"Score": "1",
"body": "The first step should be to download all necessary files. After that step, you can verify that the files are indeed from the correct publisher. Downloading the files should be a separate step from upgrading since the internet might fail just at the moment you want to upgrade. If you download the files first, you can just skip that step later. It also saves bandwidth. For example, in [pkgsrc](https://pkgsrc.org) a software package is installed by following these steps: fetch, checksum, tools, extract, patch, configure, build, install, package. Each of these steps can be run on its own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T12:21:38.177",
"Id": "469618",
"Score": "0",
"body": "Did you mean to say that I both download and upgrade because of the piping and tar as with `wget \"${latest_mediawiki_core}\" -O - | tar -xzv --strip-components 1 -C \"${war}/${domain}\"` AND `wget \"${latest_contactpage_extension}\" -O - | tar -xzv -C \"${war}/${domain}\"/extensions/`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T12:22:18.927",
"Id": "469619",
"Score": "0",
"body": "If not, than I misunderstand how did I both downloaded and upgraded instead doing both separately (if I'm not wrong, piping to tar would only succeed if the download itself succeeded, but I might be wrong)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:14:49.273",
"Id": "469696",
"Score": "0",
"body": "Yes, exactly. And sorry for giving you the too generic link to pkgsrc first. The relevant part is better described here: https://www.netbsd.org/docs/pkgsrc/build.html"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-28T07:39:59.733",
"Id": "233104",
"ParentId": "230780",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "231182",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T18:29:04.020",
"Id": "230780",
"Score": "5",
"Tags": [
"bash",
"linux",
"installer",
"wikipedia"
],
"Title": "Upgrade script for MediaWiki website with one external addon (wave 1)"
}
|
230780
|
<p>Sometimes I'm not sure if my questions should be here or StackOverflow, so I appologize if this is the wrong place.</p>
<p>I have a SQL (MS SQL 2016) stored procedure that is evaluating data looking for duplicates. Since not all data is present missing fields are blank ('') not NULL. I compare the data and give a confidence score.</p>
<p>It works for the most part, however, it doesn't process any of the entries with a blank Company. Ideally I think I'd want the blank company to be processed just like the other companies. I'm not entirely confident that it is calculating correctly to catch everything.</p>
<pre><code>SELECT
ranking AS score,
RankMapping.description AS code,
'CUST' AS tablename,
Duplicate.uid AS tableID,
originalCustNo
FROM (
SELECT
FirstCompany.uid AS originalCustNo,
Duplicate.*,
CASE WHEN FirstCompany.uid = Duplicate.uid THEN 1 ELSE 0 END
+ CASE WHEN FirstCompany.company = Duplicate.company THEN 1 ELSE 0 END
+ CASE WHEN FirstCompany.fname = Duplicate.fname AND FirstCompany.lname = Duplicate.lname THEN 1 ELSE 0 END
+ CASE WHEN FirstCompany.add1 = Duplicate.add1 AND FirstCompany.city = Duplicate.city THEN 1 ELSE 0 END
+ CASE WHEN FirstCompany.phone1 = Duplicate.phone1 THEN 1 ELSE 0 END
+ CASE WHEN FirstCompany.email = Duplicate.email THEN 1 ELSE 0 END
AS ranking
FROM
(
SELECT uid, company, fname, lname, add1, city, phone1, email
FROM (
SELECT uid, company, fname, lname, add1, city, phone1, email,
ROW_NUMBER() OVER (PARTITION BY company ORDER BY uid) AS ordering
FROM #tmpCoreData
) FC
WHERE ordering = 1
) AS FirstCompany
JOIN #tmpCoreData Duplicate
ON Duplicate.uid >= FirstCompany.uid
AND Duplicate.company = FirstCompany.company) Duplicate
JOIN (VALUES
(6, 'Original'),
(5, 'Duplicate'),
(4, 'Duplicate'),
(3, 'Likely Dupe'),
(2, 'Possible Dupe'),
(1, 'Not Likely Dupe'),
(0, 'Individual')
) RankMapping(score, description)
ON RankMapping.score = Duplicate.ranking
ORDER BY Duplicate.originalCustNo, Duplicate.ranking DESC
</code></pre>
<p>I put my data table and code into <a href="http://sqlfiddle.com/#!18/16380/1" rel="nofollow noreferrer">SQL Fiddle</a>
I'd appreciate some fresh eyes and suggestions to improve.</p>
<p>Thanks!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T20:22:30.810",
"Id": "230784",
"Score": "1",
"Tags": [
"sql",
"sql-server"
],
"Title": "Searching for Duplicates in SQL Table with Confidence Score"
}
|
230784
|
<h2>Problem</h2>
<p>Given a list and an integer chunk size, divide the list into sublists, where each sublist is of chunk size. </p>
<h2>Codes</h2>
<p>Just for practicing, I've coded to solve the problem using JavaScript and Python. There is also a built-in PHP function for that. If you'd like to review the codes and provide any change/improvement recommendations, please do so and I'd really appreciate that.</p>
<h3>Python</h3>
<pre><code>"""
# Problem
# Given a list and chunk size, divide the list into sublists
# where each sublist is of chunk size
# --- Examples: (Input List, Chunk Size) => Output List
# ([1, 2, 3, 4], 2) => [[ 1, 2], [3, 4]]
# ([1, 2, 3, 4, 5], 2) => [[ 1, 2], [3, 4], [5]]
# ([1, 2, 3, 4, 5, 6, 7, 8], 3) => [[ 1, 2, 3], [4, 5, 6], [7, 8]]
# ([1, 2, 3, 4, 5], 4) => [[ 1, 2, 3, 4], [5]]
# ([1, 2, 3, 4, 5], 10) => [[ 1, 2, 3, 4, 5]]
"""
from typing import TypeVar, List
import math
T = TypeVar('T')
def chunk_with_slice(input_list: List['T'], chunk_size: int) -> List['T']:
if chunk_size <= 0 or not isinstance(input_list, list):
return False
start_index = 0
end_index = chunk_size
iteration = len(input_list) // chunk_size
chunked_list = input_list[start_index:end_index]
output_list = []
output_list.append(chunked_list)
if (len(input_list) % chunk_size != 0):
iteration += 1
for i in range(1, iteration):
start_index, end_index = end_index, chunk_size * (i + 1)
chunked_list = input_list[start_index:end_index]
output_list.append(chunked_list)
return output_list
def chunk_slice_push(input_list: List['T'], chunk_size: int) -> List['T']:
if chunk_size <= 0 or not isinstance(input_list, list):
return False
output_list = []
start_index = 0
while start_index < len(input_list):
chunked_list = input_list[start_index: int(start_index + chunk_size)]
output_list.append(chunked_list)
start_index += chunk_size
return output_list
if __name__ == '__main__':
# ---------------------------- TEST ---------------------------
DIVIDER_DASH = '-' * 50
GREEN_APPLE = '\U0001F34F'
RED_APPLE = '\U0001F34E'
test_input_lists = [
[10, 2, 3, 40, 5, 6, 7, 88, 9, 10],
[-1, -22, 34],
[-1.3, 2.54, math.pi, 4, '5'],
[math.pi, 2, math.pi, 4, 5, 'foo', 7, 8,
'bar', math.tau, math.inf, 12, math.e]
]
test_expected_outputs = [
[
[10, 2],
[3, 40],
[5, 6],
[7, 88],
[9, 10]
],
[
[-1],
[-22],
[34]
],
[
[-1.3, 2.54, math.pi],
[4, '5']
],
[
[math.pi, 2, math.pi, 4, 5],
['foo', 7, 8, 'bar', math.tau],
[math.inf, 12, math.e]
]
]
test_chunk_sizes = [2, 1, 3, 5]
count = 0
for test_input_list in test_input_lists:
test_output_form_chunk_slice = chunk_with_slice(
test_input_list, test_chunk_sizes[count])
test_output_form_chunk_slice_push = chunk_slice_push(
test_input_list, test_chunk_sizes[count])
print(DIVIDER_DASH)
if test_expected_outputs[count] == test_output_form_chunk_slice and test_expected_outputs[count] == test_output_form_chunk_slice_push:
print(f'{GREEN_APPLE} Test {int(count + 1)} was successful.')
else:
print(f'{RED_APPLE} Test {int(count + 1)} was successful.')
count += 1
</code></pre>
<h3>JavaScript</h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function chunk_with_push(input_list, chunk_size) {
const output_list = [];
for (let element of input_list) {
const chunked_list = output_list[output_list.length - 1];
if (!chunked_list || chunked_list.length === chunk_size) {
output_list.push([element]);
} else {
chunked_list.push(element);
}
}
return output_list;
}
function chunk_with_slice(input_list, chunk_size) {
var start_index, end_index, chunked_list;
const output_list = [];
start_index = 0;
end_index = chunk_size;
chunked_list = input_list.slice(start_index, end_index);
output_list.push(chunked_list);
iteration = Math.floor(input_list.length / chunk_size);
if (input_list.length % chunk_size != 0) {
iteration += 1;
}
for (i = 1; i < iteration; i++) {
start_index = end_index;
end_index = chunk_size * (i + 1);
chunked_list = input_list.slice(start_index, end_index);
output_list.push(chunked_list);
}
return output_list;
}
function chunk_slice_push(input_list, chunk_size) {
const output_list = [];
let start_index = 0;
while (start_index < input_list.length) {
output_list.push(input_list.slice(start_index, parseInt(start_index + chunk_size)));
start_index += chunk_size;
}
return output_list;
}
// ---------------------------- TEST ---------------------------
divider_dash = '-----------------'
green_apple = ''
red_apple = ''
const test_input_lists = [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
];
const test_expected_outputs = [
[
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10]
],
[
[1],
[2],
[3]
],
[
[1, 2, 3],
[4, 5]
],
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13]
]
];
const test_chunk_sizes = [2, 1, 3, 5];
var count = 0;
for (let test_input_list of test_input_lists) {
const test_output_form_chunk_push = chunk_with_push(test_input_list, test_chunk_sizes[count]);
const test_output_form_chunk_slice = chunk_with_slice(test_input_list, test_chunk_sizes[count]);
const test_output_form_chunk_slice_push = chunk_slice_push(test_input_list, test_chunk_sizes[count]);
console.log(divider_dash);
if (JSON.stringify(test_expected_outputs[count]) === JSON.stringify(test_output_form_chunk_push) &&
JSON.stringify(test_expected_outputs[count]) === JSON.stringify(test_output_form_chunk_slice) &&
JSON.stringify(test_expected_outputs[count]) === JSON.stringify(test_output_form_chunk_slice_push)
) {
console.log(green_apple + ' Test ' + parseInt(count + 1) + ' was successful.');
} else {
console.log(red_apple + ' Test ' + parseInt(count + 1) + ' was successful');
}
count++;
}</code></pre>
</div>
</div>
</p>
<h3>PHP</h3>
<pre><code>// Problem
// Given a list and chunk size, divide the list into sublists
// where each sublist is of chunk size
// --- Examples: (Input List, Chunk Size) => Output List
// ([1, 2, 3, 4], 2) => [[ 1, 2], [3, 4]]
// ([1, 2, 3, 4, 5], 2) => [[ 1, 2], [3, 4], [5]]
// ([1, 2, 3, 4, 5, 6, 7, 8], 3) => [[ 1, 2, 3], [4, 5, 6], [7, 8]]
// ([1, 2, 3, 4, 5], 4) => [[ 1, 2, 3, 4], [5]]
// ([1, 2, 3, 4, 5], 10) => [[ 1, 2, 3, 4, 5]]
//
function builtInChunk($input_list, $input_size)
{
if ($input_size <= 0 or !is_array($input_list)) {
return false;
}
return array_chunk($input_list, $input_size);
}
// ---------------------------- TEST ---------------------------
$divider_dash = PHP_EOL . '-----------------' . PHP_EOL;
$green_apple = '';
$red_apple = '';
$test_input_lists = [
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
];
$test_expected_outputs = [
[
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10],
],
[
[1],
[2],
[3],
],
[
[1, 2, 3],
[4, 5],
],
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13],
],
];
$test_chunk_sizes = [2, 1, 3, 5];
foreach ($test_input_lists as $key => $test_input_list) {
$test_output_form_chunk_slice = builtInChunk($test_input_list, $test_chunk_sizes[$key]);
print($divider_dash);
if ($test_expected_outputs[$key] === $test_output_form_chunk_slice) {
print($green_apple . ' Test ' . intval($key + 1) . ' was successful.');
} else {
print($red_apple . ' Test ' . intval($key + 1) . ' was successful');
}
}
</code></pre>
<h3>Output</h3>
<pre><code>--------------------------------------------------
Test 1 was successful.
--------------------------------------------------
Test 2 was successful.
--------------------------------------------------
Test 3 was successful.
--------------------------------------------------
Test 4 was successful.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T05:26:17.993",
"Id": "449832",
"Score": "1",
"body": "Rather than posting redundant advice for the php snippet, apply AJNeufeld's advice about throwing and catching. An off-topic question: Why not merge this account with your Stack Overflow account?"
}
] |
[
{
"body": "<h2>Argument Checking and Duck-typing</h2>\n\n<p>Two problems with this code:</p>\n\n<pre><code> if chunk_size <= 0 or not isinstance(input_list, list):\n return False\n</code></pre>\n\n<p>If the arguments are the correct type, the function returns a list of lists. If not, it returns <code>False</code>? This is going to complicate the code which uses the function. It is better to raise an exception:</p>\n\n<pre><code> if chunk_size <= 0:\n raise ValueError(\"Chunk size must be positive\")\n</code></pre>\n\n<p>Secondly, you're requiring the input list to actually be a list. There are many Python types which can behave like a list, but are not instance of <code>list</code>. Tuples and strings are two easy examples. It is often better to just accept the type provided, and try to execute the function with the data given. If the caller provides a something that looks like a duck and quacks like a duck, don't complain that a drake is not a duck.</p>\n\n<h2>Oddity</h2>\n\n<p>In this statement ...</p>\n\n<pre><code>chunked_list = input_list[start_index: int(start_index + chunk_size)]\n</code></pre>\n\n<p>... what is that <code>int()</code> for? It seems unnecessary.</p>\n\n<h2>Return Type</h2>\n\n<p>You are breaking the list into multiple lists. Your return is not just a simple list; it is a list of lists. <code>List[List[T]]</code>.</p>\n\n<h2>Itertools</h2>\n\n<p>Python comes with many tools builtin. Check out the <a href=\"https://docs.python.org/3.7/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code> modules</a>. In particular, look at the <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>grouper()</code> recipe</a>. It reduces your \"chunking\" code into 2 statements.</p>\n\n<pre><code>>>> from itertools import zip_longest\n>>> \n>>> input_list= [10, 2, 3, 40, 5, 6, 7, 88, 9, 10, 11]\n>>> chunk_size = 2\n>>> \n>>> args = [iter(input_list)] * chunk_size\n>>> chunks = list(zip_longest(*args))\n>>> \n>>> chunks\n[(10, 2), (3, 40), (5, 6), (7, 88), (9, 10), (11, None)]\n>>> \n</code></pre>\n\n<p>As demonstrated above, it produces slightly different output. The last chunk is padded with <code>None</code> values until it is the proper length. You could easily filter out these extra values.</p>\n\n<pre><code>>>> chunks[-1] = [item for item in chunks[-1] if item is not None]\n>>> chunks\n[(10, 2), (3, 40), (5, 6), (7, 88), (9, 10), [11]]\n>>>\n</code></pre>\n\n<p>If your list can contain <code>None</code> values, then a sentinel object could be used instead. Revised code:</p>\n\n<pre><code>from itertools import zip_longest\n\ndef chunk_itertools(input_list: List[T], chunk_size: int) -> List[List[T]]:\n\n sentinel = object()\n\n args = [iter(input_list)] * chunk_size\n chunks = list(zip_longest(*args), fillvalue=sentinel)\n chunks[-1] = [item for item in chunks[-1] if item is not sentinel]\n\n return chunks\n</code></pre>\n\n<hr>\n\n<p>JavaScript & PHP reviews left to others</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T22:18:25.590",
"Id": "230791",
"ParentId": "230786",
"Score": "3"
}
},
{
"body": "<p>You have some odd stuff going on in <code>chunk_with_slice</code>; specifically these lines:</p>\n\n<pre><code>def chunk_with_slice(input_list: List['T'], chunk_size: int) -> List['T']:\n if chunk_size <= 0 or not isinstance(input_list, list):\n return False\n</code></pre>\n\n<p>First, you're using <em>strings</em> to represent type vars (<code>List['T']</code>). As mentioned in the comments, strings are used to reference types that can't be referred to directly, such as needing a forward reference, or referencing something in a separate file that can't be imported. You don't need a forward reference here though. I'd just use <code>T</code>:</p>\n\n<pre><code>def chunk_with_slice(input_list: List[T], chunk_size: int) -> List[T]:\n</code></pre>\n\n<p>Second, think about those first two lines. You're basically saying \"<code>input_list</code> is a list. But if it's not a list, return false\". If you say that <code>input_list</code> is a list, you shouldn't be allowing other types in. You've told the type checker to help you catch type errors, so ideally you shouldn't also be trying to recover from bad data at runtime. If you expect that other types may be passed in, specify that using <code>Union</code> (such as <code>Union[List, str]</code> to allow a <code>List</code> and <code>str</code> in).</p>\n\n<hr>\n\n<p>I also agree with @AJ's \"It is often better to just accept the type provided, and try to execute the function with the data given.\" comment. I'd specify <code>input_list</code> to be a <a href=\"https://docs.python.org/3/glossary.html#term-sequence\" rel=\"nofollow noreferrer\"><code>Sequence</code></a> instead. A <code>Sequence</code> is a container capable of indexing/slicing and <code>len</code>. This covers lists, tuples, strings, and others; including user-defined types. Forcing your caller to use a specific container type is unnecessary in most circumstances.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T13:32:44.540",
"Id": "449906",
"Score": "0",
"body": "PEP484 allows type-hints to be given as strings, to allow [forward references](https://www.python.org/dev/peps/pep-0484/#forward-references)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T14:01:39.593",
"Id": "449912",
"Score": "0",
"body": "@AJNeufeld Ahh, thanks. A forward reference isn't necessary here though. I'll update my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T00:32:21.480",
"Id": "230792",
"ParentId": "230786",
"Score": "3"
}
},
{
"body": "<p>For sequences (list, str, tuple, etc), this is rather straight forward:</p>\n\n<pre><code>def chunks(sequence, size):\n return [sequence[index:index+size] for index in range(0, len(sequence), size)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:09:30.780",
"Id": "230853",
"ParentId": "230786",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230791",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T20:43:14.603",
"Id": "230786",
"Score": "2",
"Tags": [
"python",
"javascript",
"beginner",
"algorithm",
"php"
],
"Title": "Split array into chunks (JavaScript, Python, PHP)"
}
|
230786
|
<blockquote>
<p><a href="https://codereview.stackexchange.com/questions/231064/anipop-the-anime-downloader">NOTE: Here's the latest version of this program, since this question idled out.</a></p>
</blockquote>
<p>This is a recreational script made to update my home server w/ the latest anime from <a href="https://horriblesubs.info/" rel="nofollow noreferrer">HorribleSubs</a>. I'd like to know if there are any obvious syntactical and performance improvements, details on my usage of Selenium and BS4 and whether or not this usage is proper. More features will be added later, but as it as now I feel there are ways to improve it. One idea I've had is to install uBlock Origin on the browser instance to decrease the number of elements to iterate over, but I don't know if this would be significant.</p>
<h3>Windows Setup</h3>
<ol>
<li>Install <a href="https://scoop.sh/" rel="nofollow noreferrer">Scoop</a> to install any necessary programs.</li>
<li>Run the following commands for whatever you don't have installed:
<pre class="lang-bsh prettyprint-override"><code>scoop bucket add extras
scoop install python geckodriver qbittorrent
pip install beautifulsoup4 selenium python-qbittorrent
</code></pre></li>
<li>Enable the qBittorrent <a href="https://github.com/lgallard/qBittorrent-Controller/wiki/How-to-enable-the-qBittorrent-Web-UI" rel="nofollow noreferrer">web interface</a>.</li>
</ol>
<h3>Le Code</h3>
<pre class="lang-py prettyprint-override"><code>import urllib.request as Web
from bs4 import BeautifulSoup as bs4
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from qbittorrent import Client
qb = Client('http://127.0.0.1:8080/')
# 'Bypass from localhost' should be enabled
# TODO: Check if this drive is full, and switch to an available one
DL_PATH = "E:/Torrents/"
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:48.0) Gecko/20100101 Firefox/48.0"
req = Web.Request('https://horriblesubs.info/current-season/', headers=headers)
src = Web.urlopen(req).read()
parser = bs4(src, features='html.parser')
divs = parser.body.find_all('div', attrs={'class': 'ind-show'})
size = len(divs)
for i, div in enumerate(divs):
driver = webdriver.Firefox()
driver.get('https://horriblesubs.info' + div.a['href'])
WebDriverWait(driver, 50).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, 'rls-info-container')))
# Expand the whole listing to get all the episodes
elem = driver.find_element_by_class_name('show-more')
while elem.text != 'No more results':
elem.click()
elem = driver.find_element_by_class_name('show-more')
src = driver.page_source
driver.close()
parser = bs4(src, features='html.parser')
hs = parser.body\
.find('div', attrs={'class': 'hs-shows'})\
.find_all('div', attrs={'class': 'rls-info-container'})
for block in hs:
# TODO: If a resolution is updated, delete the lower resolution alternative on disk
link_rel = block.find('div', attrs={'class': 'rls-link link-1080p'})
if (link_rel is None):
link_rel = block.find('div', attrs={'class': 'rls-link link-720p'})
if (link_rel is None):
link_rel = block.find('div', attrs={'class': 'rls-link link-480p'})
if (link_rel is not None):
magnet = link_rel.find('a', attrs={'title': 'Magnet Link'})['href']
qb.download_from_link(magnet, category='anime', savepath=DL_PATH + div.a.text)
print('Progress: ' + str(round(((i + 1) / size) * 100, 2)) + '%')
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T00:41:41.127",
"Id": "230793",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup",
"selenium"
],
"Title": "The anime downloader"
}
|
230793
|
<p>I'm exploring multithreading for some code that I want to speed up in C++. I wrote a simple program to facilitate my understanding. The program takes in two arrays of equal length, the value of the length itself, and a threshold. It outputs all indices <code>i</code> (in any order) where <code>abs(array_1[i]-array_2[i]) < threshold</code>. Here is the code:</p>
<pre><code>#include <mutex>
#include <vector>
#include <thread>
#include <iostream>
std::mutex output_mutex;
void process_element(const uint8_t* input_1, const uint8_t* input_2, const size_t i, const uint8_t threshold, std::vector<size_t>& output){
uint8_t element_1 = input_1[i];
uint8_t element_2 = input_2[i];
uint8_t distance = (element_1 > element_2) ?
element_1 - element_2 :
element_2 - element_1;
if(distance < threshold){
output_mutex.lock();
output.push_back(i);
output_mutex.unlock();
}
}
std::vector<size_t> process(const uint8_t* input_1, const uint8_t* input_2, const size_t length, const uint8_t threshold){
std::vector<size_t> output;
std::vector<std::thread> threads;
for (size_t i = 0; i < length; ++i) {
std::thread t([&](){
process_element(input_1,input_2,i,threshold,output);
});
threads.push_back(std::move(t));
}
for(auto&& thread : threads){
thread.join();
}
return output;
}
int main(){
uint8_t input_1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
uint8_t input_2[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
std::vector<size_t> output = process(input_1,input_2,10, 7);
for(auto&& element : output){
std::cout << int(element) << ' ';
}
}
</code></pre>
<p>It seems to do fine when I run it. </p>
<p>Am I applying multithreading correctly? </p>
<p>Are there any mistakes or things I can improve in my code? </p>
<p>Is there a better/more efficient way to compute the distance in process_element than the way I coded it? </p>
<p>Lastly, I didn't care about the order of the output indices when writing the code, but I couldn't help but notice that the reported values always seem to be in order. Is this just an artifact of the fact that <code>process_element</code> is very simple and takes almost no time at all, or will the output in general be ordered according to the order in which I run the threads?</p>
|
[] |
[
{
"body": "<p>The cost of starting up a thread is generally considered expensive. For your example of only 10 items, you won't ever see it because the application quits before you notice it started. Generally for something like this, you'd want to start up a thread to process some large portion of the array rather than one thread per element of the array. At 10 elements, it's no big deal. But once you have thousands of elements, you don't want thousands of threads running. In fact, many operating systems will limit the number of threads you can start. According to @user673679, you can get the number of concurrent threads by calling <code>std::thread::hardware_concurrency</code>.</p>\n\n<p>I recommend limiting the number of threads to something like the number of available CPU cores on the machine. Then split the input arrays into that many parts and have each thread work on one part of the array. So if you have 8 cores, split the work into 8 parts and have each thread work on 1/8th of the array.</p>\n\n<p>I ran your code with Thread Sanitizer and it's telling me you have a data race. Here's what it says:</p>\n\n<pre><code>WARNING: ThreadSanitizer: data race (pid=7975)\n Read of size 8 at 0x7ffeefbff2f0 by thread T4:\n #0 process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0::operator()() const main.cpp:34 (CPlusPlusTester:x86_64+0x100006b4a)\n #1 decltype(std::__1::forward<process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0>(fp)()) std::__1::__invoke<process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0>(process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0&&) type_traits:4339 (CPlusPlusTester:x86_64+0x100006a00)\n #2 void std::__1::__thread_execute<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0>(std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0>&, std::__1::__tuple_indices<>) thread:342 (CPlusPlusTester:x86_64+0x100006868)\n #3 void* std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0> >(void*) thread:352 (CPlusPlusTester:x86_64+0x1000059f9)\n\n Previous write of size 8 at 0x7ffeefbff2f0 by main thread:\n #0 process(unsigned char const*, unsigned char const*, unsigned long, unsigned char) main.cpp:32 (CPlusPlusTester:x86_64+0x1000018e2)\n #1 main main.cpp:47 (CPlusPlusTester:x86_64+0x100001fa1)\n\n Location is stack of main thread.\n\n Thread T4 (tid=669186, running) created by main thread at:\n #0 pthread_create <null>:2673600 (libclang_rt.tsan_osx_dynamic.dylib:x86_64h+0x2a17d)\n #1 std::__1::__libcpp_thread_create(_opaque_pthread_t**, void* (*)(void*), void*) __threading_support:328 (CPlusPlusTester:x86_64+0x10000593e)\n #2 std::__1::thread::thread<process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0, void>(process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0&&) thread:368 (CPlusPlusTester:x86_64+0x1000055e7)\n #3 std::__1::thread::thread<process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0, void>(process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0&&) thread:360 (CPlusPlusTester:x86_64+0x100001ad8)\n #4 process(unsigned char const*, unsigned char const*, unsigned long, unsigned char) main.cpp:33 (CPlusPlusTester:x86_64+0x10000189f)\n #5 main main.cpp:47 (CPlusPlusTester:x86_64+0x100001fa1)\n\nSUMMARY: ThreadSanitizer: data race main.cpp:34 in process(unsigned char const*, unsigned char const*, unsigned long, unsigned char)::$_0::operator()() const\n</code></pre>\n\n<p>Line 34 is the call to <code>process_element()</code>. @pschill pointed out: </p>\n\n<blockquote>\n <p>The lambda captures all variables by reference, including i. So if the thread starts a little bit too late, the for loop already incremented i and the call to process_element recieves the wrong value. A solution would be changing the lambda capture from [&] to [&, i], so that i is captured by value.</p>\n</blockquote>\n\n<p>You ask:</p>\n\n<blockquote>\n <p>Is this just an artifact of the fact that process_element is very simple and takes almost no time at all, or will the output in general be ordered according to the order in which I run the threads?</p>\n</blockquote>\n\n<p>I think it's just because there's so little work being done that the threads end up executing in order. One is probably done before the next is even started.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T07:58:28.127",
"Id": "449844",
"Score": "2",
"body": "I think the sanitizer found the following problem: The lambda captures all variables by reference, including `i`. So if the thread starts a little bit too late, the for loop already incremented `i` and the call to `process_element` recieves the wrong value. A solution would be changing the lambda capture from `[&]` to `[&, i]`, so that `i` is captured by value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T12:25:44.430",
"Id": "449883",
"Score": "0",
"body": "Just to add: you can get the number of concurrent threads on a machine with `std::thread::hardware_concurrency`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T15:46:14.817",
"Id": "449927",
"Score": "0",
"body": "Oh! Excellent suggestions, both! I'll update my answer to include that information. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-17T04:13:43.087",
"Id": "449982",
"Score": "0",
"body": "Wow, that's a really subtle issue with the lambda. It never even occurred to me that there could be a problem there. I'll have to look more into this Thread Sanitizer thing!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T03:05:07.793",
"Id": "230797",
"ParentId": "230794",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "230797",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T01:40:23.363",
"Id": "230794",
"Score": "3",
"Tags": [
"c++",
"multithreading"
],
"Title": "Finding similar items in two arrays with multithreading in C++"
}
|
230794
|
<ul>
<li><strong>Description:</strong> This is a simple script for scraping Amazon and eBay category, sub-category and product URLs and saving contents to files. In case
of previously saved files, the files will be read and no attempts to
re-scrape contents will be executed.</li>
<li><strong>Documentation:</strong> you will find the most of the information needed in the docstrings.</li>
<li><strong>Private methods:</strong> methods defined are private <code>_method_name</code> because this is an initial part of the program that will feed future
methods that I will add which would be getting product details and
polishing data for applying some data analysis. I will be posting
follow ups to this code when I'm done.</li>
<li><code>_get_amazon_category_names_urls()</code> returns a list mapping, not a dictionary because sometimes there are duplicate titles with different links.</li>
<li><strong>For reviewers:</strong> As this is my first scraping attempt, it might not be the best way of doing it so a whole general review is most welcome
of course. </li>
<li><strong>Focus points:</strong>
<ul>
<li>How to improve the program structure.</li>
<li>How to decrease if not eliminate scraping failures(sometimes some
random urls are not scraped and result in empty .txt files which
will be handled by a defined method, however I want to eliminate
this.)</li>
<li>Is the defined <code>self.headers</code> doing the job (which I think is preventing the target website from blocking the connection after many requests) or is there a better to do it?</li>
</ul></li>
</ul>
<p><strong>Code</strong></p>
<p><strong>Formatted version:</strong></p>
<pre><code>#!/usr/bin/env python3
from bs4 import BeautifulSoup
from time import perf_counter
import os
import requests
class WebScraper:
"""
A tool for scraping websites including:
- Amazon
- eBay
"""
def __init__(
self, website: str, target_url=None, path=None
):
"""
website: A string indication of a website:
- 'ebay'
- 'Amazon'
target_url: A string containing a single url to scrape.
"""
self.supported_websites = ["Amazon", "ebay"]
if website not in self.supported_websites:
raise ValueError(
f"Website {website} not supported."
)
self.website = website
self.target_url = target_url
if not path:
self.path = (
"/Users/user_name/Desktop/code/web scraper/"
)
if path:
self.path = path
self.headers = {
"User-Agent": "Safari/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36"
}
self.amazon_modes = {
"bs": "Best Sellers",
"nr": "New Releases",
"gi": "Gift Ideas",
"ms": "Movers and Shakers",
"mw": "Most Wished For",
}
def _cache_category_urls(
self,
text_file_names: dict,
section: str,
category_class: str,
website: str,
content_path: str,
categories: list,
print_progress=False,
cleanup_empty=True,
):
"""
Write scraped category/sub_category urls to files.
text_file_names: a dictionary containing .txt file names to save data under.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
website: a string 'ebay' or 'Amazon'.
content_path: a string containing path to folder for saving URLs.
categories: a list containing category or sub_category urls to be saved.
print_progress: if True, progress will be displayed.
cleanup_empty: if True, after writing the .txt files, empty files(failures) will be deleted.
"""
os.chdir(content_path + website + "/")
with open(
text_file_names[section][category_class], "w"
) as cats:
for category in categories:
cats.write(category + "\n")
if print_progress:
if open(
text_file_names[section][
category_class
],
"r",
).read(1):
print(
f"Saving {category} ... done."
)
else:
print(
f"Saving {category} ... failure."
)
if cleanup_empty:
self._cleanup_empty_files(
self.path + website + "/"
)
def _read_urls(
self,
text_file_names: dict,
section: str,
category_class: str,
content_path: str,
website: str,
cleanup_empty=True,
):
"""
Read saved urls from a file and return a sorted list containing the urls.
text_file_names: a dictionary containing .txt file names to save data under.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
website: a string 'ebay' or 'Amazon'.
content_path: a string containing path to folder for saving URLs.
print_progress: if True, progress will be displayed.
cleanup_empty: if True, if any empty files found during the execution, the files will be deleted.
"""
os.chdir(content_path + website + "/")
if text_file_names[section][
category_class
] in os.listdir(content_path + "Amazon/"):
with open(
text_file_names[section][category_class]
) as cats:
if cleanup_empty:
self._cleanup_empty_files(
self.path + website + "/"
)
return [
link.rstrip()
for link in cats.readlines()
]
def _scrape_urls(
self,
starting_target_urls: dict,
section: str,
category_class: str,
prev_categories=None,
print_progress=False,
):
"""
Scrape urls of a category class and return a list of URLs.
starting_target_urls: a dictionary containing the initial websites that will start the web crawling.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
prev_categories: if sub_categories are scraped, prev_categories a list of category urls.
print_progress: if True, progress will be displayed.
"""
target_url = starting_target_urls[section][1]
if category_class == "categories":
starting_url = requests.get(
starting_target_urls[section][0],
headers=self.headers,
)
html_content = BeautifulSoup(
starting_url.text, features="lxml"
)
target_url_part = starting_target_urls[section][
1
]
if not print_progress:
return sorted(
{
str(link.get("href"))
for link in html_content.findAll(
"a"
)
if target_url_part in str(link)
}
)
if print_progress:
categories = set()
for link in html_content.findAll("a"):
if target_url_part in str(link):
link_to_add = str(link.get("href"))
categories.add(link_to_add)
print(
f"Fetched {section}-{category_class}: {link_to_add}"
)
return categories
if category_class == "sub_categories":
if not print_progress:
responses = [
requests.get(
category, headers=self.headers
)
for category in prev_categories
]
category_soups = [
BeautifulSoup(
response.text, features="lxml"
)
for response in responses
]
pre_sub_category_links = [
str(link.get("href"))
for category in category_soups
for link in category.findAll("a")
if target_url in str(link)
]
return sorted(
{
link
for link in pre_sub_category_links
if link not in prev_categories
}
)
if print_progress:
responses, pre, sub_categories = (
[],
[],
set(),
)
for category in prev_categories:
response = requests.get(
category, headers=self.headers
)
responses.append(response)
print(
f"Got response {response} for {section}-{category}"
)
category_soups = [
BeautifulSoup(
response.text, features="lxml"
)
for response in responses
]
for soup in category_soups:
for link in soup.findAll("a"):
if target_url in str(link):
fetched_link = str(
link.get("href")
)
pre.append(fetched_link)
print(
f"Fetched {section}-{fetched_link}"
)
return sorted(
{
link
for link in pre
if link not in prev_categories
}
)
def _get_amazon_category_urls(
self,
section: str,
subs=True,
cache_urls=True,
print_progress=False,
cleanup_empty=True,
):
"""
Return a list containing Amazon category and sub-category(optional) urls, if previously cached, the files
will be read and required data will be returned, otherwise, required data will be scraped.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
subs: if subs, category and sub-category urls will be returned.
cache_urls: if cache_urls and content not previously cached, the content will be saved to .txt files.
print_progress: if True, progress will be displayed.
cleanup_empty: if True, if any empty files are left after the execution, will be deleted..
"""
starting_target_urls = {
"bs": (
"https://www.amazon.com/gp/bestsellers/",
"https://www.amazon.com/Best-Sellers",
),
"nr": (
"https://www.amazon.com/gp/new-releases/",
"https://www.amazon.com/gp/new-releases/",
),
"ms": (
"https://www.amazon.com/gp/movers-and-shakers/",
"https://www.amazon.com/gp/movers-and-shakers/",
),
"gi": (
"https://www.amazon.com/gp/most-gifted/",
"https://www.amazon.com/gp/most-gifted",
),
"mw": (
"https://www.amazon.com/gp/most-wished-for/",
"https://www.amazon.com/gp/most-wished-for/",
),
}
text_file_names = {
"bs": {
"categories": "bs_categories.txt",
"sub_categories": "bs_sub_categories.txt",
},
"nr": {
"categories": "nr_categories.txt",
"sub_categories": "nr_sub_categories.txt",
},
"ms": {
"categories": "ms_categories.txt",
"sub_categories": "ms_sub_categories.txt",
},
"gi": {
"categories": "gi_categories.txt",
"sub_categories": "gi_sub_categories.txt",
},
"mw": {
"categories": "mw_categories.txt",
"sub_categories": "mw_sub_categories.txt",
},
}
if self.website != "Amazon":
raise ValueError(
f"Cannot fetch Amazon data from {self.website}"
)
if section not in text_file_names:
raise ValueError(f"Invalid section {section}")
os.chdir(self.path)
if "Amazon" not in os.listdir(self.path):
os.mkdir("Amazon")
os.chdir("Amazon")
if "Amazon" in os.listdir(self.path):
categories = self._read_urls(
text_file_names,
section,
"categories",
self.path,
"Amazon",
cleanup_empty=cleanup_empty,
)
if not subs:
if cleanup_empty:
self._cleanup_empty_files(
self.path + "Amazon/"
)
return sorted(categories)
sub_categories = self._read_urls(
text_file_names,
section,
"sub_categories",
self.path,
"Amazon",
cleanup_empty=cleanup_empty,
)
try:
if categories and sub_categories:
if cleanup_empty:
self._cleanup_empty_files(
self.path + "Amazon/"
)
return (
sorted(categories),
sorted(sub_categories),
)
except UnboundLocalError:
pass
if not subs:
categories = self._scrape_urls(
starting_target_urls,
section,
"categories",
print_progress=print_progress,
)
if cache_urls:
self._cache_category_urls(
text_file_names,
section,
"categories",
"Amazon",
self.path,
categories,
print_progress=print_progress,
cleanup_empty=cleanup_empty,
)
if cleanup_empty:
self._cleanup_empty_files(
self.path + "Amazon/"
)
return sorted(categories)
if subs:
categories = self._scrape_urls(
starting_target_urls,
section,
"categories",
print_progress=print_progress,
)
if cache_urls:
self._cache_category_urls(
text_file_names,
section,
"categories",
"Amazon",
self.path,
categories,
print_progress=print_progress,
)
sub_categories = self._scrape_urls(
starting_target_urls,
section,
"sub_categories",
categories,
print_progress=print_progress,
)
if cache_urls:
self._cache_category_urls(
text_file_names,
section,
"sub_categories",
"Amazon",
self.path,
sub_categories,
print_progress=print_progress,
cleanup_empty=cleanup_empty,
)
if cleanup_empty:
self._cleanup_empty_files(
self.path + "Amazon/"
)
return (
sorted(categories),
sorted(sub_categories),
)
def _get_ebay_urls(
self, cache_urls=True, cleanup_empty=True
):
"""
Return a sorted list containing ebay category and sub-category URLs if previously cached, the files
will be read and required data will be returned, otherwise, required data will be scraped.
cache_urls: if cache_urls and content not previously cached, the content will be saved to .txt files.
cleanup_empty: if True, if any empty files are left after the execution, will be deleted.
"""
if self.website != "ebay":
raise ValueError(
f"Cannot fetch ebay data from {self.website}"
)
target_url = "https://www.ebay.com/b/"
if "ebay" not in os.listdir(self.path):
os.mkdir("ebay")
os.chdir("ebay")
if "ebay" in os.listdir(self.path):
os.chdir(self.path + "ebay/")
if "categories.txt" in os.listdir(
self.path + "ebay/"
):
with open("categories.txt") as cats:
categories = [
link.rstrip()
for link in cats.readlines()
]
if cleanup_empty:
self._cleanup_empty_files(
self.path + "ebay/"
)
return categories
initial_html = requests.get(
"https://www.ebay.com/n/all-categories",
self.headers,
)
initial_soup = BeautifulSoup(
initial_html.text, features="lxml"
)
categories = sorted(
{
str(link.get("href"))
for link in initial_soup.findAll("a")
if target_url in str(link)
}
)
if cache_urls:
with open("categories.txt", "w") as cats:
for category in categories:
cats.write(category + "\n")
if cleanup_empty:
self._cleanup_empty_files(self.path + "ebay/")
return categories
def _get_amazon_page_product_urls(
self, page_url: str, print_progress=False
):
"""
Return a sorted list of links to all products found on a single Amazon page.
page_url: a string containing target Amazon_url.
"""
prefix = "https://www.amazon.com"
page_response = requests.get(
page_url, headers=self.headers
)
page_soup = BeautifulSoup(
page_response.text, features="lxml"
)
if not print_progress:
return sorted(
{
prefix + str(link.get("href"))
for link in page_soup.findAll("a")
if "psc=" in str(link)
}
)
if print_progress:
links = set()
for link in page_soup.findAll("a"):
if "psc=" in str(link):
link_to_get = prefix + str(
link.get("href")
)
links.add(link_to_get)
print(f"Got link {link_to_get}")
return sorted(links)
@staticmethod
def _cleanup_empty_files(dir_path):
"""
Delete empty cached files in a given folder.
dir_path: a string containing path to target directory.
"""
try:
for file_name in os.listdir(dir_path):
if not os.path.isdir(dir_path + file_name):
if not open(file_name).read(1):
os.remove(file_name)
except UnicodeDecodeError:
pass
def _get_amazon_category_names_urls(
self,
section: str,
category_class: str,
print_progress=False,
cache_contents=True,
delimiter="&&&",
cleanup_empty=True,
):
"""
Return a list of pairs [category name, url] if previously cached, the files
will be read and required data will be returned, otherwise, required data will be scraped.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
print_progress: if True, progress will be displayed.
cache_contents: if data is not previously cached, category names mapped to their urls will be saved to .txt.
delimiter: delimits category name and the respective url in the .txt cached file.
cleanup_empty: if True, if any empty files are left after the execution, will be deleted.
"""
file_names = {
"categories": section + "_category_names.txt",
"sub_categories": section
+ "_sub_category_names.txt",
}
names_urls = []
os.chdir(self.path)
if "Amazon" in os.listdir(self.path):
os.chdir("Amazon")
file_name = file_names[category_class]
if file_name in os.listdir(
self.path + "Amazon"
):
with open(file_name) as names:
if cleanup_empty:
self._cleanup_empty_files(
self.path + "Amazon/"
)
return [
line.rstrip().split(delimiter)
for line in names.readlines()
]
if "Amazon" not in os.listdir(self.path):
os.mkdir("Amazon")
os.chdir("Amazon")
categories, sub_categories = self._get_amazon_category_urls(
section,
cache_urls=cache_contents,
print_progress=print_progress,
cleanup_empty=cleanup_empty,
)
for category in eval("eval(category_class)"):
category_response = requests.get(
category, headers=self.headers
)
category_html = BeautifulSoup(
category_response.text, features="lxml"
)
try:
category_name = category_html.h1.span.text
names_urls.append((category_name, category))
if cache_contents:
with open(
file_names[category_class], "w"
) as names:
names.write(
category_name
+ delimiter
+ category
+ "\n"
)
if print_progress:
if open(
file_names[category_class], "r"
).read(1):
print(
f"{section}-{category_class[:-3]}y: {category_name} ... done."
)
else:
print(
f"{section}-{category_class[:-3]}y: {category_name} ... failure."
)
except AttributeError:
pass
if cleanup_empty:
self._cleanup_empty_files(self.path + "Amazon/")
return names_urls
def _get_amazon_section_product_urls(
self,
section: str,
category_class: str,
print_progress=False,
cache_contents=True,
cleanup_empty=True,
read_only=False,
):
"""
Return links to all products within all categories available in an Amazon section(check self.amazon_modes).
section: a string indicating section to scrape. If previously cached, the files
will be read and required data will be returned, otherwise, required data will be scraped..
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
print_progress: if True, progress will be displayed.
cache_contents: if data is not previously cached, category names mapped to their urls will be saved to .txt.
cleanup_empty: if True, if any empty files are left after the execution, will be deleted.
read_only: if files are previously cached and only cached contents are required(no scraping attempts in case of
missing category/sub-category urls).
"""
all_products = []
names_urls = self._get_amazon_category_names_urls(
section,
category_class,
print_progress,
cache_contents,
cleanup_empty=cleanup_empty,
)
folder_name = " ".join(
[
self.amazon_modes[section],
category_class.title(),
"Product URLs",
]
)
if cache_contents:
if folder_name not in os.listdir(
self.path + "Amazon/"
):
os.mkdir(folder_name)
os.chdir(folder_name)
for category_name, category_url in names_urls:
if print_progress:
print(
f"Processing category {category_name} ..."
)
file_name = "-".join(
[
self.amazon_modes[section],
category_class,
category_name,
]
)
if file_name + ".txt" in os.listdir(
self.path + "Amazon/" + folder_name + "/"
):
with open(
file_name + ".txt"
) as product_urls:
urls = [
line.rstrip()
for line in product_urls.readlines()
]
all_products.append(
(category_name, urls)
)
else:
if not read_only:
urls = self._get_amazon_page_product_urls(
category_url, print_progress
)
all_products.append(
(category_name, urls)
)
if cache_contents:
with open(
file_name + ".txt", "w"
) as current:
for url in urls:
current.write(url + "\n")
if print_progress:
print(f"Saving {url}")
if print_progress:
try:
if open(file_name + ".txt").read(1):
print(
f"Category {category_name} ... done."
)
else:
print(
f"Category {category_name} ... failure."
)
except FileNotFoundError:
if print_progress:
print(
f"Category {category_name} ... failure."
)
pass
if cleanup_empty:
self._cleanup_empty_files(
self.path + "Amazon/" + folder_name
)
return all_products
if __name__ == "__main__":
start_time = perf_counter()
path_to_folder = input(
"Enter path for content saving: "
).rstrip()
abc = WebScraper("Amazon", path=path_to_folder)
print(
abc._get_amazon_section_product_urls(
"bs", "categories", print_progress=True
)
)
end_time = perf_counter()
print(f"Time: {end_time - start_time} seconds.")
</code></pre>
<p><strong>If you prefer the non-formatted version:</strong></p>
<pre><code>#!/usr/bin/env python3
from bs4 import BeautifulSoup
from time import perf_counter
import os
import requests
class WebScraper:
"""
A tool for scraping websites including:
- Amazon
- eBay
"""
def __init__(self, website: str, target_url=None, path=None):
"""
website: A string indication of a website:
- 'ebay'
- 'Amazon'
target_url: A string containing a single url to scrape.
"""
self.supported_websites = ['Amazon', 'ebay']
if website not in self.supported_websites:
raise ValueError(f'Website {website} not supported.')
self.website = website
self.target_url = target_url
if not path:
self.path = '/Users/user_name/Desktop/web scraper/'
if path:
self.path = path
self.headers = {'User-Agent': 'Safari/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'}
self.amazon_modes = {'bs': 'Best Sellers', 'nr': 'New Releases', 'gi': 'Gift Ideas',
'ms': 'Movers and Shakers', 'mw': 'Most Wished For'}
def _cache_category_urls(self, text_file_names: dict, section: str, category_class: str, website: str,
content_path: str, categories: list, print_progress=False, cleanup_empty=True):
"""
Write scraped category/sub_category urls to file.
text_file_names: a dictionary containing .txt file names to save data under.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
website: a string 'ebay' or 'Amazon'.
content_path: a string containing path to folder for saving URLs.
categories: a list containing category or sub_category urls to be saved.
print_progress: if True, progress will be displayed.
cleanup_empty: if True, after writing the .txt files, empty files(failures) will be deleted.
"""
os.chdir(content_path + website + '/')
with open(text_file_names[section][category_class], 'w') as cats:
for category in categories:
cats.write(category + '\n')
if print_progress:
if open(text_file_names[section][category_class], 'r').read(1):
print(f'Saving {category} ... done.')
else:
print(f'Saving {category} ... failure.')
if cleanup_empty:
self._cleanup_empty_files(self.path + website + '/')
def _read_urls(self, text_file_names: dict, section: str, category_class: str, content_path: str, website: str,
cleanup_empty=True):
"""
Read saved urls from a file and return a sorted list containing the urls.
text_file_names: a dictionary containing .txt file names to save data under.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
website: a string 'ebay' or 'Amazon'.
content_path: a string containing path to folder for saving URLs.
print_progress: if True, progress will be displayed.
cleanup_empty: if True, if any empty files found during the execution, the files will be deleted.
"""
os.chdir(content_path + website + '/')
if text_file_names[section][category_class] in os.listdir(content_path + 'Amazon/'):
with open(text_file_names[section][category_class]) as cats:
if cleanup_empty:
self._cleanup_empty_files(self.path + website + '/')
return [link.rstrip() for link in cats.readlines()]
def _scrape_urls(self, starting_target_urls: dict, section: str, category_class: str, prev_categories=None,
print_progress=False):
"""
Scrape urls of a category class and return a list of URLs.
starting_target_urls: a dictionary containing the initial websites that will start the web crawling.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
prev_categories: if sub_categories are scraped, prev_categories a list of category urls.
print_progress: if True, progress will be displayed.
"""
target_url = starting_target_urls[section][1]
if category_class == 'categories':
starting_url = requests.get(starting_target_urls[section][0], headers=self.headers)
html_content = BeautifulSoup(starting_url.text, features='lxml')
target_url_part = starting_target_urls[section][1]
if not print_progress:
return sorted({str(link.get('href')) for link in html_content.findAll('a')
if target_url_part in str(link)})
if print_progress:
categories = set()
for link in html_content.findAll('a'):
if target_url_part in str(link):
link_to_add = str(link.get('href'))
categories.add(link_to_add)
print(f'Fetched {section}-{category_class}: {link_to_add}')
return categories
if category_class == 'sub_categories':
if not print_progress:
responses = [requests.get(category, headers=self.headers) for category in prev_categories]
category_soups = [BeautifulSoup(response.text, features='lxml') for response in responses]
pre_sub_category_links = [str(link.get('href')) for category in category_soups
for link in category.findAll('a') if target_url in str(link)]
return sorted({link for link in pre_sub_category_links if link not in prev_categories})
if print_progress:
responses, pre, sub_categories = [], [], set()
for category in prev_categories:
response = requests.get(category, headers=self.headers)
responses.append(response)
print(f'Got response {response} for {section}-{category}')
category_soups = [BeautifulSoup(response.text, features='lxml') for response in responses]
for soup in category_soups:
for link in soup.findAll('a'):
if target_url in str(link):
fetched_link = str(link.get('href'))
pre.append(fetched_link)
print(f'Fetched {section}-{fetched_link}')
return sorted({link for link in pre if link not in prev_categories})
def _get_amazon_category_urls(self, section: str, subs=True, cache_urls=True, print_progress=False,
cleanup_empty=True):
"""
Return a list containing Amazon category and sub-category(optional) urls, if previously cached, the files
will be read and required data will be returned, otherwise, required data will be scraped.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
subs: if subs, category and sub-category urls will be returned.
cache_urls: if cache_urls and content not previously cached, the content will be saved to .txt files.
print_progress: if True, progress will be displayed.
cleanup_empty: if True, if any empty files are left after the execution, will be deleted..
"""
starting_target_urls = {'bs': ('https://www.amazon.com/gp/bestsellers/',
'https://www.amazon.com/Best-Sellers'),
'nr': ('https://www.amazon.com/gp/new-releases/',
'https://www.amazon.com/gp/new-releases/'),
'ms': ('https://www.amazon.com/gp/movers-and-shakers/',
'https://www.amazon.com/gp/movers-and-shakers/'),
'gi': ('https://www.amazon.com/gp/most-gifted/',
'https://www.amazon.com/gp/most-gifted'),
'mw': ('https://www.amazon.com/gp/most-wished-for/',
'https://www.amazon.com/gp/most-wished-for/')}
text_file_names = {'bs': {'categories': 'bs_categories.txt', 'sub_categories': 'bs_sub_categories.txt'},
'nr': {'categories': 'nr_categories.txt', 'sub_categories': 'nr_sub_categories.txt'},
'ms': {'categories': 'ms_categories.txt', 'sub_categories': 'ms_sub_categories.txt'},
'gi': {'categories': 'gi_categories.txt', 'sub_categories': 'gi_sub_categories.txt'},
'mw': {'categories': 'mw_categories.txt', 'sub_categories': 'mw_sub_categories.txt'}}
if self.website != 'Amazon':
raise ValueError(f'Cannot fetch Amazon data from {self.website}')
if section not in text_file_names:
raise ValueError(f'Invalid section {section}')
os.chdir(self.path)
if 'Amazon' not in os.listdir(self.path):
os.mkdir('Amazon')
os.chdir('Amazon')
if 'Amazon' in os.listdir(self.path):
categories = self._read_urls(text_file_names, section, 'categories', self.path, 'Amazon',
cleanup_empty=cleanup_empty)
if not subs:
if cleanup_empty:
self._cleanup_empty_files(self.path + 'Amazon/')
return sorted(categories)
sub_categories = self._read_urls(text_file_names, section, 'sub_categories', self.path, 'Amazon',
cleanup_empty=cleanup_empty)
try:
if categories and sub_categories:
if cleanup_empty:
self._cleanup_empty_files(self.path + 'Amazon/')
return sorted(categories), sorted(sub_categories)
except UnboundLocalError:
pass
if not subs:
categories = self._scrape_urls(starting_target_urls, section, 'categories', print_progress=print_progress)
if cache_urls:
self._cache_category_urls(text_file_names, section, 'categories', 'Amazon', self.path, categories,
print_progress=print_progress, cleanup_empty=cleanup_empty)
if cleanup_empty:
self._cleanup_empty_files(self.path + 'Amazon/')
return sorted(categories)
if subs:
categories = self._scrape_urls(starting_target_urls, section, 'categories', print_progress=print_progress)
if cache_urls:
self._cache_category_urls(text_file_names, section, 'categories', 'Amazon', self.path, categories,
print_progress=print_progress)
sub_categories = self._scrape_urls(starting_target_urls, section, 'sub_categories', categories,
print_progress=print_progress)
if cache_urls:
self._cache_category_urls(text_file_names, section, 'sub_categories', 'Amazon', self.path,
sub_categories, print_progress=print_progress, cleanup_empty=cleanup_empty)
if cleanup_empty:
self._cleanup_empty_files(self.path + 'Amazon/')
return sorted(categories), sorted(sub_categories)
def _get_ebay_urls(self, cache_urls=True, cleanup_empty=True):
"""
Return a sorted list containing ebay category and sub-category URLs if previously cached, the files
will be read and required data will be returned, otherwise, required data will be scraped.
cache_urls: if cache_urls and content not previously cached, the content will be saved to .txt files.
cleanup_empty: if True, if any empty files are left after the execution, will be deleted.
"""
if self.website != 'ebay':
raise ValueError(f'Cannot fetch ebay data from {self.website}')
target_url = 'https://www.ebay.com/b/'
if 'ebay' not in os.listdir(self.path):
os.mkdir('ebay')
os.chdir('ebay')
if 'ebay' in os.listdir(self.path):
os.chdir(self.path + 'ebay/')
if 'categories.txt' in os.listdir(self.path + 'ebay/'):
with open('categories.txt') as cats:
categories = [link.rstrip() for link in cats.readlines()]
if cleanup_empty:
self._cleanup_empty_files(self.path + 'ebay/')
return categories
initial_html = requests.get('https://www.ebay.com/n/all-categories', self.headers)
initial_soup = BeautifulSoup(initial_html.text, features='lxml')
categories = sorted({str(link.get('href')) for link in initial_soup.findAll('a') if target_url in str(link)})
if cache_urls:
with open('categories.txt', 'w') as cats:
for category in categories:
cats.write(category + '\n')
if cleanup_empty:
self._cleanup_empty_files(self.path + 'ebay/')
return categories
def _get_amazon_page_product_urls(self, page_url: str, print_progress=False):
"""
Return a sorted list of links to all products found on a single Amazon page.
page_url: a string containing target Amazon_url.
"""
prefix = 'https://www.amazon.com'
page_response = requests.get(page_url, headers=self.headers)
page_soup = BeautifulSoup(page_response.text, features='lxml')
if not print_progress:
return sorted({prefix + str(link.get('href')) for link in page_soup.findAll('a') if 'psc=' in str(link)})
if print_progress:
links = set()
for link in page_soup.findAll('a'):
if 'psc=' in str(link):
link_to_get = prefix + str(link.get('href'))
links.add(link_to_get)
print(f'Got link {link_to_get}')
return sorted(links)
@staticmethod
def _cleanup_empty_files(dir_path):
"""
Delete empty cached files in a given folder.
dir_path: a string containing path to target directory.
"""
try:
for file_name in os.listdir(dir_path):
if not os.path.isdir(dir_path + file_name):
if not open(file_name).read(1):
os.remove(file_name)
except UnicodeDecodeError:
pass
def _get_amazon_category_names_urls(self, section: str, category_class: str, print_progress=False,
cache_contents=True, delimiter='&&&', cleanup_empty=True):
"""
Return a list of pairs [category name, url] if previously cached, the files
will be read and required data will be returned, otherwise, required data will be scraped.
section: a string indicating section to scrape.
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
print_progress: if True, progress will be displayed.
cache_contents: if data is not previously cached, category names mapped to their urls will be saved to .txt.
delimiter: delimits category name and the respective url in the .txt cached file.
cleanup_empty: if True, if any empty files are left after the execution, will be deleted.
"""
file_names = {'categories': section + '_category_names.txt',
'sub_categories': section + '_sub_category_names.txt'}
names_urls = []
os.chdir(self.path)
if 'Amazon' in os.listdir(self.path):
os.chdir('Amazon')
file_name = file_names[category_class]
if file_name in os.listdir(self.path + 'Amazon'):
with open(file_name) as names:
if cleanup_empty:
self._cleanup_empty_files(self.path + 'Amazon/')
return [line.rstrip().split(delimiter) for line in names.readlines()]
if 'Amazon' not in os.listdir(self.path):
os.mkdir('Amazon')
os.chdir('Amazon')
categories, sub_categories = self._get_amazon_category_urls(section, cache_urls=cache_contents,
print_progress=print_progress,
cleanup_empty=cleanup_empty)
for category in eval('eval(category_class)'):
category_response = requests.get(category, headers=self.headers)
category_html = BeautifulSoup(category_response.text, features='lxml')
try:
category_name = category_html.h1.span.text
names_urls.append((category_name, category))
if cache_contents:
with open(file_names[category_class], 'w') as names:
names.write(category_name + delimiter + category + '\n')
if print_progress:
if open(file_names[category_class], 'r').read(1):
print(f'{section}-{category_class[:-3]}y: {category_name} ... done.')
else:
print(f'{section}-{category_class[:-3]}y: {category_name} ... failure.')
except AttributeError:
pass
if cleanup_empty:
self._cleanup_empty_files(self.path + 'Amazon/')
return names_urls
def _get_amazon_section_product_urls(self, section: str, category_class: str, print_progress=False,
cache_contents=True, cleanup_empty=True, read_only=False):
"""
Return links to all products within all categories available in an Amazon section(check self.amazon_modes).
section: a string indicating section to scrape. If previously cached, the files
will be read and required data will be returned, otherwise, required data will be scraped..
For Amazon:
check self.amazon_modes.
category_class: a string 'categories' or 'sub_categories'.
print_progress: if True, progress will be displayed.
cache_contents: if data is not previously cached, category names mapped to their urls will be saved to .txt.
cleanup_empty: if True, if any empty files are left after the execution, will be deleted.
read_only: if files are previously cached and only cached contents are required(no scraping attempts in case of
missing category/sub-category urls).
"""
all_products = []
names_urls = self._get_amazon_category_names_urls(section, category_class, print_progress, cache_contents,
cleanup_empty=cleanup_empty)
folder_name = ' '.join([self.amazon_modes[section], category_class.title(),
'Product URLs'])
if cache_contents:
if folder_name not in os.listdir(self.path + 'Amazon/'):
os.mkdir(folder_name)
os.chdir(folder_name)
for category_name, category_url in names_urls:
if print_progress:
print(f'Processing category {category_name} ...')
file_name = '-'.join([self.amazon_modes[section], category_class, category_name])
if file_name + '.txt' in os.listdir(self.path + 'Amazon/' + folder_name + '/'):
with open(file_name + '.txt') as product_urls:
urls = [line.rstrip() for line in product_urls.readlines()]
all_products.append((category_name, urls))
else:
if not read_only:
urls = self._get_amazon_page_product_urls(category_url, print_progress)
all_products.append((category_name, urls))
if cache_contents:
with open(file_name + '.txt', 'w') as current:
for url in urls:
current.write(url + '\n')
if print_progress:
print(f'Saving {url}')
if print_progress:
try:
if open(file_name + '.txt').read(1):
print(f'Category {category_name} ... done.')
else:
print(f'Category {category_name} ... failure.')
except FileNotFoundError:
if print_progress:
print(f'Category {category_name} ... failure.')
pass
if cleanup_empty:
self._cleanup_empty_files(self.path + 'Amazon/' + folder_name)
return all_products
if __name__ == '__main__':
start_time = perf_counter()
path_to_folder = input('Enter path for content saving: ').rstrip()
abc = WebScraper('Amazon', path=path_to_folder)
print(abc._get_amazon_section_product_urls('bs', 'categories', print_progress=True))
end_time = perf_counter()
print(f'Time: {end_time - start_time} seconds.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T12:55:02.603",
"Id": "449891",
"Score": "0",
"body": "Is there anyone interested in reviewing this? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:06:43.707",
"Id": "449929",
"Score": "2",
"body": "There’s a lot of code. Be patient "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:22:50.253",
"Id": "449932",
"Score": "0",
"body": "@GrajdeanuAlex. yeah I'm sorry for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T07:05:58.680",
"Id": "450096",
"Score": "0",
"body": "I'm interested in reviewing that, I've had a quick look already, but I haven't had time to go further yet ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T10:38:37.867",
"Id": "450113",
"Score": "0",
"body": "@Cyril D people around here lose interest quickly over long codes"
}
] |
[
{
"body": "<p>As it's a large chunck of code for this format, I'm sitcking to reviewing <code>_get_amazon_section_product_urls</code>\nbut what I mention here can be applied elsewhere. If you choose to reply with an updated version, I could then\nlook at the remaining.</p>\n\n<h1>Code Style</h1>\n\n<p>Overall, there is a good job of trying to make the code readable, and I give you bonus points for using type hinting.\nHowever, a docstring start on the same line as the brackets, with a short sentence explaining the function, then\na blank line, then a paragraph (then I put args and return. I like numpy's style):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Clear enough, no need for a docstring:\ndef randint():\n return 4 # Chosen by fair dice roll\n\n# A single line is sufficiently explanatory:\ndef _cleanup_empty_files(dir_path):\n \"\"\"Delete empty cached files in a given folder.\n\n dir_path: a string containing path to target directory.\n \"\"\"\n</code></pre>\n\n<p>Moreover, if you use type hinting, I think it's okay to omit the type specification in the docstring:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def _get_amazon_category_names_urls(self, section: str, category_class: str, print_progress=False,\n cache_contents=True, delimiter='&&&', cleanup_empty=True):\n \"\"\"Get a list of pairs [category name, url] \n\n If previously cached, the files will be read and required data will be returned, otherwise, \n required data will be scraped.\n\n section: specify section to scrape.\n Check `self.amazon_modes` when `amazon` is specified.\n category_class: 'categories' or 'sub_categories'.\n print_progress: if True, progress will be displayed.\n cache_contents: if data is not previously cached, category names mapped to their urls will be saved to .txt.\n delimiter: delimits category name and the respective url in the .txt cached file.\n cleanup_empty: if True, delete any empty files left once done.\n \"\"\"\n</code></pre>\n\n<p>I also find that the class' docstring is not so helpful. I gather it was written when getting started, but should be revisited.\nIt does not help to know what's being scrapped, why, and whether it's scraping search results, or the latest offers, or their css, or...</p>\n\n<p>I'm explicitly not talking about line length, as the official recommendation is 80, I've worked with codebase going to a 100, and here \nthe length seems to go up to 120. Is that what you want? Ok.</p>\n\n<h1>The mixing of functionalities</h1>\n\n<p>I find worriesome that certain actions are mixed up:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if print_progress:\n try:\n if open(file_name + '.txt').read(1): # This file is never closed!\n print(f'Category {category_name} ... done.')\n else:\n print(f'Category {category_name} ... failure.')\n except FileNotFoundError:\n if print_progress:\n print(f'Category {category_name} ... failure.')\n pass # Why is there a pass?\n</code></pre>\n\n<p>Opening the file is a different action from printing. I'd do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>msg = 'failure' # Assume the worst in the default state\ntry:\n with open(f'{file_name}.txt') as fin:\n if fin.read(1):\n msg = 'done'\nexcept FileNotFoundError:\n pass\nif print_progress:\n print(f'Category {category_name}: {msg}.')\n</code></pre>\n\n<p>Perhaps, instead of printing, you could look into <a href=\"https://docs.python.org/3.5/library/logging.html\" rel=\"nofollow noreferrer\">logging</a>. You could then set the\nlogging level, avoid these ifs all over the place, and the <code>print_progress</code> argument become irrelevant.</p>\n\n<p>Now that these two operations are decoupled, we can think of integrating the logging with the operation, and remove this test, as\nwhat it effectively does it check that the user had the rights to modify this file, where an error would have been thrown earlier.\nThere also a code-path which is not tested: what happens if the files have never been cached, and <code>use_cached_content</code> is <code>False</code>?\nThen the test returns false, even though function returns an empty list (a I think it should?)</p>\n\n<p>The following block is prone to errors:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if cache_contents:\n if folder_name not in os.listdir(self.path + 'Amazon/'):\n os.mkdir(folder_name)\nos.chdir(folder_name)\n</code></pre>\n\n<p>This is because the path we're really working with is <code>os.path.join(self.path, 'Amazon', folder_name)</code>, but then we're changing directory\nto <code>folder_name only</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>path = os.path.join(self.path, 'Amazon', folder_name)\nif cache_content:\n if not os.path.exists(path):\n os.mkdirs(path)\nos.chdir(path)\n</code></pre>\n\n<p>I myself am not keen on changing paths all the time, because I find it hard to keep track of where I am.\nThat's why I'd rather build the full path, create directories and work from where I am:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>with open(os.path.join(path, filename)):\n ...\n</code></pre>\n\n<h1>Naming</h1>\n\n<p>I'm more of a linux guy, and I'm uncomfortable with whitespaces in directory names, as found in <code>_get_amazon_category_names_urls</code>.\nI think that <code>read_only</code> is not as telling as <code>cached_only</code> or <code>use_cache</code> or <code>use_cached_content</code>.\nThe operation <code>file_name + '.txt'</code> is done is several places. The extention is effectively part of the filename, consider concatenating\nit once.</p>\n\n<h1>Aerate the code</h1>\n\n<p>Since it's a relatively large function, which has several operations and code-paths, I would add blank lines to separate the various\nblocks in to logical units.</p>\n\n<h1>With all this, that function looks like that:</h1>\n\n<pre class=\"lang-py prettyprint-override\"><code> def _get_amazon_section_product_urls(self, section: str, category_class: str, cache_contents=True,\n cleanup_empty=True, read_only=False):\n \"\"\"Get links to all products within all categories available in an Amazon section (as defined in\n self.amazon_modes).\n\n section: the amazon category to scrape. If previously cached, the files will be read and required\n data will be returned, otherwise, required data will be scraped.\n category_class: 'categories' or 'sub_categories'.\n cache_content: if the data was not previously cached, category names mapped to their urls will \n be saved to a text file.\n cleanup_empty: if True, delete any empty files left once done.\n use_cached_content: only use previously cached contents. (no scraping \n attempts in case of missing category/sub-category urls). Returns an empty list if not cache exists.\n \"\"\"\n all_products = []\n names_urls = self._get_amazon_category_names_urls(section, category_class, print_progress, \n cache_contents, cleanup_empty=cleanup_empty)\n\n path = ' '.join([self.amazon_modes[section], category_class.title(), 'Product URLs'])\n\n if cache_content:\n if not os.path.exists(path):\n os.mkdir(path)\n\n for category_name, category_url in names_urls:\n logger.info(f'Processing category {category_name} ...')\n msg = 'done'\n\n filename = '-'.join([self.amazon_modes[section], category_class, category_name])\n filename += '.txt'\n filepath = os.path.join(path, filename) \n\n if use_cached_content:\n try:\n with open(filepath) as fin:\n urls = [line.rstrip() for line in fin.readlines()]\n all_products.append((category_name, urls))\n except UnsupportedOperation as e:\n msg = f'failed: cannot read file ({e})'\n else:\n urls = self._get_amazon_page_product_urls(category_url, print_progress)\n all_products.append((category_name, urls))\n if cache_contents:\n with open(filepath, 'w') as fout:\n try:\n for url in urls:\n fout.write(url + '\\n')\n logger.debug(f'Saved {url}')\n except PermissionError as e:\n msg = f'failed: cannot write file ({e})'\n\n logger.info(f'Category {category_name}: {msg}.')\n\n if cleanup_empty:\n self._cleanup_empty_files(path)\n return all_products\n</code></pre>\n\n<p>Now, here, the errors are silenced, and the function returns an empty list. However, perhaps in the scheme of your software, it would\nmake sense to bubble the errors up the chain and handle the errors more appropriately? Here, an empty list is returned, is that the\ndesired failure mode up the chain?</p>\n\n<p>As a bonus, I'm now toying with Visual Studio Code, and it has this neat functionality of showing me text that I highlight everywhere \nwhere it happens. It's a way to notice where you are <a href=\"https://en.wikipedia.org/wiki/Don't_repeat_yourself\" rel=\"nofollow noreferrer\">repeating yourself</a>:\n<a href=\"https://i.stack.imgur.com/1YeVu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1YeVu.png\" alt=\"Visual Code Studio showing highlighted repeated code\"></a></p>\n\n<p>There's a lot more to review, I think it's a good start though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T22:32:36.403",
"Id": "450519",
"Score": "0",
"body": "Thank you for this, I'm almost done with another version of the code that's entirely different and I added a multi-threading functionality, I'll comment with the link here when I'm done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T01:31:05.953",
"Id": "450531",
"Score": "0",
"body": "The new version: https://codereview.stackexchange.com/questions/231126/amazon-scraper-multi-threaded"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-22T02:22:02.053",
"Id": "450534",
"Score": "0",
"body": "I need you to suggest ways to eliminate failures that are randomly occasional on certain sections not including best sellers and most wished for in the new code version above and I'll take take into consideration both feedbacks in my next follow up."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T09:58:51.213",
"Id": "231089",
"ParentId": "230796",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "231089",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T02:51:29.110",
"Id": "230796",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup"
],
"Title": "Web scraper that extracts urls from Amazon and eBay"
}
|
230796
|
<p>Writing a code to return the last 3 items in a list, if the list has 3 or more elements, otherwise return all list items.</p>
<p>But the code looks really bad.
What is a better way to write the same code?</p>
<pre><code> public void test_arrayListItems() {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("item1");
arrayList.add("item2");
arrayList.add("item3");
arrayList.add("item4");
arrayList.add("item5");
arrayList.add("item6");
arrayList.add("item7");
arrayList.add("item8");
String items = "";
int j = 0;
int k = 0;
if (arrayList.size() <= 2) {
j = arrayList.size() - 1;
} else if (arrayList.size() > 2) {
j = arrayList.size() - 1;
k = arrayList.size() - 3;
}
for (int i = k; i <= j; i++) {
items = items + "- " + arrayList.get(i) + " ";
}
logger.info(items);
}
</code></pre>
<p>thanks</p>
|
[] |
[
{
"body": "<ol>\n<li>Is a best practice to define a variable as type of the interface the instance implement it(see OOP principles)</li>\n<li>Just a little bit out of scope, you can declare your arrayList inline, like in the example I wrote.</li>\n<li>Try to use available features of List(in this example) like subList rather than cycle(what if you have thousands of elements?)</li>\n<li>toString on a list will return a string with those list, you don't have to concatenate them</li>\n<li>it is a bad practice to concatenate strings in cycles because create new strings every time you add + \" \"</li>\n</ol>\n\n<p>See an alternative solution below:</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class MainTest {\n public static void main(String[] args) {\n final int wantedSize = 3;\n final List<String> arrayList = new ArrayList<>(Arrays.asList(\"item1\", \"item2\", \"item3\", \"item4\"));\n final int listSize = arrayList.size();\n final List<String> result = (listSize >= wantedSize) ? arrayList.subList(listSize-wantedSize, listSize): arrayList;\n System.out.println(result.toString());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T15:17:29.360",
"Id": "449922",
"Score": "0",
"body": "thank you so much, I wasn't able to up vote because of my low reputation, great points made"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T07:16:55.903",
"Id": "230807",
"ParentId": "230803",
"Score": "5"
}
},
{
"body": "<p>The problem is a succession of two tasks : first you have the identify the initial index of the loop and iterate over the elements of your list distinguishing between a list having less than 3 elements or plus than 3 elements. For this purpose you can use a ternary operator and implement your loop like the code below:</p>\n\n<pre><code>List<String> arrayList; //previously defined in your code\nint size = arrayList.size();\nint k = size >= 3 ? size - 3 : 0;\nfor (int i = k; i < size; ++i) {\n //body defined later in my answer \n}\n</code></pre>\n\n<p>The second task is about logging elements of your list separated by the string <code>\" - \"</code>, for this task you can use the class <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html\" rel=\"nofollow noreferrer\">StringJoiner</a> in the body of your loop like the code below:</p>\n\n<pre><code>int size = arrayList.size();\nint k = size >= 3 ? size - 3 : 0;\nStringJoiner sj = new StringJoiner(\" - \");\nfor (int i = k; i < size; ++i) {\n sj.add(arrayList.get(i));\n}\nString items = sj.toString();\nlogger.info(items);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T15:18:15.770",
"Id": "449923",
"Score": "0",
"body": "First time seeing StringJoiner in action, thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:43:56.667",
"Id": "230818",
"ParentId": "230803",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230818",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T06:19:43.167",
"Id": "230803",
"Score": "2",
"Tags": [
"java",
"iteration"
],
"Title": "Listing last 3 items (or all if less than 3) in an ArrayList"
}
|
230803
|
<p>I wrote this program to print how many times each number occurs in a list:</p>
<pre><code>class deleteduplicate:
def __init__(self):
a=[]
num=int(input("Enter the number of elements"))
for i in range(0,num):
try:
a.append(int(input("Enter the number {}".format(i))))
except ValueError:
print ("Wrong Input")
i=i-1
flagarray=[]
countarray=[]
j=0;
for c in a:
flagarray.append(False)
countarray.append(1)
for c in a:
count=1
flag=False
ca=[]
for i in range(j,len(a)):
if a[i] == c and flagarray[i]==False:
flag=True
count=count+1
flagarray[i]=True
ca.append(i)
if len(ca)>0:
print(str(c)+"ocuurs"+str(len(ca))+"times")
j=j+1
deleteduplicate()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T07:29:46.830",
"Id": "449834",
"Score": "3",
"body": "Welcome to CodeReview. It looks like you are new to python. Feel free to read [ask] if you would like to know more about asking questions. A general Python resource that many here use is [PEP-8](https://www.python.org/dev/peps/pep-0008/)."
}
] |
[
{
"body": "<p>First off, this really shouldn't be a class, but a function. </p>\n\n<p>You should have a look at <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, which is the closest thing to a Python style guide. </p>\n\n<p>For clarity, you should also split it up so that you have the processing separate from the input (and it's validation.) The general structure of your program might look a bit like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def delete_duplicates(mylist):\n # Do stuff\n\ndef get_input():\n # Do stuff\n\nif __name__ == \"__main__\":\n delete_duplicates(get_input())\n</code></pre>\n\n<p>We call that last bit a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do/419185#419185\">guard</a> - it basically ensures that the script only executes when it is run as a script, but not when we import this into another script.</p>\n\n<p>Since it looks to me like it's about the process of removing duplicates from a list and not about the input here, I'll skip the input bits for now. </p>\n\n<p>From what your code looks to output, you seem to be counting the amount of times something occurs in a list. Python has builtin tools for that, like the <code>count()</code> method. It works like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>num_occur = mylist.count(2) # Counts how often the int 2 is in mylist.\n</code></pre>\n\n<p>What you don't seem to do is actually remove the duplicates from that list, while your class name does claim to do so. You could of course use <code>list.remove(elem)</code> to remove a single occurrence of <code>elem</code> from your list. Another way to do this may be:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>new_list = list(set(old_list))\n</code></pre>\n\n<p>This removes all duplicates by transforming your list into a set, and then back in a list. Sets cannot have duplicates, so this technique removes them all. However, if the order is preserved you can count it as a happy accident. While it'll be common if you do it with a list like <code>[1, 2, 3]</code>, when things get more complex they tend to get shuffled.</p>\n\n<p>You also seem to have a habit of calling lists arrays. They're really not, even if they look and sometimes seem to act like them on the surface. Arrays tend to be much lower level structures than lists, and it may be useful to <a href=\"https://docs.python.org/3.7/tutorial/datastructures.html\" rel=\"nofollow noreferrer\">read up more on python lists.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:57:20.943",
"Id": "449850",
"Score": "0",
"body": "Thanks Gloweye for your review"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:02:15.873",
"Id": "449853",
"Score": "0",
"body": "@gokul please upvote answers you found helpful using the (^ sign on the left)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:10:11.000",
"Id": "449857",
"Score": "0",
"body": "@AlexV yeah, I forgot about that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T11:55:43.217",
"Id": "449872",
"Score": "0",
"body": "@AlexV They do now :-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:02:00.653",
"Id": "230808",
"ParentId": "230806",
"Score": "3"
}
},
{
"body": "<p>Welcome to code review.</p>\n<h1>Style</h1>\n<p>Check <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP0008</a> the official Python style guide for maintaining code within Python acceptable standards.</p>\n<ul>\n<li><strong>Class names:</strong> Apart from the fact that this is a bad use of classes, class names should be <code>UpperCaseCamelCase</code> which implies that since this\n<code>delete_duplicates</code> is a class, then the name should be <code>DeleteDuplicates</code>.</li>\n<li><strong>Method/function/variable names:</strong> should be lowercase and words separated by underscores ex: <code>flagarray=[]</code> is <code>flag_array = []</code></li>\n<li><strong>Space around operators:</strong> a space should be left on both sides of a binary operator: <code>a=[]</code> is <code>a = []</code> and <code>flagarray=[]</code> is <code>flag_array = []</code></li>\n<li><strong>Descriptive variable names:</strong> names should reflect the objects they represent and not names like <code>j</code>, <code>c</code>, <code>i</code> which are confusing because <code>j</code> could be a variable, a string, a number ...</li>\n<li><strong>f-strings:</strong> (Python 3.6 +) are better used for combining strings and variables in a single statement. ex: <code>print(str(c)+"ocuurs"+str(len(ca))+"times")</code> can be <code>print(f'{c!s} occurs {len(ca)} times')</code></li>\n</ul>\n<h1>Code</h1>\n<ul>\n<li><strong>Functions:</strong> A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. Since this a bad use of classes because a class is usually used for an object with multi-attributes and multi-methods and this is not the case here, you might use a regular function.</li>\n<li><strong>Augmented assignment:</strong> Python supports augmented assignments ex: <code>i=i-1</code> is <code>i -= 1</code>, <code>count=count+1</code> is <code>count += 1</code> ...</li>\n<li><strong>Semicolons:</strong> are for combining multiple short statements on the same line, this <code>j=0;</code> (line 15) is an invalid use of semicolons.</li>\n<li><strong>Comparison to True and False:</strong> is usually done using <code>if something:</code> and <code>if not something_else:</code> ex: <code>flagarray[i]==False:</code> is <code>if not flag_array[i]:</code>. Non-empty sequences and non-zero variables evaluate to <code>True</code> ex: <code>if len(ca)>0:</code> is <code>if ca:</code></li>\n<li><strong>Inefficiency:</strong> If you need to print duplicates of a list you shouldn't be entering each of the list members manually (what if you have a list of size 10,000,000 items? will you be manually entering one by one?)</li>\n<li><code>Counter()</code> You could use counter dict from the <code>collections</code> library for counting list members</li>\n</ul>\n<p><strong>An improved version:</strong></p>\n<p><strong>If you want to get duplicates and print them:</strong></p>\n<pre><code>from collections import Counter\n\n\ndef get_duplicates(numbers: list):\n """Return list duplicates."""\n num_duplicates = Counter(numbers)\n return {item for item in num_duplicates if num_duplicates[item] > 1}\n\n\nif __name__ == '__main__':\n list_of_duplicates = [1, 2, 2, 3, 4, 3, 5, 2, 7, 1, ]\n print(get_duplicates(list_of_duplicates))\n</code></pre>\n<p><strong>If you want to delete duplicates then use a <code>set</code></strong></p>\n<pre><code>print(set(list_of_duplicates))\n</code></pre>\n<p><strong>output:</strong> <code>{1, 2, 3, 4, 5, 7}</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:00:39.940",
"Id": "449852",
"Score": "0",
"body": "bullseye .Actually i didnt understand what is happening in this line. return {item for item in numbers if Counter(numbers)[item] > 1} can you please explain this to me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:05:01.137",
"Id": "449854",
"Score": "0",
"body": "@gokul Thank you for accepting my answer, you should be using the upvote ^ as well however if you still need answers then I suggest you unaccept my answer and use the upvote ^ for now and decide later which answer is the most helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:08:50.843",
"Id": "449856",
"Score": "0",
"body": "@gokul `{}` are `set` delimiters, a set does not contain duplicates(each set member will appear once) if you need to understand how sets work, here's a link https://www.w3schools.com/python/python_sets.asp and if you do not understand the syntax, this is called comprehension syntax and here's another link for comprehensions https://www.pythonforbeginners.com/basics/list-comprehensions-in-python"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:10:58.323",
"Id": "449858",
"Score": "0",
"body": "Not to be confused with [dict comprehension](https://www.python.org/dev/peps/pep-0274/#semantics), which has a similar syntax."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:14:28.153",
"Id": "449860",
"Score": "0",
"body": "@AlexV thanks for the reference"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:26:07.980",
"Id": "449863",
"Score": "0",
"body": "@gokul and you're welcome, man."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:28:26.363",
"Id": "449933",
"Score": "1",
"body": "@bullseye: I just added my own answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:32:49.213",
"Id": "449934",
"Score": "0",
"body": "@Graipher if you have the time, please do check this https://codereview.stackexchange.com/questions/230796/web-scraper-that-extracts-urls-from-amazon-and-ebay I need a review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:36:19.637",
"Id": "449935",
"Score": "0",
"body": "@bullseye: Puh, that *is* a lot of code. I won't have time for that today, I might take a look tomorrow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:37:07.443",
"Id": "449936",
"Score": "0",
"body": "@Graipher take your time and thanks in advance."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:49:07.810",
"Id": "230813",
"ParentId": "230806",
"Score": "5"
}
},
{
"body": "<p>Since you are a beginner, this is a good opportunity to learn about Python's standard library, its data structures and best practices.</p>\n\n<p>Before starting, you should always separate user in-/output and the actual calculations, as recommended in other answers. I'm going to assume that from now on.</p>\n\n<p>It is also not quite clear how to interpret your question. Should your code just note all duplicate items or should it remove them?</p>\n\n<hr>\n\n<p>Let's first look at the second possibility. One way to find out how often each element appears in a <code>list</code> is to use <a href=\"https://docs.python.org/3/library/stdtypes.html#typesseq-common\" rel=\"nofollow noreferrer\"><code>list.count</code></a>. With this we could do:</p>\n\n<pre><code>def make_unique(x):\n return [v for v in x if x.count(v) == 1]\n</code></pre>\n\n<p>This uses a <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\">list comprehension</a> that works similar to a <code>for</code> loop but is more compact and slightly faster. However, the algorithm is not perfect, because <code>list.count</code> checks the whole list every time it is called, so this is <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span>.</p>\n\n<p>If we don't care about the order, then we can just use a <a href=\"https://docs.python.org/3/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>set</code></a>, which is a lot faster since it only iterates through our list once, which makes it <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>:</p>\n\n<pre><code>def make_unique(x):\n return list(set(x))\n</code></pre>\n\n<p>Another alternative if we do want to keep the order is to use the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>itertools</code> recipe</a> <code>unique_everseen</code>:</p>\n\n<pre><code>from itertools import filterfalse\n\ndef unique_everseen(iterable, key=None):\n \"List unique elements, preserving order. Remember all elements ever seen.\"\n # unique_everseen('AAAABBBCCDAABBB') --> A B C D\n # unique_everseen('ABBCcAD', str.lower) --> A B C D\n seen = set()\n seen_add = seen.add\n if key is None:\n for element in filterfalse(seen.__contains__, iterable):\n seen_add(element)\n yield element\n else:\n for element in iterable:\n k = key(element)\n if k not in seen:\n seen_add(k)\n yield element\n</code></pre>\n\n<p>It is a bit more complicated, because it also allows to define a <code>key</code> function which is used to determine if an object has been seen before. Internally it keeps a <code>set</code>, but it <code>yield</code>s elements in order. It also iterates over the list exactly once.</p>\n\n<hr>\n\n<p>If you want to get all elements that are repeated, you could also use <code>list.count</code>:</p>\n\n<pre><code>def get_duplicates(x):\n return [v for v in x if x.count(v) > 1]\n</code></pre>\n\n<p>However, storing seen elements is a better solution. To also keep track of how often you have seen them, you can store them in a <code>dict</code>:</p>\n\n<pre><code>def get_duplicates(x):\n dupes = {}\n for v in x:\n if v in dupes:\n dupes[v] += 1\n else:\n dupes[v] = 1\n for v in x:\n if dupes[v] > 1:\n yield v, dupes[v]\n dupes[v] = 0\n</code></pre>\n\n<p>This needs to make two passes over the list, just like your code. One to count all elements (you just set a flag), and one to yield them in order, together with how often they appeared. By setting the value to <code>0</code> afterwards, each value appears only once.</p>\n\n<p>That first loop can be shortened a bit by using a <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a>, so we don't need to concern ourselves with the special case that a value is not yet in the dictionary:</p>\n\n<pre><code>from collections import defaultdict\n\ndef get_duplicates(x):\n dupes = defaultdict(int)\n for v in x:\n dupes[v] += 1\n for v in x:\n if dupes[v] > 1:\n yield v, dupes[v]\n dupes[v] = 0\n</code></pre>\n\n<p>This uses the fact that an <code>int</code> is by default <code>0</code>. However, we still need two passes. So, instead we can use a <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>, which was made for exactly this situation. You want to count how often each item appears.</p>\n\n<pre><code>from collections import Counter\n\ndef get_duplicates(x):\n dupes = Counter(x)\n for v, c in dupes.items():\n if c > 1:\n yield v, c\n</code></pre>\n\n<p>But this still iterates twice, once over the whole list to build the <code>Counter</code>, and once over all unique values in it. To avoid that we can use the method <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter.most_common\" rel=\"nofollow noreferrer\"><code>Counter.most_common</code></a>, which returns the items from the counter, sorted from most common to least. Together with <a href=\"https://docs.python.org/3/library/itertools.html#itertools.takewhile\" rel=\"nofollow noreferrer\"><code>itertools.takewhile</code></a>, which keeps on taking items until the condition is false:</p>\n\n<pre><code>from collections import Counter\nfrom itertools import takewhile\n\ndef get_duplicates(x):\n return ((v, c)\n for v, c in takewhile(lambda t: t[1] > 1, Counter(x).most_common()))\n</code></pre>\n\n<p>This returns a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator</a> (just like all functions with a <code>yield</code> are). You need to iterate over it to get all elements, either with:</p>\n\n<pre><code>x = [1, 2, 2, 4, 2, 2, 6, 7, 2, 2, 5, 7]\nfor v, c in get_duplicates(x):\n print(f\"{v} occurred {c} times\")\n</code></pre>\n\n<p>You can also use <code>list</code> to exhaust the generator:</p>\n\n<pre><code>dupes = list(get_duplicates(x))\n</code></pre>\n\n<p>This function is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> for the <code>Counter</code> and <span class=\"math-container\">\\$\\mathcal{O}(k)\\$</span> with <span class=\"math-container\">\\$k \\le \\frac{n}{2}\\$</span> the number of elements that appear more than once. In total that gives you <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> at worst.</p>\n\n<hr>\n\n<p>Now let's get to the first part of your function, asking the user for input. For this it makes sense to make a function that keeps on asking the user until they supplied a valid input. While your function guards against wrong input for the elements of the list, the user can enter anything for the length. Including <code>\"foobar\"</code>, which will crash the program.</p>\n\n<pre><code>def ask_user(message, type_=None):\n while True:\n user_input = input(message)\n if type_ is None:\n return user_input\n try:\n return type_(user_input)\n except ValueError:\n print(\"Wrong Input\")\n\nif __name__ == \"__main__\":\n n = ask_user(\"Enter the number of elements\", int)\n x = [ask_user(f\"Enter the number {i}\", int) for i in range(n)]\n</code></pre>\n\n<p>Note that I used <code>type_</code> instead of <code>type</code>, because that is a built-in function. Using a trailing underscore in that case is a common workaround.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-17T07:18:23.003",
"Id": "449989",
"Score": "1",
"body": "thankyou so much Graipher"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T16:14:33.337",
"Id": "230854",
"ParentId": "230806",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230813",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T07:07:28.987",
"Id": "230806",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Program to print the multiple occurrence of numbers in a list"
}
|
230806
|
<p>The <a href="https://gmplib.org/" rel="nofollow noreferrer">GNU Multiple Precision Arithmetic Library</a> provides arbitrary-precision numeric types with both C and C++ bindings.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:33:39.853",
"Id": "230811",
"Score": "0",
"Tags": null,
"Title": null
}
|
230811
|
For code using the GNU Multiple Precision Arithmetic Library
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:33:39.853",
"Id": "230812",
"Score": "0",
"Tags": null,
"Title": null
}
|
230812
|
<p>I'm creating a couple of dynamic css classes, and the idea is that i get a string from an episerver context and add that to the class list of an element.</p>
<p>I know that numbers can be included in css classes, but what is good css code conduct, is it a good idea to include numbers in class names, or should i change it from <code>body1 --> body-one.</code></p>
<pre><code>body1 {
font-size: 1.4rem;
}
body2 {
font-size: 1.6rem;
}
body-one {
font-size: 1.4rem;
}
body-two {
font-size: 1.6rem;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:13:01.800",
"Id": "449859",
"Score": "0",
"body": "Neither is good. Instead of numbers use a suffix that describes the difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:21:03.150",
"Id": "449862",
"Score": "0",
"body": "@RoToRa, I agree, the reason i created this was to get some consistency between what they input in their CMS, and the class that appears in the code, instead of having to guess what variable corolates in the CMS and the code.\nAssume that i can't change the variables in the CMS since it's unchangeable for me."
}
] |
[
{
"body": "<p>Perfect naming in any language allowing freedom for your names are:</p>\n\n<ol>\n<li>Descriptive. (Makes it clear what it means at a glance)</li>\n<li>Short. (less chance for typos, types faster and therefore easier to work with.)</li>\n</ol>\n\n<p>In your case, the names only mean to affect the text size. So appropriate names would be something like:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>text-medium {\n font-size: 1.4rem;\n}\ntext-big {\n font-size: 1.6rem;\n}\n</code></pre>\n\n<p>Since this makes it clear what they do. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:41:11.880",
"Id": "230817",
"ParentId": "230814",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "230817",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T08:49:50.130",
"Id": "230814",
"Score": "0",
"Tags": [
"css"
],
"Title": "Good conduct of including numbers in css classes"
}
|
230814
|
<p>I've made a simple app that shows if the term entered into the search bar is present in a number of common English words.</p>
<p>This is the stackblitz: <a href="https://stackblitz.com/edit/react-mostusedwords" rel="nofollow noreferrer">https://stackblitz.com/edit/react-mostusedwords</a></p>
<p>Note how <code>App</code>, <code>SearchBar</code> and <code>ResultsDisplay</code> all have a variable to track the current search. I am looking for a better way as this seems repetitive and I can't imagine that it is good practice.</p>
<h3>App.js</h3>
<pre><code>import React, { Component } from 'react';
import { render } from 'react-dom';
import SearchBar from './Components/SearchBar/SearchBar';
import ResultsDisplay from './Components/ResultsDisplay/ResultsDisplay';
import './style.css';
import mostCommonWords from './MostCommonWords';
class App extends Component {
state = {
results: [],
currentSearch: ''
}
onSearch = (term) => {
let list = [];
if(term !== '')
for(let x = 0; x < mostCommonWords.length; x++)
if(mostCommonWords[x].includes(term))
list.push(mostCommonWords[x])
this.setState({ results: list, currentSearch: term });
}
render() {
return (
<div>
<h1 className="app-header1">Search 1000 common English words</h1>
<SearchBar onSearch={ this.onSearch } />
<ResultsDisplay
currentSearch={ this.state.currentSearch }
results={ this.state.results }
/>
</div>
);
}
}
render(<App />, document.getElementById('root'));
</code></pre>
<p><code>mostCommonWords</code> is just an array of words in a separate file.</p>
<h3>SearchBar.js</h3>
<pre><code>import React, { Component } from 'react';
import './SearchBar.css';
export default class SearchBar extends React.Component {
state = { searchTerm: 'as' }
componentDidMount() {
this.doSearch(this.state.searchTerm);
}
onInputChange = e => {
const newValue = e.target.value;
this.setState({ searchTerm: newValue });
this.doSearch(newValue);
}
doSearch(value){
setTimeout(
() => {
/** if value not equal, user has changed it already, so do not search */
if(value === this.state.searchTerm)
this.props.onSearch(value);
},
500
);
}
onFormSubmit = e => {
e.preventDefault();
}
render() {
return (
<div className="search-bar">
<form onSubmit={ this.onFormSubmit }>
<h2>Enter search term:</h2>
<input
name="theInputField"
value={ this.state.searchTerm }
onChange = { this.onInputChange }
/>
<div className="buttonDiv">
{/** This button does not yet */}
<button
type="button"
onClick = { e => { this.onFormSubmit(e) } }
>Search</button>
<button
type="button"
onClick = { () => { this.setState({ searchTerm: ''}) } }
>Clear</button>
</div>
</form>
</div>
);
}
}
</code></pre>
<h3>ResultsDisplay.js</h3>
<pre><code>import React, { Component } from 'react';
import Result from './Result';
import './ResultsDisplay.css';
export default class ResultsDisplay extends React.Component {
state = {
totalItems: 0,
jsxData: [],
currentSearch: ''
};
componentDidUpdate(prevProps, prevState) {
if(this.props.currentSearch == prevProps.currentSearch)
return;
this.updateColumns(this.props.results);
}
updateColumns = (newItems) => {
if(!newItems || newItems.length === 0) {
this.setState({
jsxData: [],
totalItems: 0,
currentSearch: this.props.currentSearch
});
return;
}
let totalColumns = 4;
let totalItems = newItems.length;
let itemsPerColumn = Math.ceil(totalItems / totalColumns);
let rows = [];
for(let x = 0; x < itemsPerColumn; x++) {
rows.push([]);
}
for(let it = 0; it < itemsPerColumn; it++) {
for(let col = 0; col < totalColumns; col++) {
let item = newItems[col * itemsPerColumn + it];
console.log(col * itemsPerColumn + it);
rows[it].push(
<Result index={col * itemsPerColumn + it} key={item} text={item} />
);
}
}
let newJsx = [];
for(let col = 0; col < itemsPerColumn; col++) {
newJsx.push(
<tr>{rows[col]}</tr>
);
}
this.setState({
jsxData: newJsx,
totalItems: totalItems,
currentSearch: this.props.currentSearch
});
}
render(props) {
return (
<div className="results-display">
{ this.showItems() }
</div>
);
}
showItems = () => {
if(this.state.totalItems === 0) {
return (
<div>
<h2>No results</h2>
<em>No or invalid search. Try a (different) search and press enter.</em>
</div>
)
}
return (
<div>
<h2>{ this.state.totalItems } results found</h2>
<table><tbody>
{ this.state.jsxData }
</tbody></table>
</div>
);
}
}
</code></pre>
<h3>Result.js</h3>
<pre><code>import React, { Component } from 'react';
import './Result.css';
export default class Result extends React.Component {
render(props) {
if(!this.props.text)
return (<td></td>);
return (
<td className="result">
{ +this.props.index + 1 }: { this.props.text }
</td>
);
}
}
</code></pre>
<p>I need the variable to compare in the update function, but can't this be more tightly linked? In blog posts I've found this requires implementing quite copious amounts of code for something that seems simple.</p>
<p>I'd also appreciate any input on other improvements on the code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T15:42:20.380",
"Id": "449926",
"Score": "0",
"body": "Hi D3Duck, you need to input your code in your post, not on a third party link :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T22:28:28.593",
"Id": "449976",
"Score": "0",
"body": "@IEatBagels Thank you. Fixed that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-17T04:19:49.713",
"Id": "449983",
"Score": "0",
"body": "can it be taken off hold now? Question was fixed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T13:51:24.140",
"Id": "450153",
"Score": "0",
"body": "Good job on fixing your question, it's great now I hope you get answers :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-16T09:49:50.073",
"Id": "230819",
"Score": "1",
"Tags": [
"react.js",
"jsx"
],
"Title": "Beginner React App - handling different components with the same variable"
}
|
230819
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.