body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am student who is creating a big project trying to display data and information on maps using OpenLayers and React. At this point I have created a basic two page project where the map is the central piece of the application. For every page I have one main <code>Component</code> that contains its Sidebar, the Viewer Component that contains the map itself and some additional Components specific for that page.</p> <p>The viewer Class is a special Component that I wrote for every page. This Component handles all the user interactions with the page. It sends and receives information from the main Component as well. I have chosen to create a separate Viewer Class for each page because of the different ways each page works. They might load in different things or handle interactions completely different. If I had one Viewer Class that can be used by every page this would become to large and have to many if statements to check what code to run when handling with each separate page.</p> <p>Here is an example of the Homepage Viewer. In the constructor I create the map and add some references for a popup window that shows up when the user clicks on one of the features on the map. This popup window shows some basic information about the feature and let's the user add it to his list of features.</p> <ul> <li><p>In <code>ComponentDidMount</code> I first make the <code>Map</code> class add the <code>boundrieslayer</code> and give an function to call when one of the features of this layer has been clicked on. I also create the overlay window for the popup to the map. This will be shown when a feature has been clicked.</p></li> <li><p><code>resetMapLayers</code> is a function that has will be called on each Render. Here I make the map check if what background Tilelayer to use and if it should show the top layer or not.</p></li> <li><p><code>featureSelected()</code> is the function that handles a click event of a<br> feature of the top layer. This will create a popup with the basic<br> information of the feature.</p></li> <li><p><code>closePopup</code> will be called when the popup has been closed. This will<br> make the map deselect the clicked on feature. Otherwise it would stay selected when the popup has been closed. It will also remove the <code>Overlay(popup)</code> from the screen.</p></li> <li><p><code>addFeature()</code> is the function that will be called when a user chooses to add this feature to his list of features. This can be done by the user in the popup window of that feature</p></li> </ul> <p></p> <pre><code>import React, { Component } from "react"; import { connect } from "react-redux"; import Map from "../Map/Map"; import "ol/ol.css"; import styles from "./Viewer.module.scss"; import Overlay from "ol/Overlay"; import Button from "../UI/Button/Button"; class MainViewer extends Component { constructor(props) { super(props); Map.createNewMap(); this.popup = React.createRef(); this.popupContent = React.createRef(); } componentDidMount() { Map.addBoundriesLayer(this.featureSelected); Map.map.setTarget("map"); let container = this.popup.current; let overlay = new Overlay({ element: container, autoPan: true, autoPanAnimation: { duration: 250, }, }); this.overlay = overlay; Map.map.addOverlay(overlay); } resetMapLayers() { Map.setBackgroundTileLayer(this.props.type); Map.togglePlotBoundriesLayers(this.props.plotBoundriesState); } featureSelected = (event, select) =&gt; { if (event.selected[0]) { this.selectedFeature = event.selected[0]; let selectedFeature = { id: event.selected[0].id_, gewasgroepnaam: event.selected[0].getProperties().GEWASGROEP, gewasnaam: event.selected[0].getProperties().LBLHFDTLT, oppervlak: (event.selected[0].getProperties().OPPERVL / 10000).toFixed( 2 ), coords: event.selected[0].getProperties().geometry.extent_, }; let content = this.popupContent.current; content.innerHTML = "&lt;p&gt;&lt;strong&gt;Name: &lt;/strong&gt;" + selectedFeature.name + "&lt;/p&gt;" + "&lt;p&gt;&lt;strong&gt;Exact Name: &lt;/strong&gt;" + selectedFeature.exactName + "&lt;/p&gt;" + "&lt;p&gt;&lt;strong&gt;Area: &lt;/strong&gt;" + selectedFeature.area + " ha&lt;/p&gt;"; this.overlay.setPosition(event.mapBrowserEvent.coordinate); } }; closePopup() { this.overlay.setPosition(undefined); Map.clearSelect(); return false; } addFeature() { this.overlay.setPosition(undefined); Map.clearSelect(); this.props.featureAddedHandler(this.selectedFeature); } render() { this.resetMapLayers(); return ( &lt;div&gt; &lt;div id="map" className={styles.Map}&gt;&lt;/div&gt; &lt;div ref={this.popup} className={styles.OlPopup}&gt; &lt;div className={styles.OlPopupButtonsDiv}&gt; &lt;Button btnType="Danger" className={[styles.PopupButton, styles.ClosePopupButton].join( " " )} clicked={() =&gt; this.closePopup()} &gt; Annuleer &lt;/Button&gt; &lt;Button btnType="Success" className={[styles.PopupButton, styles.AddPopupButton].join(" ")} clicked={() =&gt; this.addFeature()} &gt; Voeg Toe &lt;/Button&gt; &lt;/div&gt; &lt;div ref={this.popupContent}&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ); } } const mapStateToProps = (state) =&gt; { return { type: state.mapDetails.type, plotBoundriesState: state.mapDetails.state, }; }; export default connect(mapStateToProps)(MainViewer); </code></pre> <p>The <code>Map</code> class contains the actual map. It handles with all the specific map issues. It allows to add layers to the map, creating the initial map, adding map interactions,...</p> <ul> <li><p>In the constructor I call the methods to initialy create a basic map with a TileLayer background.</p></li> <li><p>The <code>createMap</code> and <code>createNewMap</code> methods let's me create the map object itself.</p></li> <li><p><code>createBackgroundLayerGroups()</code> creates the Tilelayer that is the background layer. It can be either OSM or Bing Maps. The visibility property let's me make handle which one to show.</p></li> <li><p><code>clearAllBoundriesLayers()</code> deletes all the boundries layers that are able to be put on top of the Tilelayer. It deletes every layer and clears the select of the interactions that has been added to these layers. I do this so when I change page the layers will be deleted.</p></li> <li><p><code>addBoundriesLayer</code> let's me set and add a boundries layer. This is the Vector layer that will be put on top of the TileLayer.</p></li> <li><p><code>addUsersPlotBoundriesLayer</code> does the same as <code>"addBoundriesLayer"</code> but does it for all the layers that the user has. This function will be called in another page that only shows the features of the user.</p></li> <li><p><code>setExtentOfMapByUserFeaters</code> let's me set the extent of the map by either a given extent or by the features of the user.</p></li> <li><p><code>setInteractionForPlotBoundriesLayer</code> adds the interaction for the <code>PlotBoundriesLayer</code>.</p></li> <li><p><code>setHoverInteractionForUserPlotBoundries</code> adds the hover interaction for the <code>plotUserBoundriesLayer</code>.</p></li> <li><p><code>clearSelect</code> clears all the selected features. So they won't be highlighted no more.</p></li> <li><p><code>setBackgroundTileLayer</code> let's me show a specific background TileLayer.</p></li> <li><p><code>togglePlotBoundriesLayers</code> let's me hide or show the Vector layer that is then been shown.</p></li> </ul> <pre><code>import Map from "ol/Map"; import TileWMS from "ol/source/TileWMS"; import TileLayer from "ol/layer/Tile"; import View from "ol/View"; import OSM from "ol/source/OSM"; import BingMaps from "ol/source/BingMaps"; import VectorSource from "ol/source/Vector"; import { bbox as bboxStrategy } from "ol/loadingstrategy"; import GeoJSON from "ol/format/GeoJSON"; import { Vector, Group, Tile } from "ol/layer"; import Select from "ol/interaction/Select"; import { Feature } from "ol"; import { Polygon } from "ol/geom"; import { Fill, Stroke, Style } from "ol/style"; class OlMap { constructor() { this.createNewMap(); this.createBackgroundLayerGroups(); } createNewMap() { this.map = this.createMap(); } createMap() { return new Map({ target: null, layers: [], view: new View({ center: [594668.0262129545, 6602083.305674396], maxZoom: 19, zoom: 14, }), }); } createBackgroundLayerGroups() { this.layersOSM = new Group({ layers: [ new Tile({ source: new OSM(), }), new Tile({ source: new BingMaps({ imagerySet: "Aerial", key: process.env.REACT_APP_BING_MAPS, }), visible: false, }), ], }); } clearAllBoundriesLayers() { this.map.getLayers().forEach((layer) =&gt; { if ( layer.get("name") === "plotBoundriesLayer" || layer.get("name") === "plotUserBoundriesLayer" ) { layer.getSource().clear(); this.map.removeLayer(layer); } }); if (this.select) { this.select.getFeatures().clear(); } } addBoundriesLayer(featureSelected) { this.clearAllBoundriesLayers(); let vectorSource = new VectorSource({ format: new GeoJSON(), minScale: 15000000, loader: function (extent, resolution, projection) { /* Link for the DLV let url = process.env.REACT_APP_MAP_API + extent.join(",") + ",EPSG:3857"; */ let url = process.env.REACT_APP_MAP_API + extent.join(",") + ",EPSG:3857"; // */ let xhr = new XMLHttpRequest(); xhr.open("GET", url); let onError = function () { vectorSource.removeLoadedExtent(extent); }; xhr.onerror = onError; xhr.onload = function () { if (xhr.status === 200) { let features = vectorSource .getFormat() .readFeatures(xhr.responseText); features.forEach(function (feature) { //ID for the DLV //feature.setId(feature.get("OBJ_ID")); feature.setId(feature.get("OIDN")); }); vectorSource.addFeatures(features); } else { onError(); } }; xhr.send(); }, strategy: bboxStrategy, }); let vector = new Vector({ //minZoom: 13, source: vectorSource, }); this.setInteractionForPlotBoundriesLayer(vector, featureSelected); vector.set("name", "plotBoundriesLayer"); this.map.addLayer(vector); } addUsersPlotBoundriesLayer(featureSelected, featureHovered, newFeatures) { this.clearAllBoundriesLayers(); if (newFeatures.length &gt; 0) { let vectorSource = new VectorSource({ format: new GeoJSON(), minScale: 15000000, strategy: bboxStrategy, }); newFeatures.forEach((newFeature) =&gt; { let feature = new Feature({ geometry: new Polygon([newFeature.geometry]), }); feature.setId(newFeature.plotId); vectorSource.addFeature(feature); }); let vector = new Vector({ //minZoom: 13, source: vectorSource, }); this.setInteractionForPlotBoundriesLayer(vector, featureSelected); this.setHoverInteractionForUserPlotBoundries(vector, featureHovered); vector.set("name", "plotUserBoundriesLayer"); this.plotsExtent = vectorSource.getExtent(); this.map.addLayer(vector); } } setExtentOfMapByUserFeaters(extent) { if (extent === undefined) { if (this.plotsExtent !== undefined &amp;&amp; this.plotsExtent[0] !== Infinity) { this.map.getView().fit(this.plotsExtent); } } else { this.map.getView().fit(extent); } } setInteractionForPlotBoundriesLayer(layer, featureSelected) { this.select = new Select({ layers: [layer], }); this.select.on("select", (event) =&gt; featureSelected(event, this.select)); this.map.addInteraction(this.select); } setHoverInteractionForUserPlotBoundries(layer, featureHovered) { this.hoveredFeature = null; let defaultStyle = new Style({ stroke: new Stroke({ width: 2, color: "#9c1616", }), fill: new Fill({ color: "#c04e4e" }), }); let hoveredStyle = new Style({ stroke: new Stroke({ width: 2, color: "#9c1616", }), fill: new Fill({ color: "#9c1616" }), }); this.map.on("pointermove", (e) =&gt; { layer .getSource() .getFeatures() .forEach((feature) =&gt; { feature.setStyle(defaultStyle); }); let newFeature = null; this.map.forEachFeatureAtPixel(e.pixel, (f) =&gt; { newFeature = f; newFeature.setStyle(hoveredStyle); return true; }); if (newFeature) { if ( this.hoveredFeature === null || this.hoveredFeature !== newFeature ) { this.hoveredFeature = newFeature; featureHovered(this.hoveredFeature.id_); } } else { if (this.hoveredFeature !== null) { this.hoveredFeature = null; featureHovered(null); } } }); } hoveredSideBarFeatureHandler(hoveredFeatureId) { let defaultStyle = new Style({ stroke: new Stroke({ width: 2, color: "#9c1616", }), fill: new Fill({ color: "#c04e4e" }), }); let hoveredStyle = new Style({ stroke: new Stroke({ width: 2, color: "#9c1616", }), fill: new Fill({ color: "#9c1616" }), }); this.map.getLayers().forEach((layer) =&gt; { if (layer.get("name") === "plotUserBoundriesLayer") { layer .getSource() .getFeatures() .forEach((feature) =&gt; { if (feature.id_ === hoveredFeatureId) { feature.setStyle(hoveredStyle); } else { feature.setStyle(defaultStyle); } }); } }); } clearSelect() { this.select.getFeatures().clear(); } setBackgroundTileLayer(type) { if (this.backgroundTileType === null) { this.backgroundTileType = "OPENSTREETMAP"; } if (this.map.getLayers().getArray().length === 0) { this.map.setLayerGroup(this.layersOSM); } else { if (this.backgroundTileType !== type) { this.backgroundTileType = type; console.log(this.map.getLayers()); this.map.getLayers().getArray()[0].setVisible(false); this.map.getLayers().getArray()[1].setVisible(false); if (type === "OPENSTREETMAP") { this.map.getLayers().getArray()[0].setVisible(true); } else if (type === "BING MAPS") { this.map.getLayers().getArray()[1].setVisible(true); } } } } togglePlotBoundriesLayers(state) { if (this.plotBoundriesState === null) { this.plotBoundriesState = true; } if (this.plotBoundriesState !== state) { this.plotBoundriesState = state; this.map.getLayers().forEach((layer) =&gt; { if (layer.get("name") === "plotBoundriesLayer") { layer.setVisible(state); } if (layer.get("name") === "plotUserBoundriesLayer") { console.log(state); layer.setVisible(state); } }); } } addTileLayer(url) { const wmsLayer = new TileLayer({ source: new TileWMS({ url, params: { TILED: true, }, crossOrigin: "Anonymous", }), }); this.map.addLayer(wmsLayer); } } export default new OlMap(); </code></pre> <p>At this point I am wondering if I am doing things well or what can be done different or better to optimize my code. This will help me in the long run not getting stuck with bade code I created at the beginning of the project.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:47:00.047", "Id": "240299", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "Using OpenLayers in React" }
240299
<p>Given a Tax type and city, access a REST API to get the total amount of taxes with the given type and at the given city. This information is to be grouped by users and ordered ascending by numerical id. To access the log of taxes, I perform an HTTP GET request to <code>https://api.doit.com/taxes/search?taxType={0}&amp;page={1}</code> where the <code>taxType</code> is either 'd' or 'c'and the <code>page</code> is the page of the results, as an integer. The response to a request is a JSON ith the following 5 fields:</p> <pre><code>public class PageResult { public string page { get; set; } public int per_page { get; set; } public int total { get; set; } public int total_pages { get; set; } public TaxData[] data { get; set; } } </code></pre> <p>Each Tax Record has the following schema:</p> <pre><code>public class TaxData { public int id { get; set; } public int userId { get; set; } public string userName { get; set; } public long timestamp { get; set; } public string txnType { get; set; } public string amount { get; set; } public City city { get; set; } public string ip { get; set; } } </code></pre> <p>The city object has the following scheme:</p> <pre><code>public class City { public int id { get; set; } public string address { get; set; } public string city { get; set; } public int zipCode { get; set; } } </code></pre> <p>I need to return a 2d array of integers with two columns, where the first column contains user ids of all users those pay taxes in the given city using the given tax type. The second column for a row corresponding to some user must contain the total amount that this user pays in dollars.</p> <p>the following code that I want to review, especially the API consuming way.</p> <pre><code>class Program { private static readonly string apiUrl = "https://api.doit.com/taxes/search?taxType={0}&amp;page={1}"; static void Main(string[] args) { var c = GetTaxesTotals(1, "d"); Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(c)); Console.ReadLine(); } public static List&lt;List&lt;int&gt;&gt; GetTaxesTotals(int cityId, string taxType) { List&lt;TaxData&gt; taxes = GetTaxes(cityId, taxType); var transactionGroupsPreUser = taxes.OrderBy(x =&gt; x.userId).GroupBy(x =&gt; x.userId); var result = new List&lt;List&lt;int&gt;&gt;(); result = transactionGroupsPreUser.Select(g =&gt; new List&lt;int&gt; { g.Key, (int)g.Sum(x =&gt; decimal.Parse(x.amount, NumberStyles.Currency)) }).ToList(); if (result.Count == 0) { result = new List&lt;List&lt;int&gt;&gt; { new List&lt;int&gt; { -1, -1 } }; } return result; } private static PageResult GetDataPage(string taxType, int page) { if (!string.Equals(taxType, "c", StringComparison.OrdinalIgnoreCase) &amp;&amp; !string.Equals(taxType, "d", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Unexpected tax type the allowed values: 'c', 'd'"); } var uri = string.Format(apiUrl, taxType, page); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); request.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate; var jsonResult = string.Empty; using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { jsonResult = reader.ReadToEnd(); } return Newtonsoft.Json.JsonConvert.DeserializeObject&lt;PageResult&gt;(jsonResult); } private static List&lt;TaxData&gt; GetTaxes(int city, string taxType) { PageResult page = null; var taxes = new List&lt;TaxData&gt;(); var currentPageIndex = 0; do { currentPageIndex++; page = GetDataPage(taxType, currentPageIndex); if (page?.data != null) { taxes.AddRange(page.data.Where(x =&gt; x.city.id == city)); } } while (currentPageIndex &lt; page.total_pages); return taxes; } } </code></pre>
[]
[ { "body": "<p>Welcome to Code Review.\nI'm new to this site too so I hope that this is what you are looking for.</p>\n\n<p>Looking at the API call it seems that <code>GetDataPage</code> does more than one action:</p>\n\n<ul>\n<li>validates the inputs used to form the URL </li>\n<li>forms the URL</li>\n<li>create a HttpWebRequest instance</li>\n<li>makes the call</li>\n<li>formats the response</li>\n</ul>\n\n<p>I would suggest refactoring <code>GetDataPage</code> into 5 smaller methods to make it more self-documenting.</p>\n\n<p>In terms of calling the API there does not seem to be any handling for cases other than the happy path, eg,</p>\n\n<ul>\n<li>if the server is down</li>\n<li>if the server hangs, ie, you make the request and get no response back. In this case I suspect your code will hang as the call to the API is not async</li>\n<li>if the server returns a response other than the expected one (I guess a 200)</li>\n</ul>\n\n<p>Adding code to address these would make your code more robust. If there is one suggestion over all the others it would be to make the HTTP request async so that the application is not blocked while awaiting the response.</p>\n\n<p>I notice that there is no exception handling but I am assuming that this is a prototype.</p>\n\n<p>I hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T09:56:52.027", "Id": "240329", "ParentId": "240300", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T18:53:19.303", "Id": "240300", "Score": "1", "Tags": [ "c#", "performance", "api" ], "Title": "Consuming an API with Pagination" }
240300
<p>I programmed the extended Euclidean algorithm together with the inverse modulo because I am making an RSA system from scratch. Any feedback regarding efficiency etc. is welcome :)</p> <pre><code> def ext_gcd(a, b): a0, a1 = a, b x0, x1 = 1, 0 y0, y1 = 0, 1 while a1 != 0: q = a0//a1 r, s, t = a1, x1, y1 a1 = a0 % a1 x1 = x0 - q*x1 y1 = y0 - q*y1 a0, x0, y0 = r, s, t return x0, y0, a0 def inverse_mod(a, mod): va, y0, a0 = Math.ext_gcd(a, mod) return va % mod </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T21:11:34.637", "Id": "471308", "Score": "1", "body": "No... the answer given there isn't very time efficient..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T21:16:08.547", "Id": "471311", "Score": "1", "body": "@πάνταῥεῖ You likely know this but [duplicates are different on CR](https://codereview.meta.stackexchange.com/a/5704/120114)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T17:17:54.663", "Id": "472062", "Score": "1", "body": "I'm voting to repoen because while both posts involve the Euclidean algorithm this one also mentions inverse modulo. For context, see meta posts like [this](https://codereview.meta.stackexchange.com/a/5704/120114) and [this](https://codereview.meta.stackexchange.com/a/5896/120114)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T22:05:02.330", "Id": "472087", "Score": "1", "body": "While the issues I'd raise with both snippets overlap, I think them sufficiently different to not qualify as duplicates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T14:56:59.070", "Id": "472179", "Score": "1", "body": "I also thought that this shouldn't be marked as duplicate... yes me and the other guy have both the same mathematical algorithm but mine is a little bit different and the answers given there... well the one answer at the moment uses the most time inefficient approach I have ever seen and I was asking also for feedback for time efficiency. I would appreciate a reopen." } ]
[ { "body": "<p>Give your variables more meaningful names reflecting their role in the algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T20:22:58.183", "Id": "471301", "Score": "1", "body": "I'm getting some dejavu here..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T20:24:45.750", "Id": "471303", "Score": "0", "body": "@Peilonrayz Sure, me too ...." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T20:14:07.327", "Id": "240305", "ParentId": "240304", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T20:09:21.720", "Id": "240304", "Score": "1", "Tags": [ "python", "reinventing-the-wheel", "mathematics", "cryptography" ], "Title": "Python extended Euclidean algortihm + inverse modulo" }
240304
<p>Given a binary tree, return the sum of values of its deepest leaves.</p> <p><a href="https://i.stack.imgur.com/NSkLh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NSkLh.png" alt="enter image description here"></a> </p> <blockquote> <p>Constraints:</p> <p>The number of nodes in the tree is between 1 and 10^4. The value of nodes is between 1 and 100.</p> </blockquote> <p>Please review for performance and style </p> <pre><code>using GraphsQuestions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TreeQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/deepest-leaves-sum/ /// &lt;/summary&gt; [TestClass] public class DeepestLeavesSumTest { [TestMethod] public void ExampleTest() { var root = new TreeNode(1); root.left = new TreeNode(2); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); root.left.left.left = new TreeNode(7); root.right = new TreeNode(3); root.right.right = new TreeNode(6); root.right.right.right = new TreeNode(8); DeepestLeavesSumClass deepest = new DeepestLeavesSumClass(); Assert.AreEqual(15, deepest.DeepestLeavesSum(root)); } } public class DeepestLeavesSumClass { int maxDepth = 0; int sum = 0; public int DeepestLeavesSum(TreeNode root) { if (root == null) { return 0; } DFS(root, 0); return sum; } private void DFS(TreeNode root, int depth) { if (root == null) { return; } if (maxDepth &lt; depth + 1) { maxDepth = depth + 1; sum = root.val; } else if (depth + 1 == maxDepth) { sum += root.val; } DFS(root.left, depth + 1); DFS(root.right, depth + 1); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T21:14:07.970", "Id": "471309", "Score": "0", "body": "if you give -1 please explain why, I would like to learn." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T13:17:40.520", "Id": "471375", "Score": "0", "body": "In a binary tree formatted as in your given input data, each layer starts at a number of type \\$2^{depth} - 1\\$, so you don't even need to perform a DFS, and only \\$O(1)\\$ memory is required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T13:24:14.087", "Id": "471376", "Score": "0", "body": "How? What do you mean" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T13:25:53.097", "Id": "471377", "Score": "0", "body": "The `root = [1,2,3,4,5,null,6,7,null,null,null,null,8]` part. In such a format, e.g. the third layer starts at index \\$2^3 - 1 = 7\\$ (and continues till the array ends or the index \\$2^4 - 1 = 15\\$ exclusive)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T14:32:00.807", "Id": "471384", "Score": "0", "body": "Oh i get what you mean. But the function is givena TreeNode as input" } ]
[ { "body": "<p>This solution seems generally fine although it's not much code to analyze and it's already as succinct as it could reasonably be.</p>\n\n<p>A few suggestions:</p>\n\n<ul>\n<li>Avoid naming a class <code>SomethingClass</code>. It's enough that the type is a class; appending types to names adds noise.</li>\n<li><code>SumDeepestLeaves</code> sounds more like a method (an action) while <code>DeepestLeavesSum</code> sounds more like a property or attribute.</li>\n<li>Instead of using <code>depth + 1</code>, use <code>depth</code>. It doesn't matter how you compute the depth as long as it's consistent.</li>\n<li>Use vertical whitespace before and after all blocks and function definitions.</li>\n<li><p>Creating objects is expensive. Worse, introducing state can cause bugs as the method is <a href=\"https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning\" rel=\"nofollow noreferrer\">non-idempotent</a>--the caller can't use the object more than once or results will be incorrect. </p>\n\n<p>It's an antipattern to have to create an object just to call what seems like a stateless method from the perspective of the caller. Doing:</p>\n\n<pre><code>DeepestLeavesSumClass deepest = new DeepestLeavesSumClass();\nAssert.AreEqual(15, deepest.DeepestLeavesSum(root));\n</code></pre>\n\n<p>feels a lot like:</p>\n\n<pre><code>MathematicsClass mathematics = new MathematicsClass();\nAssert.AreEqual(3, mathematics.Add(1, 2));\n</code></pre>\n\n<p>I exaggerate, but a static method like:</p>\n\n<pre><code>Assert.AreEqual(15, BinaryTree.SumDeepestLeaves(root));\n</code></pre>\n\n<p>is more pleasant and semantically meaningful. An alternative to making it static would be to encapsulate/hide <code>TreeNode</code> as a member of a <code>BinaryTree</code> class, then instantiate the <code>BinaryTree</code> class, populate your nodes and call <code>tree.SumDeepestLeaves()</code> to sum your tree's deepest leaves. This is a bit of a tangent on your current design even if it feels most correct from an OOP perspective.</p></li>\n</ul>\n\n<p>Basically, you've introduced two class variables on an object as a shortcut in order to keep your algorithm clean and easy to write, but this design adds complexity to the caller and makes the class brittle.</p>\n\n<p>One solution is to use the <code>ref</code> keyword to keep all data local to the calls:</p>\n\n<pre><code>class BinaryTree\n{\n public static int SumDeepestLeaves(TreeNode root)\n {\n if (root == null)\n {\n return 0;\n }\n\n int maxDepth = 0;\n int sum = 0;\n SumDeepestLeaves(root, 0, ref maxDepth, ref sum);\n return sum;\n }\n\n private static void SumDeepestLeaves(TreeNode root, int depth, ref int maxDepth, ref int sum)\n {\n if (root == null)\n {\n return;\n }\n else if (maxDepth &lt; depth)\n {\n maxDepth = depth;\n sum = root.val;\n }\n else if (depth == maxDepth)\n {\n sum += root.val;\n }\n\n SumDeepestLeaves(root.left, depth + 1, ref maxDepth, ref sum);\n SumDeepestLeaves(root.right, depth + 1, ref maxDepth, ref sum);\n }\n}\n</code></pre>\n\n<p>This is more verbose, but the benefits are worth it. You can also argue that <code>ref</code> makes the programmer's intent clearer to help justify the extra verbosity and added parameters.</p>\n\n<p>Kudos on keeping the recursive helper private. However, a name like <code>DFS</code> seems too generic--it does do a DFS, but it's specific to summing deepest leaves. As the <code>BinaryTree</code> class grows to contain dozens of methods, it'd no longer be obvious from the name that <code>DFS</code> is related to <code>SumDeepestLeaves</code>. Overload the <code>SumDeepestLeaves</code> method so there's no doubt.</p>\n\n<p>You can also do this using a BFS instead of recursion using the level-order trick where each iteration on the queue dumps the entire level, queuing up the next round and summing the current. This isn't definitely better, but at least there's no refs and no helper function, so all the logic is in one place, and it's worth knowing about in any case.</p>\n\n<pre><code>class BinaryTree \n{\n public int SumDeepestLeaves(TreeNode root) \n {\n if (root == null)\n {\n return 0;\n }\n\n var queue = new Queue&lt;TreeNode&gt;();\n queue.Enqueue(root);\n int sum = 0;\n\n while (queue.Count() &gt; 0)\n {\n sum = 0;\n\n for (int i = queue.Count() - 1; i &gt;= 0; i--) \n {\n TreeNode curr = queue.Dequeue();\n sum += curr.val;\n\n if (curr.left != null) \n {\n queue.Enqueue(curr.left);\n }\n\n if (curr.right != null)\n {\n queue.Enqueue(curr.right);\n }\n }\n }\n\n return sum;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T05:54:12.437", "Id": "240320", "ParentId": "240306", "Score": "2" } }, { "body": "<p>Rename <code>DFS</code> to <code>DeepestLeavesSum</code>.</p>\n\n<p>Extract <code>depth + 1</code> to variable. </p>\n\n<p>In here <code>else if (depth + 1 == maxDepth)</code> the <code>else</code> is reduant.</p>\n\n<p>The order of <code>depth + 1</code> and <code>maxDepth</code> is different between the Ifs. One time <code>maxDepth</code> is on the left side and other time on the right side.</p>\n\n<p>Usually, when writing recursion, you return the value and not store it in the class. </p>\n\n<p>If you call <code>DeepestLeavesSum</code> twice with the same object the second call will return wrong results because it will use <code>sum</code> and <code>maxDepth</code> of the first call. <strong>A good practice is avoiding saving state.</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T11:09:01.490", "Id": "240333", "ParentId": "240306", "Score": "3" } } ]
{ "AcceptedAnswerId": "240320", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T20:45:47.907", "Id": "240306", "Score": "3", "Tags": [ "c#", "programming-challenge", "binary-tree" ], "Title": "LeetCode: Deepest Leaves Sum C#" }
240306
<p>I've spent the past few days writing a python based client that allows you to locally encrypt your message and send it through Gmail. The encryption scheme is based off of hybrid RSA/AES encryption, where the message body is encrypted with AES and the one time session key is RSA PKCS1 OEAP. It also provides valdation of the sender by hashing and signing the hash with your private key. For this to run it needs pycryptodome but it's imported as Crypto, as well as less secure connections need to be enabled on the Gmail account. Any feedback would be greatly appreciated.</p> <pre><code>"""This is a wrapper for gmail to be able to send emails encrypted locally with 256 bit AES and 4096 bit RSA hybrid encryption.""" import email import imaplib import pickle import smtplib import socket from getpass import getpass from Crypto.Hash import SHA512 from Crypto.Cipher import PKCS1_OAEP from Crypto.Cipher import AES from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Signature import pss # Needs pycryptodome def logo(): """Opening screen prompt""" print(' __ ___ _ __ ______ __') print(' / |/ /___ _(_) / / ____/______ ______ / /_') print(' / /|_/ / __ `/ / / / / / ___/ / / / __ \/ __/') print(' / / / / /_/ / / / / /___/ / / /_/ / /_/ / /_ ') print('/_/ /_/\__,_/_/_/ \____/_/ \__, / .___/\__/') print(' /____/_/ ') def usr_help(): """Displays help message.""" print('Getting Started:\n' '\n' ' -First you must generate your keys.\n' ' -After that you must share your public key with who ever\n' ' you intend to communicate with, they must also share their\n' ' public key with you.\n' '\n' '(1) Send email - This allows you to send emails to people you have\n ' ' shared and recieved public keys from.\n' '\n' '(2) Check email - This loads your inbox and allows you to select a message\n' ' to read\n' '\n' '(3) Delete emails - This loads your inbox and allows you to select emails\n' ' to delete\n' '\n' '(4) Import public key - This loads any public key sent to your inbox.\n' '\n' '(5) Share public key - This sends your public key to someones email to \n' ' to be imported and used\n' '\n' '(6) Generate key pair - This generates your public and private key pair.\n' ' This must be done when your first use mail crypt.\n' ' If you generate a new key pair it will overwrite \n' ' your existing key pair, so you will not be able to\n' ' read old emails and you will have to re-share your\n' ' public key\n' '\n' '(7) Help - Displays this message.\n' '\n' '(00) Exit - This closes connectins, logs out, and ends mail cyrpt.\n' '\n') input("Press any key to return to the menu.") def splash(): """front page gets Gmail login info username and password is passed in as string and returned to the main loop""" print('\n' * 8) print("Welcome to MailCrypt the secure Gmail wrapper.") print('Connecting...') username = input("Enter email address to use.\n") passwd = getpass() return username, passwd def load_inbox(imap_server_instance): """loads emails from inbox. Opens a connection to the Gmail IMAP server, should be able to swap that with any email provider that has an IMAP sever that can interface with the imaplib module. By default it loads only the inbox folder. Calls the decrypt_msg function to decrypt the cyher text email""" try: imap_server_instance.select('inbox') _, data = imap_server_instance.uid('search', None, 'ALL') data = data[0].split() for item in data: # Loops through all emails in inbox and displays there UID and who sent it. _, email_data = imap_server_instance.uid('fetch', item, '(RFC822)') raw = email_data[0][1] msg = email.message_from_bytes(raw) print('UID:', item.decode(), end=" From: ") print(msg['From']) msg_to_fetch = input('What message do you want to read? (UID)\n') _, email_data = imap_server_instance.uid('fetch', msg_to_fetch, '(RFC822)') raw = email_data[0][1] msg = email.message_from_bytes(raw) # The call to decrypt_msg function clear_msg, authentic, sig_stat = decrypt_msg(msg.get_payload(), msg['From']) if authentic: print('Message tag valid') else: print('Message tag INVALID!') if sig_stat: print('Message signature is valid.') else: print('Message signature INVALID!') print(clear_msg) input('Press any key to return to the menu.') except imaplib.IMAP4.error: print("Error please try again. (005)") def delete_email(imap_server_instance): """Moves email to deleted folder and deletes.""" uids = [] try: imap_server_instance.select('inbox') _, data = imap_server_instance.uid('search', None, 'ALL') data = data[0].split() for item in data: # Loops through all emails in inbox and displays there UID and who sent it. _, email_data = imap_server_instance.uid('fetch', item, '(RFC822)') raw = email_data[0][1] msg = email.message_from_bytes(raw) uids.append(item.decode()) print('UID:', item.decode(), end=" From: ") print(msg['From']) except imaplib.IMAP4.error: print("Error please try again. (005)") while True: email_to_delete = input("What email would you like to delete?(UID)\n Enter 00 to exit.\n") if email_to_delete in uids: imap_server_instance.uid('store', email_to_delete, '+X-GM-LABELS', '(\\Trash)') elif email_to_delete == '00': imap_server_instance.expunge() break else: print('Invalid choice!') def share_public_key(username, smtp_server_instance): """Shares your curently stored public key""" recipient = input('Enter email to send public key to.\n') with open('my_public_key.pem', 'r') as public_key_save: public_key_string = public_key_save.read() try: smtp_server_instance.sendmail(username, recipient, public_key_string) print('email sent') except smtplib.SMTPRecipientsRefused: print("Could not reach recipients. (003)") except smtplib.SMTPDataError: print("Unknown error. (004)") def send_email(): """Generates the email but doesent send Calls the encrypt_msg function""" print('Enter destination email address.') recipient = input() print('Type your message here, press enter to send.') msg_body = input() enc_msg_body = encrypt_msg(msg_body.encode(), recipient) return enc_msg_body, recipient def import_public_key(imap_server_instance): """Imports public key from inbox by logging in and scaning all emails for the key word 'PUBLIC', newer keys found will over write the older keys in the public key dictionary and file Calls the public_key_store function""" print('Updating public keys.') try: imap_server_instance.select('inbox') _, data = imap_server_instance.uid('search', None, 'ALL') data = data[0].decode().split() for item in data: _, email_data = imap_server_instance.uid('fetch', item, '(RFC822)') raw = email_data[0][1].decode() msg = email.message_from_string(raw) if 'PUBLIC' in msg.get_payload(): public_key_store(msg['From'], msg.get_payload()) except imaplib.IMAP4.error: print('Unexpected error. (005)') def send(username, recipient, msg_body, smtp_server_instance): """Opens connection to gmail smtp server and sends the email""" try: smtp_server_instance.sendmail(username, recipient, msg_body) print('email sent') except smtplib.SMTPRecipientsRefused: print("Could not reach recipients. (003)") except (smtplib.SMTPDataError, smtplib.SMTPSenderRefused): print("Unknown error. (004)") def generate_keys(): """This uses the pycrypt RSA module to create private and public keys, the RSA.generate key length can be changed for more or less secuity. (must be expont of 256) Calls public_key_store func""" while True: if input('Generating a new set of keys will permainatly delete your old ones.\n ' 'Enter y to continue\n').lower() != 'y': print('Exiting.') break print('Generating new key pair.') private_key = RSA.generate(4096) public_key = private_key.publickey() with open('my_public_key.pem', 'wb') as public_key_save, \ open('private_key.pem', 'wb') as private_key_save: public_key_save.write(public_key.export_key('PEM')) private_key_save.write(private_key.export_key('PEM', passphrase=getpass('Enter password to secure private key.\n'))) return None def encrypt_msg(msg_body, recipient): """uses public key retrieve function to pull public key out of saved keys""" publickey = public_key_retrieve(recipient) session_key = get_random_bytes(32) if publickey: aes_cipher = AES.new(session_key, AES.MODE_EAX) nonce = aes_cipher.nonce aes_cipher_text, tag = aes_cipher.encrypt_and_digest(msg_body) rsa_cipher = PKCS1_OAEP.new(publickey) enc_session_key = rsa_cipher.encrypt(session_key) try: with open('private_key.pem', 'r') as private_key_save: privatekey = RSA.import_key(private_key_save.read(), passphrase=getpass('\nEnter password to unlock private key.')) msg_hash = SHA512.new(msg_body) signature = pss.new(privatekey).sign(msg_hash) except ValueError: return 'Invalid private key or password.\n' full_msg = aes_cipher_text.hex() + ' ' + tag.hex() + ' ' + nonce.hex() + ' ' + enc_session_key.hex() + ' ' + signature.hex() return full_msg print('No public key for that email is stored.') return None def decrypt_msg(full_msg, sender_publickey): """decrypts message imported from your inbox index of full_msg components in split list 0 aes_cipher_text 1 tag 2 nonce 3 enc_session_key 4 signature """ seperated_msg = full_msg.split(' ') # Encodes, and converts items in list from hex to bytes for item in enumerate(seperated_msg): seperated_msg[item[0]] = seperated_msg[item[0]].encode().fromhex(seperated_msg[item[0]]) try: with open('private_key.pem', 'r') as private_key_save: privatekey = RSA.import_key(private_key_save.read(), passphrase=getpass('Enter password to unlock private key.')) decrypt = PKCS1_OAEP.new(privatekey) psk = decrypt.decrypt(seperated_msg[3]) except ValueError: return 'Invalid private key or password.\n', False, False aes_cipher = AES.new(psk, AES.MODE_EAX, nonce=seperated_msg[2]) clear_text = aes_cipher.decrypt(seperated_msg[0]) try: aes_cipher.verify(seperated_msg[1]) authentic = True except ValueError: authentic = False msg_hash = SHA512.new(clear_text) valid_sig = pss.new(public_key_retrieve(sender_publickey)) try: valid_sig.verify(msg_hash, seperated_msg[4]) sig_stat = True except ValueError: sig_stat = False return clear_text, authentic, sig_stat def public_key_store(email_address, new_public_key): """Handles storeing and updating stored public keys""" try: # Tries to open existing file with open('public_key_bank.pkl', 'rb') as public_key_file: public_key_bank = pickle.load(public_key_file) except FileNotFoundError: public_key_bank = {} public_key_bank[email_address] = new_public_key with open('public_key_bank.pkl', 'wb') as public_key_file: pickle.dump(public_key_bank, public_key_file) def public_key_retrieve(email_address): """retreives public key from saved""" try: with open('public_key_bank.pkl', 'rb') as public_key_file: public_key_bank = pickle.load(public_key_file) if email_address in public_key_bank: requested_key = public_key_bank[email_address] requested_key = RSA.import_key(requested_key) return requested_key return False except FileNotFoundError: print('Public key file has not been created. (006)') print('\n' * 100) logo() try: with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp_server, \ imaplib.IMAP4_SSL('imap.gmail.com') as imap_server: while True: USERNAME, PASSWD = splash() try: smtp_server.ehlo() smtp_server.login(USERNAME, PASSWD) imap_server.login(USERNAME, PASSWD) break except smtplib.SMTPAuthenticationError: print('Incorrect username or password! (001)') except imaplib.IMAP4.error: print('Incorrect username or password! (002)') except (OSError, smtplib.SMTPServerDisconnected, imaplib.IMAP4_SSL.error): print('Conection error. (008)') break while True: print('\n' * 100) logo() print('\n' * 5) OPTION = input('What would you like to do\n' '(1) Send email\n' '(2) Check email\n' '(3) Delete email\n' '(4) Import public key\n' '(5) Share public key\n' '(6) Generate key pair.\n' '(7) Help\n' '(00) Exit\n') print('\n' * 100) if OPTION == '1': # Send email CIPHER_TEXT, DESTINATION_EMAIL = send_email() send(USERNAME, DESTINATION_EMAIL, CIPHER_TEXT, smtp_server) elif OPTION == '2': # Check email load_inbox(imap_server) elif OPTION == '3': # Delete email delete_email(imap_server) elif OPTION == '4': # Import public key import_public_key(imap_server) elif OPTION == '5': # Share public key share_public_key(USERNAME, smtp_server) elif OPTION == '6': # Generate key pair generate_keys() elif OPTION == '7': usr_help() elif OPTION == '00': # End program loop and logs out of smtp/imap servers try: smtp_server.quit() imap_server.close() imap_server.logout() except imaplib.IMAP4.error: pass PASSWD = '0000000000000000000000000' break else: print('Invalid option!') except socket.gaierror: print('Please check your network connection and try again. (007)') except KeyboardInterrupt: pass </code></pre>
[]
[ { "body": "<p>You should separate the UI from the actual logic of the program.<br>\nWhilst a nice UI is cool I believe that it's impeding your ability to structure your code properly.\nAnd so I'd recommend making Mail Crypt a Python library first, and a CLI second.</p>\n\n<p>Since this is a library we want:</p>\n\n<ul>\n<li>Any errors raised to pass through to the user.</li>\n<li>No <code>print</code> statements.</li>\n<li>All values to be provided to the method. (not inside the method)</li>\n</ul>\n\n<p>Additionally since <code>load_inbox</code>, <code>delete_email</code> and <code>import_public_key</code> require the same code we can make an <code>Email</code> class to interact with them.</p>\n\n<p>This can get the following code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class MailCrypt:\n def __init__(self, smtp, imap):\n self.smtp = smtp\n self.imap = imap\n\n def send(self, account, recipient, message):\n message = encrypt_msg(message.encode(), recipient)\n self.smtp.sendmail(account, recipient, message)\n\n def emails(self):\n self.imap.select('inbox')\n uids = self.imap.uid('search', None, 'ALL')\n for uid in data[1][0].split():\n email = self.imap.uid('fetch', uid, '(RFC822)')\n yield Email(\n self.imap,\n email.message_from_bytes(email[1][0][1]),\n uid.decode(),\n )\n\n def delete_all(self):\n self.imap.expunge()\n\n def share_public_key(self, account, recipient):\n with open('my_public_key.pem', 'r') as f:\n public_key = f.read()\n smtp_server_instance.sendmail(account, recipient, public_key)\n\n def generate_keys(self, passphrase):\n private_key = RSA.generate(4096)\n public_key = private_key.publickey()\n\n with open('my_public_key.pem', 'wb') as fpub, \\\n open('private_key.pem', 'wb') as fpri:\n fpub.write(public_key.export_key('PEM'))\n fpri.write(private_key.export_key('PEM', passphrase=passphrase))\n\n\nclass Email:\n def __init__(self, imap, email, uid):\n self.email = email\n self.uid = uid\n\n def read(self):\n return decrypt_msg(self.email.get_payload(), self.email['From'])\n\n def delete(self):\n self.imap.uid('store', self.uid, '+X-GM-LABELS', '(\\\\Trash)')\n\n def import_key(self):\n payload = self.email.get_payload()\n if 'PUBLIC' in payload:\n public_key_store(msg['From'], payload)\n</code></pre>\n\n<p>This is, I hope, clearly much easier to read and work with than the code you have.</p>\n\n<p>This doesn't cover all of the functionality that you had before.\nFor example I've only written the code to import the key from one email.\nI have also not written the select an email code that you had duplicated over multiple functions.</p>\n\n<p>However to implement these is really quite simple:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def import_all(mc):\n for email in mc.emails():\n email.import_key()\n\n\ndef select_email(mc):\n emails = {e.uid: e for e in mc.emails()}\n for email in emails.values():\n print('UID: {} FROM: {}'.format(email.uid, email.email['From']))\n uid = input('What email would you like? ')\n return emails[uid]\n</code></pre>\n\n<p>The public key store should:</p>\n\n<ul>\n<li>Be a class.</li>\n<li>Store the keys in memory.</li>\n<li>Raise an error if the key you're asking for is not in the store.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>class PublicStore:\n def __init__(self, location):\n self._location = location\n self._keys = self._load()\n\n def _load(self):\n try:\n with open(self._location, 'rb') as f:\n return pickle.load(f)\n except FileNotFoundError:\n return {}\n\n def store(email, key):\n self._keys[email] = key\n with open(self._location, 'wb') as f:\n pickle.dump(self._keys, f)\n\n def get(email):\n return RSA.import_key(self._keys[email])\n</code></pre>\n\n<p>Your encryption and decryption can be improved by:</p>\n\n<ul>\n<li>Moving the personal key into a class.</li>\n<li>Getting the personal and sender keys outside of the encrypt or decrypt functions.</li>\n<li>Removing a lot of unneeded variables.</li>\n<li>You can use a comprehension to build the <code>seperated_msg</code>.</li>\n<li><p>You should let errors propagate. This is not the correct place to handle them.</p>\n\n<p>If you're not a fan of this then you can alternately create another class and handle the verification in one or two of its methods.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>class PersonalKey:\n def __init__(self, public_location, private_location):\n self._public_location = public_location\n self._private_location = private_location\n\n def get_public(self, passphrase):\n with open(self._public_location, 'r') as f:\n return RSA.import_key(f.read(), passphrase=passphrase)\n\n def get_private(self, passphrase):\n with open(self._private_location, 'r') as f:\n return RSA.import_key(f.read(), passphrase=passphrase)\n\n\ndef encrypt_msg(message, sender_key, personal_key):\n aes_cipher = AES.new(get_random_bytes(32), AES.MODE_EAX)\n aes_cipher_text, tag = aes_cipher.encrypt_and_digest(message)\n return (\n aes_cipher_text.hex()\n + ' ' + tag.hex()\n + ' ' + aes_cipher.nonce.hex()\n + ' ' + PKCS1_OAEP.new(sender_key).encrypt(session_key).hex()\n + ' ' + pss.new(personal_key).sign(SHA512.new(message)).hex()\n )\n\n\ndef decrypt_msg(message, sender_key, personal_key):\n seperated_msg = [\n value.encode().fromhex(value)\n for value in message.split(' ')\n ]\n aes_cipher = AES.new(\n PKCS1_OAEP.new(personal_key).decrypt(seperated_msg[3]),\n AES.MODE_EAX,\n nonce=seperated_msg[2],\n )\n clear_text = aes_cipher.decrypt(seperated_msg[0])\n aes_cipher.verify(seperated_msg[1])\n pss.new(sender_key).verify(SHA512.new(clear_text), seperated_msg[4])\n return clear_text\n</code></pre>\n\n<p>Unfortunately the answer has consumed enough of my time. The above code my not work, and the changes I made in each section conflict with each-other.</p>\n\n<p>Please can you take the above answer and complete the final steps getting the code to work together. When you're doing this with the above functions you are not allowed to use <code>print</code>, <code>getpass</code> or <code>input</code> in the above. However when, effectively, rebuilding the CLI you can use these functions until your heart's content.</p>\n\n<p>Once you've made your changes please come back and post another question :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T17:34:20.837", "Id": "240350", "ParentId": "240310", "Score": "3" } } ]
{ "AcceptedAnswerId": "240350", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T21:52:24.277", "Id": "240310", "Score": "2", "Tags": [ "python", "python-3.x", "cryptography", "email" ], "Title": "Mail Crypt CLI encrypted email wrapper for Gmail" }
240310
<p><strong>> Exercise 1: Design a database connection</strong></p> <blockquote> <p>To access a database, we need to open a connection to it first and close it once our job is done. Connecting to a database depends on the type of the target database and the database management system (DBMS). For example, connecting to a SQL Server database is different from connecting to an Oracle database. But both these connections have a few things in common:</p> <p>• They have a connection string\ • They can be opened\ • They can be closed\ • They may have a timeout attribute (so if the connection could not be opened within the timeout, an exception will be thrown).\</p> <p>Your job is to represent these commonalities in a base class called DbConnection. This class should have two properties:</p> <p>ConnectionString : string\ Timeout : TimeSpan</p> <p>A DbConnection will not be in a valid state if it doesn’t have a connection string. So you need to pass a connection string in the constructor of this class. Also, take into account the scenarios where null or an empty string is sent as the connection string. Make sure to throw an exception to guarantee that your class will always be in a valid state.</p> <p>Our DbConnection should also have two methods for opening and closing a connection. We don’t know how to open or close a connection in a DbConnection and this should be left to the classes that derive from DbConnection. These classes (eg SqlConnection or OracleConnection) will provide the actual implementation. So you need to declare these methods as abstract.</p> <p>Derive two classes SqlConnection and OracleConnection from DbConnection and provide a simple implementation of opening and closing connections using Console.WriteLine(). In the real-world, SQL Server provides an API for opening or closing a connection to a database. But for this exercise, we don’t need to worry about it.</p> </blockquote> <p><strong>>Exercise 2: Design a database command</strong></p> <blockquote> <p>Now that we have the concept of a DbConnection, let’s work out how to represent a DbCommand.</p> <p>Design a class called DbCommand for executing an instruction against the database. A DbCommand cannot be in a valid state without having a connection. So in the constructor of this class, pass a DbConnection. Don’t forget to cater for the null.</p> <p>Each DbCommand should also have the instruction to be sent to the database. In case of SQL Server, this instruction is expressed in T-SQL language. Use a string to represent this instruction. Again, a command cannot be in a valid state without this instruction. So make sure to receive it in the constructor and cater for the null reference or an empty string.</p> <p>Each command should be executable. So we need to create a method called Execute(). In this method, we need a simple implementation as follows:</p> <p>Open the connection. Run the instruction. Close the connection.</p> <p>Note that here, inside the DbCommand, we have a reference to DbConnection. Depending on the type of DbConnection sent at runtime, opening and closing a connection will be different. For example, if we initialize this DbCommand with a SqlConnection, we will open and close a connection to a Sql Server database. This is polymorphism. Interestingly, DbCommand doesn’t care about how a connection is opened or closed. It’s not the responsibility of the DbCommand. All it cares about is to send an instruction to a database.</p> <p>For running the instruction, simply output it to the Console. In the real-world, SQL Server (or any other DBMS) provides an API for running an instruction against the database. We don’t need to worry about it for this exercise.</p> <p>In the main method, initialize a DbCommand with some string as the instruction and a SqlConnection. Execute the command and see the result on the console.</p> <p>Then, swap the SqlConnection with an OracleConnection and see polymorphism in action</p> </blockquote> <p>I know that is a lot to read for reference. Not sure why this was worded the way it was. At this point I'm sure I will learn more here than whatever the intentions of this was from the author. All I gather is that this was an attempt to teach abstract and virtual methods. To my knowledge everything works here and I would be grateful to just get a better understanding of this and perhaps shown a better approach to this than whatever the author had in mind.</p> <p><strong>DbCommand.cs</strong></p> <pre><code>using System; namespace DesignDatabaseConnection { public class DbCommand { private readonly DbConnection _dbconnection; public DbConnection Dbconnection =&gt; _dbconnection; private readonly string _instruction; internal DbCommand(string instruction, DbConnection dbConnection) { if (string.IsNullOrEmpty(_instruction)) throw new ArgumentNullException(); _instruction = instruction; _dbconnection = dbConnection; } public void Execute() { Dbconnection.Open(); Console.WriteLine("Running the instruction"); Dbconnection.Close(); } } } </code></pre> <p><strong>DbConnection.cs</strong></p> <pre><code>using System; namespace DesignDatabaseConnection { public abstract class DbConnection { private readonly string _connectionString; private readonly TimeSpan _timeout; public string ConnectionString =&gt; _connectionString; public TimeSpan Timeout =&gt; _timeout; public DbConnection(string connectionString, TimeSpan timeout) { if (string.IsNullOrEmpty(connectionString)) throw new ArgumentNullException(); _connectionString = connectionString; _timeout = timeout; } public abstract void Open(); public abstract void Close(); } } </code></pre> <p><strong>OracleConnection.cs</strong></p> <pre><code>using System; namespace DesignDatabaseConnection { public class OracleConnection : DbConnection { public OracleConnection(string connectionString, TimeSpan timeout) : base(connectionString, timeout) { } public override void Open() =&gt; Console.WriteLine("Database is open."); public override void Close() =&gt; Console.WriteLine("Database is closed."); } } </code></pre> <p><strong>SqlConnection.cs</strong></p> <pre><code>using System; namespace DesignDatabaseConnection { public class SqlConnection : DbConnection { public SqlConnection(string connectionString, TimeSpan timeout) : base(connectionString, timeout) { } public override void Open() =&gt; Console.WriteLine("Database is open."); public override void Close() =&gt; Console.WriteLine("Database is closed."); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T23:00:48.653", "Id": "471320", "Score": "0", "body": "I suggest you see adapter abd bridge pattern and also how the .Net framework implemented it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T08:10:26.123", "Id": "471345", "Score": "0", "body": "I'll give it a read. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T21:10:13.073", "Id": "471420", "Score": "0", "body": "@Gilad was this the purpose of pointing that out for me to read [The main difference between an adaptor and a bridge pattern, is that a bridge pattern serves to decouple an abstraction class from its implementation, and an adaptor pattern converts the interface between classes with less inheritance.](https://www.codeproject.com/Articles/10053/Refactoring-To-Patterns-Bridge-and-Adapter-Pattern)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T21:20:39.903", "Id": "471421", "Score": "0", "body": "@Miiliorn the purpose is to point out how this is already done in the .Net framework and how it should be done in order of preserving S.O.L.I.D principles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T19:46:25.327", "Id": "471687", "Score": "0", "body": "I assume there is nothing left to add or improve upon?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-10T21:53:58.423", "Id": "240311", "Score": "3", "Tags": [ "c#", "beginner", "object-oriented", "polymorphism" ], "Title": "POLYMORPHISM - Design a database connection and command" }
240311
<p>I'm using ImageProcessor in C# and I can't come up with a way to make a generic method out of its methods as to avoid writing the same code more than once.</p> <p>Say, I have two methods, crop and resize.</p> <pre><code> public Image Resize(Image image, int width, int height) { // Create a Image to be returned after being scaled, call it resizedImage: Image resizedImage; // Create a Size for the image to be scaled to, call it size: var size = new Size(width, height); // Create an ImageFactory to process the image, call it imageFactory: using (var imageFactory = new ImageFactory(preserveExifData: true)) { // Create a MemoryStream to temporarily store the processed image, call it imageStream: using (var imageStream = new MemoryStream()) { // Scale the image using the ImageProcessor library // Load the image to be resized, resize it and save it to the MemoryStream: imageFactory.Load(image) .Resize(size) .Save(imageStream); // Assign the processed image to the previously declared resizedImage: resizedImage = Image.FromStream(imageStream); } } // Return the resized image: return resizedImage; } public Image Crop(Image image, float left, float top, float right, float bottom, bool isModePercentage = true) { // Create a Image to be returned after being cropped, call it croppedImage: Image croppedImage; // Create a CropMode to specify what cropping method to use (Percentage or Pixels), call it cropMode // If isModePercentage = true we use CropMode.Percentage, otherwise use CropMode.Pixels: var cropMode = isModePercentage ? CropMode.Percentage : CropMode.Pixels; // Create a CropLayer to specify how and how much the image should be cropped, call it cropLayer: var cropLayer = new CropLayer(left, top, right, bottom, cropMode); // Create an ImageFactory to process the image, call it imageFactory: using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true)) { // Create a MemoryStream to temporarily store the processed image, call it imageStream: using (MemoryStream imageStream = new MemoryStream()) { // Crop the image using the ImageProcessor library // Load the image to be cropped, crop it and save it to the MemoryStream: imageFactory.Load(image) .Crop(cropLayer) .Save(imageStream); // Assign the processed image to the previously declared croppedImage: croppedImage = Image.FromStream(imageStream); } } // Return the cropped image: return croppedImage; } </code></pre> <p>How can I avoid having to instantiate imagefactory and memory stream multiple times, reducing the size of my methods and avoid to write the same code twice?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T13:09:00.343", "Id": "472027", "Score": "0", "body": "Your title should state what your code does, not what you want out of a review. Please read the relevant Help pages." } ]
[ { "body": "<p>Well, it works well, but as you said, it can be optimized</p>\n\n<h3>Review:</h3>\n\n<p>You are commenting each line which is not good, only comment meaningful code sections. Commonly the names of the functions and variables you are calling is intuitive enough to know how the code is working. When it is insufficient then it is the moment to comment.</p>\n\n<h3>Refactoring:</h3>\n\n<p>You may create two class fields (<code>ImageFactory</code>,<code>MemoryStream</code>) and work with these.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private ImageFactory imageFactory;\nprivate MemoryStream imageStream;\n\npublic [ClassName]() //the constructor if doubts\n{\n imageFactory = ImageFactory(preserveExifData: true);\n imageStream = MemoryStream();\n}\n\npublic Image Resize(Image image, int width, int height)\n{\n imageFactory.Load(image).Resize(new Size(width, height)).Save(imageStream);\n return Image.FromStream(imageStream);\n}\n\npublic Image Crop(Image image, float left, float top, float right, float bottom,\n bool isModePercentage = true)\n{\n var cropMode = isModePercentage ? CropMode.Percentage : CropMode.Pixels;\n var cropLayer = new CropLayer(left, top, right, bottom, cropMode);\n\n imageFactory.Load(image).Crop(cropLayer).Save(imageStream);\n\n return Image.FromStream(imageStream);\n}\n</code></pre>\n\n<p>Hope it has been helpful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T09:54:13.533", "Id": "471361", "Score": "0", "body": "Disposing imageStream and imageFactory is missing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T23:12:50.060", "Id": "471969", "Score": "0", "body": "@shanif could you check the answer I posted and tell me what you think about it? thanks!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T02:09:27.097", "Id": "240315", "ParentId": "240312", "Score": "3" } }, { "body": "<h2>Refactor</h2>\n\n<p>I extracted the common code to functions.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private ImageFactory CreateImageFactory(Image image)\n{\n var imageFactory = new ImageFactory(preserveExifData: true) );\n return imageFactory.Load(image);\n}\n\nprivate static Image GetImage(this ImageFactory imageFactory)\n{\n Image res;\n using (var imageStream = new MemoryStream())\n {\n res = Image.FromStream(imageStream);\n }\n\n return res;\n}\n\npublic Image Resize(Image image, int width, int height)\n{\n Image resizedImage;\n var size = new Size(width, height);\n using (var imageFactory = CreateImageFactory(image))\n { \n resizedImage = imageFactory.Resize(size).GetImage();\n }\n\n return resizedImage;\n}\n\npublic Image Crop(Image image, float left, float top, float right, float bottom, bool isModePercentage = true)\n{\n Image croppedImage;\n var cropMode = isModePercentage ? CropMode.Percentage : CropMode.Pixels;\n var cropLayer = new CropLayer(left, top, right, bottom, cropMode);\n using (var imageFactory = CreateImageFactory(image))\n { \n croppedImage = imageFactory.Crop(cropLayer).GetImage();\n }\n return croppedImage;\n}\n</code></pre>\n\n<h2>Code Review</h2>\n\n<p>As said before you commenting each line while your code is readable and speak for itself. </p>\n\n<p>Some people consider <strong>comments</strong> as a <strong>code smell</strong>. </p>\n\n<p>For example, while refactoring the code, it was very easy to lose the connection between the code the corresponding comment.</p>\n\n<p>Besides that I think your code is readable, you have good names and it easy to understand.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T10:23:21.590", "Id": "240331", "ParentId": "240312", "Score": "2" } }, { "body": "<p>I kept looking into this and discovered an answer that might be better than the one I previously accepted</p>\n\n<pre><code> public Image ProcessImage(Image image, Func&lt;ImageFactory, ImageFactory&gt; process)\n {\n using (var imageFactory = new ImageFactory(preserveExifData: true))\n {\n using (var imageStream = new MemoryStream())\n {\n ImageFactory loadResult = imageFactory.Load(image);\n ImageFactory processResult = process(loadResult);\n processResult.Save(imageStream);\n\n imageStream.Position = 0;\n return Image.FromStream(imageStream);\n }\n }\n }\n // And then get the result like so //////////////////////////////////\n var resultResize =_imageEditor.ProcessImage(_image, im =&gt; im.Resize(size));\n var resultRotate =_imageEditor.ProcessImage(_image, im =&gt; im.Rotate(degrees));\n</code></pre>\n\n<p>I think this looks way cleaner like this - and it's super short.</p>\n\n<p>I don't really want to accept my own answer but unless someone comes up with a reason this is wrong/bad I'll keep it like this for now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T07:43:56.320", "Id": "471991", "Score": "1", "body": "I thought of doing something like that, don't know why I decided it will be too much effort. What good about this implementation is that you can chain how much operations that you want. Well done! " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T07:50:50.023", "Id": "471993", "Score": "1", "body": "imageStream.Position = 0; This line dide exist in the original implementation, I wonder why you added it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T07:52:42.493", "Id": "471994", "Score": "1", "body": "Please make sure returning from inside the using is ok in terms of releasing the resource. In the original implementation you didn't have return inside the using." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:59:14.747", "Id": "472077", "Score": "1", "body": "@shanif I'm glad I managed to do something clean, didn't know about Func<> and lambda expressions before this and was a good learning experience. The imageStream.Position I took from another answer somewhere but tbh I'm not sure anymore why. Regarding returning inside the using, it's OK because it's essentially a try/finally block, so even if I return \"inside the try\" it will still run the \"finally\". Thanks again for your review!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T23:06:48.453", "Id": "240601", "ParentId": "240312", "Score": "3" } } ]
{ "AcceptedAnswerId": "240601", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T00:36:40.360", "Id": "240312", "Score": "4", "Tags": [ "c#" ], "Title": "Is it possible to make a generic method out of this, or at least separate them?" }
240312
<p><a href="https://i.stack.imgur.com/JZ2Uz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JZ2Uz.png" alt="enter image description here"></a></p> <p>My question concerns problem (b). This is my attempt:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>def shift_left(D,k) for j = 0 to k: x_current = D.delete_first() //this remove and return first item D.insert_last(x_current) return D</code></pre> </div> </div> </p> <p>The answer key was given the following for the solution. I am just trying to figure out if my solution is correct. I know this solution key uses recursion. Does my solution work as well?</p> <p><a href="https://i.stack.imgur.com/P3slU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P3slU.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T16:23:57.180", "Id": "474256", "Score": "0", "body": "You should also make sure your code is free from compiler errors (there's one in your code now)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T20:39:51.613", "Id": "474278", "Score": "0", "body": "That is why you downvote?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T22:18:05.237", "Id": "474287", "Score": "0", "body": "It's only temporary." } ]
[ { "body": "<p>Your code solves the problem in a desired way, it is concise which is good.</p>\n<h3>Some comments</h3>\n<p>Your design limits the shifting to <code>k &gt; len(D) - 1</code>, if it is your intention, then it is perfect otherwise this could be solved by doing</p>\n<pre class=\"lang-py prettyprint-override\"><code>def shift_left(D, k):\n k = k % len(D) #the modulus makes k to be in the positive integer domain\n if (k &lt; 1):\n return\n x = D.delete_first()\n D.insert_last(x)\n #it could be done with a for and saves recursively comparing k each time\n shift_left(D, k-1)\n</code></pre>\n<h3>An alternative</h3>\n<pre class=\"lang-py prettyprint-override\"><code>def shift_left(D, k):\n k = k % len(D)\n if (k &lt; 1):\n return\n #avoids recursion, which saves recursive calls and passing parameters\n #(could be done using a while)\n for i in range(0,k)\n x = D.delete_first()\n D.insert_last(x)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T01:41:18.090", "Id": "240314", "ParentId": "240313", "Score": "2" } } ]
{ "AcceptedAnswerId": "240314", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T00:45:19.210", "Id": "240313", "Score": "2", "Tags": [ "python", "algorithm" ], "Title": "Describing algorithms to implement higher level operations in terms of the lower level operations" }
240313
<p>I wanted to get some feedback concerning the program. It's console based and in C#. If I should try to add constraints like making sure only the 4 questions shown are able to be typed in and nothing else or uses a number system to retrieve and set answers and if to add a randomization. If I am to add randomization how am I to do so with string and methods? Was thinking of loading it from an external file where questions and answers would be read, randomized and printed.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Trivia_Game { class Questions { public void Question1() { List&lt;string&gt; Q1 = new List&lt;string&gt;(); Q1.Add("Paris"); Q1.Add("Spain"); Q1.Add("England"); Q1.Add("Portugal"); string Answer1=""; string TrueAnswer = "Paris"; for (int i = 0; i &lt; Q1.Count; i++) { Console.Write(Q1[i] + ", "); } Console.WriteLine(); while (Answer1 != TrueAnswer) { Console.WriteLine("What is the Capital of France?"); Answer1 = Console.ReadLine(); Console.WriteLine(); if (Answer1 != TrueAnswer) { Console.WriteLine("Wrong answer"); Console.WriteLine(); } else { Console.WriteLine("Correct"); } } } } class Program { static void Main(string[] args) { Questions questions = new Questions(); questions.Question1(); Console.ReadKey(); } } } </code></pre>
[]
[ { "body": "<p>You can create a Question class which include the question, the answers, and the right answer.</p>\n\n<p>Then you create a list of questions hard coded / from file / from server ( what ever you want) </p>\n\n<p>Convert the code in Question 1 to be more generic and work with the Question class. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T20:15:42.493", "Id": "471416", "Score": "0", "body": "Thank you, I will do just that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T09:09:32.827", "Id": "240328", "ParentId": "240316", "Score": "1" } } ]
{ "AcceptedAnswerId": "240328", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T02:54:48.227", "Id": "240316", "Score": "2", "Tags": [ "c#", "game", "quiz" ], "Title": "Feedback on a Small Trivia Game in C#" }
240316
<p>I’m a complete beginner. I was practicing from coding bat and the question was to create a function that will round 3 integers to the nearest 10 and then find their summation. I thought of a way to do it and it’s given in the picture below. Please help.</p> <pre><code>def round10(num): return # This will return the rounded number def sum(a,b,c) return round10(a) + round10(b) + round10(c) </code></pre> <p><a href="https://i.stack.imgur.com/XlLQ7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XlLQ7.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T07:31:56.123", "Id": "471343", "Score": "3", "body": "Welcome to Code Review. Code Review is a place to help improve your code after you have successfully implemented and tested it. Questions asking for advice on code yet to be written or implemented are off-topic for this site and will be closed. See [What topics can I ask about?](https://codereview.stackexchange.com/help/on-topic) for reference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T13:26:36.113", "Id": "471378", "Score": "1", "body": "Please include the code as actual code, not as a picture. Does or doesn't it work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T16:20:17.003", "Id": "471400", "Score": "0", "body": "Sorry about the picture. The code I wrote in the picture doesn’t work. I didn’t know that integers themselves were immutable. The answer given by Jono 2906 works perfectly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:28:05.317", "Id": "471443", "Score": "0", "body": "To note, the first close reason has a bad name in this case - Authorship of code. We know you're the author, however you haven't embedded the code into the question in a format all users can digest. For instance the bright background is causing my eyes to hurt when trying to read your image. This is only worse for our blind users that can't see." } ]
[ { "body": "<h2>There is a potential here to mangle type conversions</h2>\n\n<p>I noticed that you are trying to manipulate integers in ways only strings and other iterables can: both <code>len(num)</code> and <code>num[0]</code>/<code>num[-1]</code> will give you a <code>TypeError</code>. In order to prevent that from happening, you would need to first convert the number to a string and then to a <code>list</code>:</p>\n\n<pre><code>def round10(num):\n number = list(str(num))\n</code></pre>\n\n<p><a href=\"https://tio.run/##K6gsycjPM/7/PyU1TaEovzQvxdBAI680V9OKSwEIgKyk1CIFW4WczOISjeKSIrCcJliuoCgzrwTM/w/TaKrJBWMaGiDYJsYItrGJmeZ/AA\" rel=\"nofollow noreferrer\" title=\"Python 3 – Try It Online\">Try it online!</a></p>\n\n<p>However, a further problem arises from the fact that integers cannot be subtracted from strings (once again, <code>TypeError</code>), so each list item needs to be converted to an integer:</p>\n\n<pre><code>def round10(num):\n number = list(str(number))\n for i in range(len(number)): # Doable because num is a list\n number[i] = int(number[i])\n</code></pre>\n\n<p><a href=\"https://tio.run/##RY49DsIwDIX3nMISS7y1SmGoxMYtEENCXYgUnCo/A6cPIajE02e/52dv7/T0rEpZaIXgMy/jIDm/cBZQq5KhAGdwNiYZU2gaNm31ASxYhqD5QdIRy58dcYYDXLw2jsDQXedI3ySwEXRLavs9/2pv9YTlJP89iubZQp9i2f87othxHDpPqrOaTlg@\" rel=\"nofollow noreferrer\" title=\"Python 3 – Try It Online\">Try it online!</a></p>\n\n<p>Then, once all the logic has been applied, it needs to be converted back to an integer. This means that you would have to convert the list to a single string and call <code>int()</code> on that string:</p>\n\n<pre><code>def round10(num):\n number = list(str(num))\n for i in range(len(number)): # Doable because num is a list\n number[i] = int(number[i])\n\n if len(number) &lt; 2 and num &gt;= 5:\n number = [1, 0]\n\n elif len(number) &gt; 2 and number[-1] &gt;= 5:\n number[0] += 1\n number[-1] = 0\n\n else:\n number[0] -= 1\n number[-1] = 0\n\n final = \"\"\n for n in number:\n final += str(n)\n\n # Here, I'd use final = \"\".join([str(n) for n in number])\n\n return int(final)\n</code></pre>\n\n<p><a href=\"https://tio.run/##hZLBTsMwEETv@YpRe8AWLUpIyyEiPXGAb4hycMgGjMKmspMDXx9spzSQVsIHyzuefbbGPn717x2n41hTA9MNXCex4OFTZhHccKuKDHK02vbC9ibsybDXdAYammEUv5FoicVklzLDGk@dqlpCRa9qsORJ0BYqkEL/zC906Y7Q3ItzLaPg0Q1@cfGIeyiuA@yQY58tQI5SJBvEZdDDRO2CcZgZ/qhtUl5FFXGJ2xzJUvb@HHF0glu61rj9r7HRrFpXrlbnKNlHOXln5ORz9wjRn0JZ45kMbfByU8NHO8PuPjrNopjMS2op51QM9YPhEHnoluPR@OLnB@zdG/9VkvhC2qUXUrp7kHL8Bg\" rel=\"nofollow noreferrer\" title=\"Python 3 – Try It Online\">Try it online!</a></p>\n\n<p>As you can see, there is quite a potential to confuse all the types in use.</p>\n\n<h2>There are logic errors within your <code>if</code>-statements</h2>\n\n<p>If you go to the <strong>Try It Online!</strong> link from the above function, you'll see that there are issues with your logic:</p>\n\n<ol>\n<li>Numbers with more than one digit round incorrectly.</li>\n<li>The number <code>10</code> gets rounded to <code>0</code>.</li>\n<li>If the last digit is less than five, then the number gets rounded down too far.</li>\n<li><strong>Very important</strong>: If a number happens to round up to the next hundred (e.g. 599 -> 600), then there is no incrementation of the rest of the number.</li>\n</ol>\n\n<p>Below is a fixed version of your proposed method that works for numbers up to <code>194</code>:</p>\n\n<pre><code>def round10(num):\n number = list(str(num))\n for i in range(len(number)): # Doable because num is a list\n number[i] = int(number[i])\n\n if len(number) &lt; 2 and num &gt;= 5:\n number = [1, 0]\n\n elif len(number) &gt;= 2 and number[-1] &gt;= 5:\n number[-2] += 1\n number[-1] = 0\n\n else:\n number[-1] = 0\n\n final = \"\"\n for n in number:\n final += str(n)\n\n # Here, I'd use final = \"\".join([str(n) for n in number])\n\n return int(final)\n</code></pre>\n\n<p><a href=\"https://tio.run/##fZHBToQwEIbvPMVk92Abdw3dXUwg4smDPgPpocigNThsChx8emzLCkrNcmiYv/980/49f/XvLR3HscIaTDtQJWJGwyfPIrCf/SvRQA6N7nrW9cbvcb9XtwY0aAKj6A1Zg8QmO@cZbOGpVWWDUOKrGjp0JNAdKE/y/Qu/0NKO0NSzueaR9@gafnHhAQ6gqPKwxxySbAWylELsIJZe9ws2K4btmyFu1l7If1nF/iDhNgcR6MKdNo4u@A6zq45ak2psudnMqZFLbfIuvZPPDvQpX@6/hWc0uIOXmwpcigvs7qPVxIrJvKZKvgRgsB8M@XR9Nx/PxhU/j53Y5/yriDiQTsfQlZ4CLbkPpLAxTTkfvwE\" rel=\"nofollow noreferrer\" title=\"Python 3 – Try It Online\">Try it online!</a></p>\n\n<h3>Changes:</h3>\n\n<ul>\n<li><code>elif len(number) &gt; 2 and number[-1] &gt;= 5:</code> has been changed to <code>elif len(number) &gt;= 2 and number[-1] &gt;= 5:</code>. This fixes the issue where numbers with two or more digits do not round correctly.</li>\n<li>I have removed <code>number[0] -= 1</code> from the <code>else</code> block in order to address points 2 and 3</li>\n</ul>\n\n<p>Notice how I haven't addressed issue 4. That's because I feel like implementing such a system would be beyond the scope of the CodingBat challenge.</p>\n\n<h2>That's because there is a simpler way to do this</h2>\n\n<p>Indeed, I suggest that instead of relying on string manipulation, you utilise mathematics to do the rounding for you.</p>\n\n<h3>Use the modulus (<code>%</code>) operator</h3>\n\n<p>The <code>%</code> operator returns the remainder of the first number divided by the second. This can be used to see how far the number is from the nearest 10:</p>\n\n<pre><code>def round10(num):\n distance = num % 10\n</code></pre>\n\n<p><a href=\"https://tio.run/##K6gsycjPM/7/PyU1TaEovzQvxdBAI680V9OKSwEIUjKLSxLzklMVbBWAggqqCoYGYPGi1JLSojy49P@Cosy8Eg2YflNNTS5UEUMDDCEzc03N/wA\" rel=\"nofollow noreferrer\" title=\"Python 3 – Try It Online\">Try it online!</a></p>\n\n<p>Then, if the distance from the nearest 10 is greater than or equal to 5, simply add 10 minus that distance onto the original number. Otherwise, subtract 10 minus that distance from the original number:</p>\n\n<pre><code>def round10(num):\n if num % 10 &gt;= 5: \n return num + (10 - (num % 10))\n else:\n return num - (10 - (num % 10))\n</code></pre>\n\n<p><a href=\"https://tio.run/##K6gsycjPM/7/PyU1TaEovzQvxdBAI680V9OKSwEIMtMUgBwFVQVDAwU7WwVTKwWwMAgUpZaUFuWBpbUVNIDyugoaMLWammBlqTnFqVbYNOhi0fC/oCgzr0QD5gZToBCqCFgVqpCZuabmfwA\" rel=\"nofollow noreferrer\" title=\"Python 3 – Try It Online\">Try it online!</a></p>\n\n<h2>A Minor Point</h2>\n\n<p>I assume that CodingBat wants the function that performs the summing to be called <code>sum</code>. In that case, you can't really change it. But if this were in a proper program, I would strongly recommend you change the function name. Why? To avoid \"masking\" (that is, overwriting) the built-in function called <code>sum</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T10:43:21.617", "Id": "471364", "Score": "1", "body": "Thank you soo much man. I’m really grateful. I’m only 15 and I started learning from freecodecamp 4 days ago. Again, thank you ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T11:51:49.363", "Id": "471367", "Score": "0", "body": "Glad I could help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T16:36:35.107", "Id": "471401", "Score": "0", "body": "I was wondering whether you could give me some advice on programming. I started off with python and I’ve learnt some of the basics. What do you think is the best way to learn python and what strategies should I use while solving problems? And what language should I learn next if I (somehow) finish learning python? Any tips will help . I really appreciate your help, stay safe m8." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:10:13.850", "Id": "471439", "Score": "0", "body": "@BumBum I believe the best way to learn python (and any language for that matter) is through **practice**. Online tutorials are a great way to learn the basics, but I suggest that you also \"experiment\" with what is being taught - once you feel you have a basic understanding of a concept, open a program like IDLE and play around with what you've learnt. In regards to the best way to approach problems, I suggest that before you write any code, you take a moment to plan your approach. Doing so will help you think critically about what needs to be written." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:12:31.457", "Id": "471441", "Score": "0", "body": "@BumBum in regards to what to do after Python, I suggest that you move onto a language which has explicit data typing (such as C++). Doing so will help you fully understand the interactions between objects such as integers and strings. It will also give you exposure to other concepts that Python doesn't necessarily teach (such as memory manipulation, or advanced OOP). Hopefully that helps!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T04:25:49.223", "Id": "471457", "Score": "0", "body": "Thank you for your help . Do you know any good free websites I can learn from ?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T08:08:16.050", "Id": "240327", "ParentId": "240322", "Score": "1" } } ]
{ "AcceptedAnswerId": "240327", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T07:02:44.423", "Id": "240322", "Score": "-1", "Tags": [ "python" ], "Title": "Rounding number to 10" }
240322
<pre><code>for i in range(1,int(input())+1): print(((10**i -1)//9)*((10**i -1)//9)) print('lol just need to fill one more line to post the question IGNORE IT') </code></pre> <p>What is the meaning of '*' in between <code>((10**i -1)//9)</code> and <code>((10**i -1)//9)</code> in the above print statement?</p>
[]
[ { "body": "<p><strong><code>**</code></strong> this means power , for example : <code>5 ** 2</code> which mean : <code>5 squared --&gt; 25</code>. <br><code>2 ** 7</code> which mean : <code>2 to the power of 7 -- &gt; 128</code>.</p>\n\n<p><strong><code>//</code></strong> this means Floor division - division that results into whole number adjusted to the left in the number line.\n<br>For example:</p>\n\n<pre><code>x = 15\ny = 4\nprint('x / y =',x/y) # Output: x / y = 3.75\nprint('x // y =',x//y) # Output: x // y = 3\nprint('x ** y =',x**y) # Output: x ** y = 50625\nprint('x * y =',x*y) # Output: x * y = 60\n</code></pre>\n\n<p><strong>Update</strong>\n<br>To be more clear : <code>*</code> this means multiplication operator.</p>\n\n<p>Hope that helps you , Good Luck</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T10:40:23.227", "Id": "240332", "ParentId": "240323", "Score": "4" } }, { "body": "<p>Let's first look at what you are printing:</p>\n\n<pre><code>((10**i -1)//9)*((10**i -1)//9) \n\n#that is the math task, from which you are printing the result\n</code></pre>\n\n<p>You asked what <code>*</code> means.\nThis is the multiplication operator...</p>\n\n<p>Let's look at the other things, so you get a better understanding of what is going on</p>\n\n<pre><code>result = 10**i - 1\n</code></pre>\n\n<p>Here you are doing 10 to the power of i and then minus one.\nThe <code>**</code> operator means to the power of...</p>\n\n<p>So <code>2**4</code> means 2^4 or two to the power of four.</p>\n\n<p>Then you are dividing the result of that task with 9 <code>(result)//9</code> \nYou are using <code>//</code> which is the floor division. This will cut of the decimal place.</p>\n\n<p>The right side after the <code>*</code> is just the same as the first one.\nYou multiply them with the <code>*</code> operator.</p>\n\n<pre><code>result = (10**i -1)//9\nprint( result * result ) #Multiplication\n</code></pre>\n\n<p>I hope that this helped you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T13:56:01.543", "Id": "240337", "ParentId": "240323", "Score": "1" } } ]
{ "AcceptedAnswerId": "240337", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T07:11:50.503", "Id": "240323", "Score": "-3", "Tags": [ "python", "python-3.x", "community-challenge" ], "Title": "'*' present in the print statement-PYTHON" }
240323
<p>I'm trying to keep my sanity while working with a legacy winforms application that uses an web api, both maintained by my team.</p> <p>In the past we have multiple cases of methods using wrong api endpoints, or even having different names in both client and server implementation, so we came with the idea of having an interface to represent the API available methods:</p> <pre><code>public interface IUser { Task&lt;List&lt;Data&gt;&gt; Fetch(string login); } </code></pre> <p>Using this approach, the server API implementation is pretty straightforward:</p> <pre><code>public class UserController : MyController&lt;User&gt; { [HttpGet, ResponseType(typeof(List&lt;Data&gt;))] public async Task&lt;IHttpActionResult&gt; Fetch(string login) { var business = GetBusiness(); var result = await business.Fetch(login); return Ok(result); } } public class User: MyBusiness, IUser { public async Task&lt;List&lt;Data&gt;&gt; Fetch(string login) { using (var context = GetContext(...)) { var result = await context...; result.SomethingElse = await SomethingElse(); return result; } } public async Task&lt;Foo&gt; SomethingElse() { using (var context = GetContext(...)) { return await ...; } } } </code></pre> <p>In the client side, we don't want the presentation layer dealing with web api request URL formatting, so we encapsulate those details inside a web api class wrapper which implements the same interface:</p> <pre><code>public class User: IUser { private User() { } private static class ApiConstants { public const string Fetch = "api/{0}/User/Fetch"; } public static readonly User Data = new User(); public async Task&lt;List&lt;Data&gt;&gt; Fetch(string login) { var result = new List&lt;Data&gt;(); try { result = await ApiHelper.GetAsync&lt;List&lt;Data&gt;&gt;( User.ApiConstants.Fetch, new NameValueCollection { {"login", login}, }); } catch (Exception ex) { Logger.Error(ex); } return result; } } </code></pre> <p>Whenever I do need to use this in the presentation layer, I would do something like this:</p> <pre><code>private void ok_Click(object sender, EventArgs e) { var data = Extensions.BlockWithoutLockup( async () =&gt; await Api.User.Data.Fetch(login)); // do stuff } </code></pre> <p>Things there are currently bugging me:</p> <ul> <li><p>Swallowing the error in the client api wrapper;</p> <ul> <li>fixing this involves creating a generic error handling to tell apart business validations from infrastructure issues.</li> <li>We're planning to throw the exception all way to the interface and it will take the proper action based on the exception type.</li> </ul></li> <li><p>Having the <code>ApiConstants</code> inner class</p> <ul> <li>We're considering using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stacktrace" rel="nofollow noreferrer"><code>StackTrace</code></a> to get the caller method/class and compose the URL but StackTrace doesn't play nice with async calls</li> <li>as having that constant could be useful for dealing with endpoint naming exceptions, we don't feel like we should provide such level of customization by now</li> </ul></li> <li><p>Have to type several times the API call return type:</p> <ul> <li>fair occurrences: <ul> <li>in the common interface</li> <li>in the API business implementation</li> <li>in the wrapper method declaration</li> </ul></li> <li>in the Controller ResponseType attribute, for generating dynamic documentation help pages</li> <li>in the result variable within the wrapper method</li> <li>passing the same T to the <code>ApiHelper.GetAsync</code> method</li> </ul></li> <li><p>Initializing the database context several times in the API layer:</p> <ul> <li>we're considering create a MyBusiness.Context protected property <ul> <li>using this we could create it only once and pass it through dependant calls; </li> <li>this would also provide support to transactions down in the road</li> </ul></li> </ul></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T20:51:18.407", "Id": "471417", "Score": "0", "body": "I didn't understand why swallow the exception. Why not just let it be thrown and add a middleware that log the exception?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T12:12:43.043", "Id": "471479", "Score": "0", "body": "@shanif, in the past they tried a quick and dirt path to start using the api; that went bad as winforms UI doesn't play nice with async/await and at some point they starting getting flooded with error messages; at that moment the introduced this idea on do not fail in the api level just return empty responses and that was implemented in the wrapper level; i think it is time now to remove that ugly fix" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T14:23:52.550", "Id": "240340", "Score": "2", "Tags": [ "c#", "api", "entity-framework", "async-await", "winforms" ], "Title": "Web API wrapper design and sharing EF database context" }
240340
<h2>What I want to Build</h2> <p>I need to store structured data in a file column format. i.e. Each row of data is split across multiple files, each file representing one specific data item.</p> <p>Example:</p> <pre><code>class Team { int id; int size; }; class Person { std::string name; int age; double salary; Team. team; } </code></pre> <p>If I saved this to a file it would generate one row with three columns (name/age/salary/team (team will have its own two columns)). But each column is stored in its own file.</p> <h3>Example:</h3> <pre><code>CF::File. saveFile("data"); saveFile &lt;&lt; Person{"Loki", 33, 12345, Team{12,34}}; saveFile &lt;&lt; Person{"Tom", 25, 34566, Team{13,34}}; saveFile &lt;&lt; Person{"Luke", 45, 43125, Team{14,34}}; saveFile &lt;&lt; Person{"John", 32, 43895, Team{15,34}}; saveFile &lt;&lt; Person{"Pete", 18, 43111, Team{16,34}}; </code></pre> <p>This should generate three files, each file with 5 values:</p> <pre><code>&gt; find data data/name data/age data/salary data/team/id data/team/size </code></pre> <p>Currently it does not generate indexes into these files (but this may be a later addition).</p> <h2>Building</h2> <p>I reuse code (The Traits) from ThorsSerializer (reviewed here <a href="https://codereview.stackexchange.com/questions/81922/macro-to-build-type-declaration">Macro to build type declaration</a> )</p> <p>If you want to build this code you will need to have a local copy of <a href="https://github.com/Loki-Astari/ThorsSerializer" rel="nofollow noreferrer">ThorsSerializer</a>. The easiest way to get a copy is via <strong>brew</strong> (or a header only version can be retrieved via git).</p> <pre><code> Brew: installed (and removed) via brew `brew install thors-serializer`. Git: git clone --single-branch --branch header-only https://github.com/Loki-Astari/ThorsSerializer.git </code></pre> <h2>Things I think could be better.</h2> <ol> <li>Constructors.<br> Seems like a lot of duplication between the move and copy constructors. Not sure best way to deal with this.</li> <li>Recursive template expansion.<br> I use <code>{0, (&lt;expression&gt;, 0)...}</code> to expand tuples open to more elegant alternatives.</li> </ol> <p>Why:</p> <pre><code>int ignore = {0, (&lt;expression&gt;, 0)...}; ((void)ignore); /* * {0, This zero is for the situation where the Args... pack is empty * Without this case an empty parameter pack causes a compilation failure. * * , 0) This allows me to use void expressions and the comma * operator results in the zero result of the ( &lt;exp&gt;, 0) * * Then we assign to a single int as this reduces the initialization * a comma expression list of all zeros. * * Then we have to use the variable in an expression otherwise the * compiler will complain. So just cast to void which is a no-op. */ </code></pre> <h2>Source</h2> <h3>File.h</h3> <pre><code>#ifndef THORSANVIL_FS_COLUMNFORMAT_FILE_H #define THORSANVIL_FS_COLUMNFORMAT_FILE_H #include &lt;ThorSerialize/Traits.h&gt; #include &lt;string&gt; #include &lt;tuple&gt; #include &lt;fstream&gt; namespace ThorsAnvil { namespace FS { namespace ColumnFormat { template&lt;typename T&gt; class File; template&lt;typename T, ThorsAnvil::Serialize::TraitType type = ThorsAnvil::Serialize::Traits&lt;T&gt;::type&gt; struct FileTupleColumn; template&lt;typename T&gt; struct FileTupleColumn&lt;T, ThorsAnvil::Serialize::TraitType::Value&gt; { using ColumnType = std::ofstream; }; template&lt;typename T&gt; struct FileTupleColumn&lt;T, ThorsAnvil::Serialize::TraitType::Map&gt; { using ColumnType = File&lt;T&gt;; }; template&lt;typename T, typename P&gt; struct FileTupleColumnBuilder; template&lt;typename T, typename P&gt; struct FileTupleColumnBuilder&lt;T, std::pair&lt;char const*, P T::*&gt;&gt; { using ColumnType = typename FileTupleColumn&lt;P&gt;::ColumnType; }; template&lt;typename T, typename TUP&gt; struct FileTupleBuilderFromArgs; template&lt;typename T, typename... Args&gt; struct FileTupleBuilderFromArgs&lt;T, std::tuple&lt;Args...&gt;&gt; { using FileTuple = std::tuple&lt;typename FileTupleColumnBuilder&lt;T, Args&gt;::ColumnType...&gt;; }; template&lt;typename T&gt; struct FileTupleBuilderFromObj { using Traits = ThorsAnvil::Serialize::Traits&lt;T&gt;; using FileTuple = typename FileTupleBuilderFromArgs&lt;T, typename Traits::Members&gt;::FileTuple; }; template&lt;typename T&gt; class File { using FileTuple = typename FileTupleBuilderFromObj&lt;T&gt;::FileTuple; bool fileOpened; std::string baseFileName; FileTuple fileTuple; public: File(std::string&amp;&amp; fileName = ""); File(std::string const&amp; fileName); ~File(); void open(std::string const&amp; fileName); void open(std::string&amp;&amp; fileName); void open(); void close(); void write(T const&amp; data); friend File&amp; operator&lt;&lt;(File&amp; file, T const&amp; data) { file.write(data); return file; } template&lt;std::size_t I, typename F, typename M&gt; void writeOneMember(F&amp; files, M&amp; members, T const&amp; data); template&lt;typename F, typename M, std::size_t... I&gt; void writeMembers(F&amp; files, M&amp; member, T const&amp; data, std::index_sequence&lt;I...&gt; const&amp;); private: using Traits = ThorsAnvil::Serialize::Traits&lt;T&gt;; using Members = typename Traits::Members; using Index = std::make_index_sequence&lt;std::tuple_size&lt;Members&gt;::value&gt;; void doOpen(); void doClose(); template&lt;std::size_t... I&gt; void doCloseMembers(std::index_sequence&lt;I...&gt; const&amp;); template&lt;std::size_t... I&gt; void doOpenMembers(std::index_sequence&lt;I...&gt; const&amp;); }; } } } #endif </code></pre> <h3>File.tpp</h3> <pre><code>#ifndef THORSANVIL_FS_COLUMNFORMAT_FILE_TPP #define THORSANVIL_FS_COLUMNFORMAT_FILE_TPP #include "file.h" #include &lt;sys/stat.h&gt; #include &lt;sys/types.h&gt; #include &lt;string_view&gt; #include &lt;iostream&gt; namespace ThorsAnvil { namespace FS { namespace ColumnFormat { template&lt;typename T&gt; File&lt;T&gt;::File(std::string&amp;&amp; fileName) : fileOpened(false) , baseFileName(std::move(fileName)) { open(); } template&lt;typename T&gt; File&lt;T&gt;::File(std::string const&amp; fileName) : fileOpened(false) , baseFileName(std::move(fileName)) { open(); } template&lt;typename T&gt; File&lt;T&gt;::~File() {} template&lt;typename T&gt; void File&lt;T&gt;::open(std::string const&amp; fileName) { if (fileOpened) { return; } baseFileName = fileName; open(); } template&lt;typename T&gt; void File&lt;T&gt;::open(std::string&amp;&amp; fileName) { if (fileOpened) { return; } baseFileName = std::move(fileName); open(); } template&lt;typename T&gt; void File&lt;T&gt;::open() { if (baseFileName == "") { return; } doOpen(); fileOpened = true; } template&lt;typename T&gt; void File&lt;T&gt;::close() { if (!fileOpened) { return; } doClose(); fileOpened = false; } template&lt;typename T&gt; template&lt;std::size_t... I&gt; void File&lt;T&gt;::doCloseMembers(std::index_sequence&lt;I...&gt; const&amp;) { int ignore = { 0, ([&amp;fileTuple = this-&gt;fileTuple](){std::get&lt;I&gt;(fileTuple).close();}(), 0)... }; ((void)ignore); } template&lt;typename T&gt; template&lt;std::size_t... I&gt; void File&lt;T&gt;::doOpenMembers(std::index_sequence&lt;I...&gt; const&amp;) { int ignore = { 0, ( [&amp;baseFileName = this-&gt;baseFileName, &amp;fileTuple = this-&gt;fileTuple]() { auto&amp; members = Traits::getMembers(); auto&amp; name = std::get&lt;I&gt;(members).first; auto&amp; file = std::get&lt;I&gt;(fileTuple); mkdir(baseFileName.c_str(), 0777); std::string fileNamePath(baseFileName); fileNamePath += "/"; fileNamePath += name; file.open(fileNamePath); }(), 0 )... }; ((void)ignore); } template&lt;typename T&gt; void File&lt;T&gt;::doOpen() { doOpenMembers(Index{}); } template&lt;typename T&gt; void File&lt;T&gt;::doClose() { doCloseMembers(Index{}); } template&lt;typename F, typename T, ThorsAnvil::Serialize::TraitType type = ThorsAnvil::Serialize::Traits&lt;T&gt;::type&gt; struct FileWriter { void write(F&amp; file, T const&amp; obj) { file &lt;&lt; obj; } }; template&lt;typename T&gt; struct FileWriter&lt;std::ofstream, T, ThorsAnvil::Serialize::TraitType::Value&gt; { void write(std::ostream&amp; file, T const&amp; obj) { file.write(reinterpret_cast&lt;char const*&gt;(&amp;obj), sizeof obj); } }; template&lt;&gt; struct FileWriter&lt;std::ofstream, std::string, ThorsAnvil::Serialize::TraitType::Value&gt; { void write(std::ostream&amp; file, std::string const&amp; obj) { std::string::const_iterator start = std::begin(obj); std::size_t used = 0; for(std::size_t size = obj.find('\n'); size != std::string::npos; size = obj.find('\n', size + 1)) { size = (size == std::string::npos) ? (std::end(obj) - start) : size; std::size_t len = (size - used); file &lt;&lt; std::string_view(&amp;*start, size - used) &lt;&lt; '\0'; start += (len + 1); used += (len + 1); } file &lt;&lt; std::string_view(&amp;*start) &lt;&lt; "\n"; } }; template&lt;typename P&gt; struct GetPointerType; template&lt;typename R, typename T&gt; struct GetPointerType&lt;std::pair&lt;char const*, R T::*&gt;&gt; { using ReturnType = R; }; template&lt;typename T&gt; template&lt;typename F, typename M, std::size_t... I&gt; void File&lt;T&gt;::writeMembers(F&amp; files, M&amp; members, T const&amp; data, std::index_sequence&lt;I...&gt; const&amp;) { auto ignore = { 0, ( [&amp;files, &amp;members, &amp;data]() { auto&amp; file = std::get&lt;I&gt;(files); auto&amp; pointer = std::get&lt;I&gt;(members).second; using File = typename std::tuple_element&lt;I, F&gt;::type; using PointerType = typename std::tuple_element&lt;I, Members&gt;::type; using Dst = typename GetPointerType&lt;PointerType&gt;::ReturnType; FileWriter&lt;File, Dst&gt; fileWriter; fileWriter.write(file, data.*pointer); }(), 0 )... }; ((void)ignore); } template&lt;typename T&gt; void File&lt;T&gt;::write(T const&amp; data) { writeMembers(fileTuple, Traits::getMembers(), data, Index{}); } } } } #endif </code></pre> <h3>Main.cpp</h3> <p>A test application to make sure it works.</p> <pre><code>#include "file.h" #include "file.tpp" #include &lt;ThorSerialize/Traits.h&gt; #include &lt;iostream&gt; struct Person { std::string name; int age; }; struct Employee { Person p; double salary; }; ThorsAnvil_MakeTrait(Person, name, age); ThorsAnvil_MakeTrait(Employee, p, salary); namespace CF = ThorsAnvil::FS::ColumnFormat; int main() { CF::File&lt;Person&gt; file1("data1"); CF::File&lt;Employee&gt; file2("data2"); std::cout &lt;&lt; "H World\n"; file1 &lt;&lt; Person{"Martin", 12}; file2 &lt;&lt; Employee{Person{"KK", 14}, 2.34}; } </code></pre> <h3>Makefile</h3> <pre><code>SRC = $(wildcard *.cpp) OBJ = $(patsubst %.cpp, %.o, $(SRC)) CXXFLAGS▸ += -std=c++17 -Wall -Wextra -pedantic -Wno-unknown-pragmas $(EXTRA_INCLUDE_DIR) all: $(OBJ) $(CXX) $(CXXFLAGS) -o file $(OBJ) </code></pre> <p>If you installed <code>ThorsSerializer</code> via brew this should work as-is. If you used the header-only version of git then you will need to add a line to this file:</p> <pre><code>EXTRA_INCLUDE_DIR = &lt;Dir where you cloned from&gt;/ThorsSerializer </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T17:33:59.783", "Id": "471405", "Score": "0", "body": "Is \"Formst\" in the title a typo?" } ]
[ { "body": "<p>Some random thoughts here:</p>\n\n<h1>Structure</h1>\n\n<p>It is a bit surprising that I need to include <code>file.tpp</code> to get the definition of templates. The confusion may be reduced by either making <code>file.h</code> include <code>file.tpp</code>, or renaming <code>file.h</code> to something like <code>file_fwd.h</code>.</p>\n\n<h1>Interface</h1>\n\n<p>Do you really need open and closed states? The implementation is simpler if the closed state is not supported (i.e., streams open at construction and close at destruction). Then, you can drop <code>open</code> and <code>close</code>, as well as the <code>fileOpened</code> member.</p>\n\n<p>The public function <code>writeMembers</code> has an <code>std::index_sequence</code> parameter. I guess keeping it parallel to <code>writeOneMember</code> is cleaner:</p>\n\n<pre><code>template &lt;std::size_t I, typename F, typename M&gt;\nvoid writeOneMember(F&amp; files, M&amp; members, T const&amp; data);\n\ntemplate &lt;std::size_t... I, typename F, typename M&gt;\nvoid writeMembers(F&amp; files, M&amp; members, T const&amp; data);\n</code></pre>\n\n<p>(Also I don't think you need to pass empty types like <code>std::index_sequence</code> by const reference.)</p>\n\n<h1>Implementation</h1>\n\n<blockquote>\n<pre><code>File(std::string&amp;&amp; fileName = \"\");\nFile(std::string const&amp; fileName);\n~File();\n</code></pre>\n</blockquote>\n\n<p>I don't think you need the destructor &mdash; it's just <code>{}</code> after all. The two constructors can also be merged, thanks to <code>std::string</code> supporting move semantics: (I )</p>\n\n<pre><code>File(std::string fileName = {})\n : baseFileName{std::move(fileName)}\n{\n open();\n}\n</code></pre>\n\n<p>I'm surprised that assigning a braced-init-list to a scalar even compiles (<a href=\"https://wandbox.org/permlink/TEtMCu6h2N99bNMu\" rel=\"nofollow noreferrer\">I can't get that to compile</a>). Anyway, you don't need them &mdash; fold expressions are simpler:</p>\n\n<pre><code>(expression, ...);\n</code></pre>\n\n<p>Also, the capture of many lambdas may be simplified to just <code>[&amp;]</code> (unless you really want to be explicit; I wouldn't for immediately invoked lambdas like this).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:55:34.453", "Id": "471556", "Score": "1", "body": "Thanks for that. Quesiton about the constructor. K I see how you can simplify the case for `std::string` because we know that it has move semantics. But what about a constructor for a generic class that takes a template parameter in the constructor. In that case we can not tell if T has a move constructor but writing this way would force a non movable object to be copied twice. Is there a generic way of writing the constructor that would work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T09:09:27.247", "Id": "471607", "Score": "0", "body": "@MartinYork For generic types, we can use perfect forwarding, which allows us to collect arguments and defer construction. This is the usual approach taken by the standard library (`emplace`, `optional(in_place)`, etc.). If list initialization semantics is needed, users can `forward_as_tuple` and make a wrapper that automatically converts to the destination type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-08T06:59:51.643", "Id": "484845", "Score": "0", "body": "https://wandbox.org/permlink/whOHW6kcmm601GiY" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T01:30:49.243", "Id": "240376", "ParentId": "240341", "Score": "2" } } ]
{ "AcceptedAnswerId": "240376", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T14:37:24.473", "Id": "240341", "Score": "3", "Tags": [ "c++", "c++17" ], "Title": "Column File Format Stream" }
240341
<p>This is my implementation of a graph and <a href="https://en.wikipedia.org/wiki/Kruskal%27s_algorithm" rel="nofollow noreferrer">Kruskal's algorithm</a> in Python. I wanted to design the graph module myself and I would like some feedback on the design. I tried to follow <a href="https://en.wikipedia.org/wiki/SOLID" rel="nofollow noreferrer">SOLID</a> throughout. I am not sure if the separate Vertex object is wise, but I feel it could be useful as I expand this module. </p> <p>I had a copy of a flowchart of Kruskal's algorithm from a textbook (not my current course) and I decided to implement it, I am wondering how Pythonic my code is.</p> <p>I have also programmed Prim's algorithm in the same file but I will split it over two questions.</p> <pre><code>class Vertex: def __init__(self, name): self.name = name def __str__(self): return f"Vertex {self.name}" class Edge: def __init__(self, start, end, weight): self.start = start self.end = end self.weight = weight def __str__(self): return f"{self.start}{self.end}" class Graph: def __init__(self, v, e): self.vertices = v self.edges = e def vertex_from_name(self, name): """ Return vertex object given vertex name. """ return next((v for v in self.vertices if v.name == name), None) def add_edge(self, start, end, weight): """ Add an edge connecting two vertices. Arguments can either be vertex name or vertex object. """ if isinstance(start, str): start = self.vertex_from_name(start) if isinstance(end, str): end = self.vertex_from_name(end) self.edges.append(Edge(start, end, weight)) def edge_on_vertex(self, v): """ Return edges connected to given vertex v.""" return [e for e in self.edges if (e.start == v) or (e.end == v)] def connected_vertices(self, v): """ Return the vertices connected to argument v.""" if isinstance(v, str): v = self.vertex_from_name(v) return [e.start for e in self.edges if e.end == v] + [e.end for e in self.edges if e.start == v] def union(self, lst, e1, e2): """ Given a list of lists, merges e1 root list with e2 root list and returns merged list.""" xroot, yroot = [], [] # Find roots of both elements for i in lst: if e1 in i: xroot = i if e2 in i: yroot = i # Same root, cannot merge if xroot == yroot: return False xroot += yroot lst.remove(yroot) return lst def is_cycle(self): """ Return if the graph contains a cycle. """ self.sets = [[v] for v in self.vertices] self._edges = sorted(self.edges, key=lambda x: x.weight) for e in self._edges: _temp = self.union(self.sets, e.start, e.end) if _temp == False: return True else: self.sets = _temp return False def Kruskals(self): """ Return MST using Kruskal's algorithm. """ self.tree = Graph([], []) self.tree.vertices = self.vertices self.sorted_edges = sorted(self.edges, key=lambda x: x.weight) self.tree.edges.append(self.sorted_edges.pop(0)) for edge in self.sorted_edges: self.tree.edges.append(edge) if self.tree.is_cycle(): self.tree.edges.remove(edge) return self.tree if __name__ == "__main__": v = [Vertex(x) for x in ["A", "B", "C", "D", "E", "F"]] g = Graph(v, []) g.add_edge("A", "B", 9) g.add_edge("A", "C", 12) g.add_edge("A", "D", 9) g.add_edge("A", "E", 11) g.add_edge("A", "F", 8) g.add_edge("B", "C", 10) g.add_edge("B", "F", 15) g.add_edge("C", "D", 8) g.add_edge("D", "E", 14) g.add_edge("E", "F", 12) print(g.Kruskals().edges) </code></pre>
[]
[ { "body": "<h2>Type hints</h2>\n\n<pre><code>def __init__(self, start, end, weight):\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def __init__(self, start: Vertex, end: Vertex, weight: float):\n</code></pre>\n\n<p>depending on a few things, including the order of declaration of your classes, <code>Vertex</code> might need to be <code>'Vertex'</code> here.</p>\n\n<p>For another example, this</p>\n\n<pre><code>def vertex_from_name(self, name):\n</code></pre>\n\n<p>can turn into</p>\n\n<pre><code>def vertex_from_name(self, name: str) -&gt; Vertex:\n</code></pre>\n\n<h2>Efficient lookups</h2>\n\n<p>To make this more efficient:</p>\n\n<pre><code> return next((v for v in self.vertices if v.name == name), None)\n</code></pre>\n\n<p>Consider maintaining a string-to-<code>Vertex</code> dictionary to reduce this lookup from O(n) to O(1) in time.</p>\n\n<h2>Premature materialization</h2>\n\n<p>These:</p>\n\n<pre><code> return [e for e in self.edges if (e.start == v) or (e.end == v)]\n\n\n return [e.start for e in self.edges if e.end == v] + [e.end for e in self.edges if e.start == v]\n</code></pre>\n\n<p>require that the entire results be stored to an in-memory list. To return the generator directly and reduce this memory requirement, the first one can be</p>\n\n<pre><code> return (e for e in self.edges if v in {e.start, e.end})\n</code></pre>\n\n<p>and the second one can be</p>\n\n<pre><code>yield from (e.start for e in self.edges if e.end == v)\nyield from (e.end for e in self.edges if e.start == v)\n</code></pre>\n\n<h2>Set-membership tests</h2>\n\n<p>This:</p>\n\n<pre><code>\"\"\" Given a list of lists, merges e1 root list with e2 root list and returns merged list.\"\"\"\n</code></pre>\n\n<p>is probably better-expressed as accepting a list of <code>set</code>, not a list of <code>list</code>s. That will make these two tests:</p>\n\n<pre><code> if e1 in i:\n xroot = i\n if e2 in i:\n yroot = i\n</code></pre>\n\n<p>faster. This:</p>\n\n<pre><code> self.sets = [[v] for v in self.vertices]\n</code></pre>\n\n<p>would then become</p>\n\n<pre><code> self.sets = [{v} for v in self.vertices]\n</code></pre>\n\n<h2>Strings as iterables</h2>\n\n<p>This</p>\n\n<pre><code>v = [Vertex(x) for x in [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"]]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>v = [Vertex(x) for x in 'ABCDEF']\n</code></pre>\n\n<h2>Convenience functions</h2>\n\n<p>Consider making a convenience function to turn this</p>\n\n<pre><code>g.add_edge(\"A\", \"B\", 9)\ng.add_edge(\"A\", \"C\", 12)\ng.add_edge(\"A\", \"D\", 9)\ng.add_edge(\"A\", \"E\", 11)\ng.add_edge(\"A\", \"F\", 8)\ng.add_edge(\"B\", \"C\", 10)\ng.add_edge(\"B\", \"F\", 15)\ng.add_edge(\"C\", \"D\", 8)\ng.add_edge(\"D\", \"E\", 14)\ng.add_edge(\"E\", \"F\", 12)\n</code></pre>\n\n<p>into</p>\n\n<pre><code>g.add_edges(\n (\"A\", \"B\", 9),\n (\"A\", \"C\", 12),\n (\"A\", \"D\", 9),\n (\"A\", \"E\", 11),\n (\"A\", \"F\", 8),\n (\"B\", \"C\", 10),\n (\"B\", \"F\", 15),\n (\"C\", \"D\", 8),\n (\"D\", \"E\", 14),\n (\"E\", \"F\", 12),\n)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T18:30:34.667", "Id": "240352", "ParentId": "240343", "Score": "2" } }, { "body": "<h1>Temporary state in <code>self</code></h1>\n\n<p><code>is_cycle</code> leaves <code>sets</code> and <code>_edges</code> in <code>self</code>. Not as a cache or as a result, but as temporary state which then leaks out, that is generally seen as a bad thing.</p>\n\n<p><code>Kruskals</code> leaves the <code>tree</code> in <code>self</code>, that's a bit more useful, but it could also be considered temporary state in <code>self</code>.</p>\n\n<h1>The Algorithm</h1>\n\n<p><code>union</code> doesn't look like an implementation of Union-Find to me. \"Ask all sets whether the element is in them\" is not how <a href=\"https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Find\" rel=\"nofollow noreferrer\"><code>Find</code> normally works</a>. Despite that, it looks like something that reasonably should work, just slower.</p>\n\n<p>The way <code>is_cycle</code> works means that the disjoint sets are built up from scratch (and the edges are re-sorted) every time <code>is_cycle</code> is called. That's wasteful, instead of rebuilding them from scratch, the sets could be kept up to date by unioning them as the main algorithm goes along. Calling <code>is_cycle</code> at all is wasteful: it loops over all edges, but the cycle could have been detected even before creating it by testing <code>Find(edge.start) != Find(edge.end)</code> in the main algorithm (<code>Kruskals</code>), which is how <a href=\"https://en.wikipedia.org/wiki/Kruskal%27s_algorithm#Pseudocode\" rel=\"nofollow noreferrer\">the pseudocode on Wikipedia</a> does it.</p>\n\n<p>Overall I think that makes the current algorithm take O(E²V log E) time, instead of O(E log E). Maybe not quite that, I just took the worst cases of all the nested loops, I didn't look at the effect of the number of sets decreasing as the algorithm progresses. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:55:33.970", "Id": "471937", "Score": "0", "body": "Thanks for the review. I will have to have a deeper look at Union-find and disjoint sets. One question: for the big O, what does V represent? Is it just another variable, independent of E?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:06:43.777", "Id": "471941", "Score": "1", "body": "@EugeneProut V is the number of vertices, E the number of edges. E cannot be greater than V² so they're not totally independent (every E could be replaced with V²), but using both V and E in the complexity analysis gives some idea of how the algorithm reacts to sparse graphs" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:52:42.023", "Id": "240586", "ParentId": "240343", "Score": "2" } } ]
{ "AcceptedAnswerId": "240352", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T15:08:40.733", "Id": "240343", "Score": "1", "Tags": [ "python", "object-oriented", "graph" ], "Title": "Graphs and Kruskal's Algorithm - Python OOP" }
240343
<p>I have learnt python 3 for about 1 month. After I learnt the basics of oop in python, I try to create a blackjack game based on tutorial's framework. I spent 1 weeks to complete it. I want to see whether some further improvements can be done on my code. Thank you!</p> <p>My blackjack game steps:</p> <ol> <li>dealer(one exposed card, one hidden card) and four players(two exposed cards) at the beginning</li> <li>if dealer has the exposed card with Ace, ask whether the players want an insurance</li> <li>(hit, stand, double down, surrender) available for normal hand, (split) added for special hand</li> <li>dealer get cards until he reaches 17</li> <li>showing result</li> <li>ask for a new game</li> </ol> <p>My tools:</p> <ul> <li>Anaconda (python 3.7)</li> <li>Pycharm 2019.3.3</li> </ul> <pre><code># Main author: Yip # Second author: 駱昊 import random from functools import total_ordering @total_ordering class Card(object): """one single card""" def __init__(self, suite, face): self._suite = suite self._face = face @property def face(self): return self._face @property def suite(self): return self._suite def __eq__(self, other): return self.face == other def __lt__(self, other): return self.face &lt; other def __add__(self, other): return self.face + other def __str__(self): if self._face == 1: face_str = 'A' elif self._face == 11: face_str = 'J' elif self._face == 12: face_str = 'Q' elif self._face == 13: face_str = 'K' else: face_str = str(self._face) return f'{self._suite}{face_str}' def __repr__(self): return self.__str__() class Poker(object): """deck of card""" def __init__(self): self._cards = [Card(suite, face) for suite in '♠♥♣♦' for face in range(1, 14)] self._current = 0 @property def cards(self): return self._cards def shuffle(self): """random shuffle""" self._current = 0 random.shuffle(self._cards) @property def next(self): """dealing cards""" card = self._cards[self._current] self._current += 1 return card def __getitem__(self, item): return self._cards[item] class Person(object): """for both dealer and players""" def __init__(self, name, bet): self._name = name self._cards_on_hand = [] self._bet = bet self._not_bust = True self._21 = False @property def name(self): return self._name @property def cards_on_hand(self): return self._cards_on_hand @cards_on_hand.setter def cards_on_hand(self, value): self._cards_on_hand = value def __getitem__(self, a, b): return self._cards_on_hand[a:b] @property def bet(self): return self._bet @bet.setter def bet(self, value): self._bet = value @property def not_bust(self): return self._not_bust @not_bust.setter def not_bust(self, value): self._not_bust = value @property def have21(self): return self._21 @have21.setter def have21(self, value): self._21 = value def __truediv__(self, other): return self.bet / other def get(self, card): """getting cards""" self._cards_on_hand.append(card) def arrange(self, card_key): """arrange the card""" self._cards_on_hand.sort(key=card_key) def sum_on_hand(self, hand=None): total_big = 0 ace_in = None for face in self._cards_on_hand: if face &gt; 10: face = 10 if face == 1: face = 11 ace_in = True total_big = face + total_big if total_big &gt; 21 and ace_in: if total_big - 10 &lt; 21: # take the smaller count return total_big - 10 else: self.not_bust = False return False elif total_big &gt; 21: self.not_bust = False return False else: return total_big def check_bust(self, hand=None): if not self.sum_on_hand(self.cards_on_hand): self.not_bust = False self.bet = 0 return False elif self.sum_on_hand(self.cards_on_hand) == 21: print(f'{self.name} got 21!') self.have21 = True return True else: return True @property def natural_21(self): # check whether the person got 21 in the beginning if self.sum_on_hand(self.cards_on_hand) == 21: self.have21 = True return True else: return False def clear(self): self.cards_on_hand.clear() self._not_bust = True self.have21 = False class Player(Person): def __init__(self, name, bet=0): super().__init__(name, bet) self._second_hand = [] self._insurance = False self._option = {"hit": self.hit, "stand": self.stand, "double down": self.double_down} self._have_split = False self._have_surrender = False self.initial_bet = bet self._second_not_bust = True self.first_not_bust = True self.second_bet = 0 self.second_have21 = False @property def second_hand(self): return self._second_hand @second_hand.setter def second_hand(self, value): self.second_hand = value @property def insurance(self): return self._insurance @insurance.setter def insurance(self, value): self._insurance = value @property def option(self): return self._option @option.setter def option(self, value): self._option = value @property def second_not_bust(self): return self._second_not_bust @second_not_bust.setter def second_not_bust(self, value): self._second_not_bust = value @property def have_surrender(self): return self._have_surrender @have_surrender.setter def have_surrender(self, value): self._have_surrender = value @property def have_split(self): return self._have_split @have_split.setter def have_split(self, value): self._have_split = value def sum_on_hand(self, hand=None): if hand == self.cards_on_hand: total_big = 0 ace_in = None for face in self.cards_on_hand: if face &gt; 10: face = 10 if face == 1: face = 11 ace_in = True total_big = face + total_big if total_big &gt; 21 and ace_in: if total_big - 10 &lt;= 21: return total_big - 10 else: self.not_bust = False return False elif total_big &gt; 21: self.not_bust = False return False else: return total_big else: total_big = 0 ace_in = None for face in hand: if face &gt; 10: face = 10 if face == 1: face = 11 ace_in = True total_big = face + total_big if total_big &gt; 21 and ace_in: if total_big - 10 &lt;= 21: return total_big - 10 else: self.second_not_bust = False return False elif total_big &gt; 21: self.second_not_bust = False return False else: return total_big def check_bust(self, hand=None): if not self.have_split: if not self.sum_on_hand(hand): self.first_not_bust = False self.bet = 0 return False elif self.sum_on_hand(hand) == 21: print(f'{self.name} got 21!') self.have21 = True return True else: return True else: if hand == self.cards_on_hand: if not self.sum_on_hand(hand): self.first_not_bust = False self.bet = 0 return False elif self.sum_on_hand(hand) == 21: print(f'{self.name}\'s first hand got 21!') self.have21 = True return True else: return True else: if not self.sum_on_hand(hand): self._second_not_bust = False self.second_bet = 0 return False elif self.sum_on_hand(hand) == 21: print(f'{self.name}\'s second hand got 21!') self.second_have21 = True return True else: return True def hit(self, card, hand): hand.append(card.next) if self.check_bust(hand) and self.have21: print(self) return print("action completed\n" + "-" * 20) elif self.check_bust(hand): pass else: print(f'{self.name}:\n{hand}\tbet:{self.bet}') return print(f'{self.name} bust!', end="\n\n") print(self) while len(hand) &lt; 5: ans = input("do you want to hit once more?(yes|no):") if ans == "yes": hand.append(card.next) if self.check_bust(hand) and self.have21: # if the player doesn't bust and have 21 print(self) return print("action completed\n" + "-" * 20) elif self.check_bust(hand): print(self) else: # the player busts print(f'{self.name}:\n{hand}\tbet:{self.bet}') return print(f'{self.name} bust!\n' + "-" * 20) elif ans == "no": return print("action completed\n" + "-" * 20) else: # second chance for careless mistake in inputting print("please enter a valid order, otherwise your decision will be defaulted as no") ans01 = {"yes": True, "no": False}.get(str(input("do you want to hit once more?(yes|no):")).lower(), False) if ans01: hand.append(card.next) if self.check_bust(hand): print(self) else: print(f'{self.name}:\n{hand}\tbet:{self.bet}') return print(f'{self.name} burst!', end="\n") else: print(self) return print("action completed\n", "-" * 20) else: return print("you cannot hit anymore as your total card number in hand reached 5\n" + "-" * 20) def stand(self): print(self) return print("action completed\n" + "-" * 20) def double_down(self, card, hand): if hand == self.cards_on_hand: self.bet *= 2 hand.append(card.next) if self.check_bust(hand): print(self) return print("action completed\n" + "-" * 20) else: print(self) return print(f'{self.name} bust!\n' + "-" * 20) else: self.second_bet *= 2 hand.append(card.next) if self.check_bust(hand): print(self) return print("action completed\n" + "-" * 20) else: print(self) return print(f'{self.name} bust!\n' + "-" * 20) def surrender(self): self.bet //= 2 # lost half of the player's bet self.have_surrender = True print(f'{self.name} has surrendered.') return print("action completed\n" + "-" * 20) def split(self, card): self.second_bet = self.bet * 1 # create another bet box self._have_split = True self.second_hand.append(self.cards_on_hand[1]) self._cards_on_hand = self.cards_on_hand[0:1] print(self) self.cards_on_hand.append(card.next) self.second_hand.append(card.next) if self.have21 and not self.second_have21: print(self) print("-" * 20) print("[second hand]:\n") self.choice(card, self.second_hand) elif not self.have21 and not self.second_have21: print(self) print("-" * 20) print("[first hand]:\n") self.choice(card, self.cards_on_hand) print("[second hand]:\n") self.choice(card, self.second_hand) elif self.have21 and self.second_have21: print(self) return print("action completed\n" + "-" * 20) else: print(self) print("-" * 20) print("[first hand]:\n") self.choice(card, self.cards_on_hand) def decide_insurance(self): print(f'{self.name}, do you want to buy insurance(yes|no):', end="") want = input("") if want == "yes": self.bet *= 1.5 self.insurance = True elif want == "no": return else: print("please enter a valid order, otherwise your decision will be defaulted as no") choice01 = {"yes": True, "no": False}.get(str(input("do you want to buy insurance(yes|no):")).lower(), False) if choice01: self.bet *= 1.5 self.insurance = True else: return def choice(self, card, hand): if not self._have_split and hand[0] == hand[1]: self.option.update({"split": self.split}) if self._have_split and "split" in self.option and "surrender" in self.option: self.option.pop("split") self.option.pop("surrender") if (not self._have_split) and len(hand) == 2: self.option.update({"surrender": self.surrender}) print(self) print(f'options offered for {self.name}:{list(self.option.keys())}') chosen = str(input("please type your decision here:")).lower() if chosen == "hit" or chosen == "double down": self.option[chosen](card, hand) elif chosen == "split" and "split" in self.option: self.option[chosen](card) elif chosen == "stand" or chosen == "surrender": self.option[chosen]() else: print("\nplease enter a valid order, otherwise your decision will be defaulted as stand") print(f'options offered for {self.name}:{list(self.option.keys())}') chosen = input("please type your decision here:") if chosen == "hit" or chosen == "double down": self.option[chosen](card, hand) elif chosen == "split" and "split" in self.option: self.option[chosen](card) else: self.option["stand"]() def get_result(self, dealer_sum): def comp(a, b): # four situation in comparing if a == b: return "draw" elif a &gt; b and a == 21: return "win with 21" elif a &gt; b and a != 21: return "bigger than host" else: return "lost" if not self._have_split: return comp(self.sum_on_hand(self.cards_on_hand), dealer_sum) else: return f"{comp(self.sum_on_hand(self.cards_on_hand), dealer_sum)}|{comp(self.sum_on_hand(self.second_hand), dealer_sum)}" def clear(self): # restore the default value when starting a new game super().clear() self.second_hand.clear() self._insurance = False self._option = {"hit": self.hit, "stand": self.stand, "double down": self.double_down} self._have_split = False self._have_surrender = False self._second_not_bust = True self.first_not_bust = True self.bet = self.bet + self.second_bet self.second_bet = 0 self.second_have21 = False def __repr__(self): if len(self.second_hand) &gt; 0: if self.first_not_bust and self.second_not_bust: return f'{self.name}:\nfirst hand:{self.cards_on_hand} second hand: {self.second_hand}\tfirst bet:{self.bet}\tsecond bet:{self.second_bet}' \ f'\t sum of first hand:{self.sum_on_hand(self.cards_on_hand)}\tsum of second hand:{self.sum_on_hand(self.second_hand)}' elif not self.first_not_bust and self.second_not_bust: return f'{self.name}:\nfirst hand:[bust] second hand: {self.second_hand}\tfirst bet:{self.bet}\tsecond bet:{self.second_bet}' \ f'\t sum of second hand:{self.sum_on_hand(self.second_hand)}' elif self.first_not_bust and not self.second_not_bust: return f'{self.name}:\nfirst hand:{self.cards_on_hand} second hand:[bust]\tfirst bet:{self.bet}\tsecond bet:{self.second_bet}' \ f'\t sum of first hand:{self.sum_on_hand(self.cards_on_hand)}' else: return f'{self.name}:\nfirst hand:[bust] second hand:[bust]\tfirst bet:{self.bet}\tsecond bet:{self.second_bet}' elif not self.not_bust: return f'{self.name}:\n[bust]\t bet:{self.bet}' else: return f'{self.name}:\n{self.cards_on_hand}\tbet:{self.bet}\t sum:{self.sum_on_hand(self.cards_on_hand)}' class Dealer(Person): def __init__(self, name, bet=0): super().__init__(name, bet) self._blackjack = False self.last = False @property def blackjack(self): return self._blackjack @blackjack.setter def blackjack(self, value): self._blackjack = value def get(self, card): self.cards_on_hand.append(card) @property def natural_21(self): if self.sum_on_hand == 21: self.blackjack = True return True else: return False @property def check_Ace(self): check = self.cards_on_hand[0] if check.face == 1: return True else: return False def initial_secondT(self): check01 = self.cards_on_hand[1] if check01.face == 10: self.blackjack = True return True else: return False def clear(self): super().clear() self.blackjack = False self.last = False def __repr__(self): if self.blackjack or self.last: if self.not_bust: return f'{self.name}:\n{self.cards_on_hand}\tsum:{self.sum_on_hand()}' else: return f'{self.name}:\n[bust]\t' elif not self.not_bust: return f'{self.name}:\n[bust]' else: return f'{self.name}:\n[{self.cards_on_hand[0]},hidden card*{len(self.cards_on_hand) - 1}]' # key of arranging the cards in hand def get_key(card): return card.face, card.suite def blackjack(): p = Poker() p.shuffle() players = [Player('player 1', 100), Player('player 2', 100), Player('player 3', 100)] host = Dealer("host") game = True def player_get(time=1): for count in range(time): for people in players: people.get(p.next) def player_display(): for each in players: each.arrange(get_key) print(each) def host_get_display(): host.get(p.next) print(host) def all_display(time=1): for times in range(time): player_get() player_display() host_get_display() print("-" * 20) def all_clear(): for rubbish in players: rubbish.not_bust = True rubbish.clear() host.clear() def zero_bet(): # check any player has invalid bet for _ in players: if _.bet &lt;= 0: print( f"{_.name},your bet must at least reach 100,please add your bet,otherwise your bet will be defaulted 100.") def inputNumber(message): while True: try: userInput = int(input(message)) except ValueError: print("please enter a valid number,otherwise your bet will be will be defaulted 100.") continue else: return userInput want_add = inputNumber("how much do you want to add:") if want_add &gt; 0 and _.bet + want_add &gt;= 100: _.bet += want_add else: print("please enter a valid number,otherwise your bet will be will be defaulted 100.") want_add01 = inputNumber("how much do you want to add:") if want_add01 &gt; 0 and _.bet + want_add01 &gt;= 100: _.bet += want_add01 else: _.bet = 100 def play(): print("-" * 20) all_clear() # clear the hand p.shuffle() # shuffling cards zero_bet() # check bet all_display(2) # deal the cards to players and host have_21 = [] for anyone in players: # check who have got 21 and decide the situation if anyone.natural_21: have_21.append(anyone.name) anyone.have21 = True nonlocal game game = False if host.natural_21: # these parts for anyone who got 21 in the beginning have_21.append(host.name) if len(have_21) &gt; 1 and host.blackjack: # draw print(f'{",".join(have_21)} have 21.') print("Draw") print("new game?(yes|no):", end="") game = {"yes": True, "no": False}.get(str(input()).lower(), False) print() return elif host.name in have_21: # host wins if host.check_Ace: # let the players have a chance to win money if the first card of host is Ace player_display() for everyone in players: everyone.decide_insurance() print(host) print("Players who bought insurance won 2 times of the insurance!") for have in players: if have.insurance: have.bet = have.bet * 5 // 3 # return the insurance and win 2 times of the insurance print(f'{have.name}\'s current bet is {have.bet}:') game = {"yes": True, "no": False}.get(str(input("new game?(yes|no)").lower()), False) print() # for clearer display return else: # if the first card is T, no chance. print(f'{host.name} has 21') print(f'{host.name} wins!') print(host) print("new game?(yes|no):", end="") game = {"yes": True, "no": False}.get(str(input()).lower(), False) print() return elif host.name not in have_21 and have_21: # player(s) win print() print(f'{",".join(have_21)} has 21') print(f'{",".join(have_21)} wins!Profit is 150% of his/her bet') for __ in players: if __.have21: __.bet *= 2.5 print(f'{__.name}\'s current bet is {__.bet}:') print("new game?(yes|no):", end="") game = {"yes": True, "no": False}.get(str(input()).lower(), False) print() return else: pass if host.check_Ace: # if the host gets Ace, the host need to ask whether the players want insurance player_display() for everyone in players: everyone.decide_insurance() if host.initial_secondT(): print(host, end="\n") print(host) print("Players who bought insurance won 2 times of the insurance!") for have in players: if have.insurance: have.bet = have.bet * 5 // 3 # return the insurance and win 2 times of the insurance print(f'{have.name}\'s current bet is {have.bet}:') choice = input("new game?(yes|no)") game = choice == "yes" else: print(f"{host.name}did not get a blackjack,the insurance bought is lost,game goes on.") print() for _ in players: if _.insurance: _.bet = _.initial_bet # player will lose their insurance and game goes on for ask in players: # ask players' decision ask.choice(p, ask.cards_on_hand) while True: # the host will get card until he reach 17 host.last = True if host.sum_on_hand() &lt; 17 and len(host.cards_on_hand) &lt; 5 and host.check_bust(): print(f"{host.name} is getting...") host_get_display() elif host.sum_on_hand() &gt;= 17 or not host.check_bust(): print(f"{host.name} can't get anymore") break print("-" * 20) if not host.not_bust: # if the host busts player_display() print(host) print(f'{host.name} bust!') print("player(s) left with blackjack won profit of 1.5 times of his/her bet,else have 1 times") for left in players: if not left.have_split: # for those who didn't split if left.have21: left.bet *= 2.5 print(f'{left.name}\'s current bet:{left.bet}') elif left.not_bust: left.bet *= 2 print(f'{left.name}\'s current bet:{left.bet}') print("-" * 20) else: if left.have21: left.bet *= 2.5 print(f'{left.name}\'s current first bet:{left.bet}') elif left.not_bust: left.bet *= 2 print(f'{left.name}\'s current first bet:{left.bet}') if left.second_have21: left.second_bet *= 2.5 print(f'{left.name}\'s current second bet:{left.second_bet}') elif left.second_not_bust: left.second_bet *= 2 print(f'{left.name}\'s current second bet:{left.second_bet}') print("-" * 20) print("new game?(yes|no):", end="") game = {"yes": True, "no": False}.get(str(input()).lower(), False) return win_with_21 = [] # four situations if the host didn't bust bigger_than_host = [] lost = [] draw = [] result = {"win_with_21": "player(s) left with blackjack won profit of 1.5 times of his/her bet ", "bigger_than_host": "player(s) who win host without 21 won profit of 1 times of his/her bet", "lost": "player(s) who lost host without 21 lost his/her bet", "draw": "player(s) who got a draw have their bet return"} # description of result for winner in players: if not winner.have_surrender and not winner.have_split: # for player who didn't surrender and didn't split situation = winner.get_result(host.sum_on_hand()) if situation == "win with 21": winner.bet *= 2.5 win_with_21.append(winner.name) elif situation == "bigger than host": winner.bet *= 2 bigger_than_host.append(winner.name) elif situation == "draw": draw.append(winner.name) else: winner.bet = 0 lost.append(winner.name) elif not winner.have_surrender and winner.have_split: # for player who have spited and didn't surrender situation01 = (winner.get_result(host.sum_on_hand()).split("|"))[0] situation02 = (winner.get_result(host.sum_on_hand()).split("|"))[1] if situation01 == "win with 21": # the situation for first hand winner.bet *= 2.5 win_with_21.append(f'{winner.name}\'s first hand') elif situation01 == "bigger than host": winner.bet *= 2 bigger_than_host.append(f'{winner.name}\'s first hand') elif situation01 == "draw": draw.append(f'{winner.name}\'s first hand') else: winner.bet = 0 lost.append(f'{winner.name}\'s first hand') if situation02 == "win with 21": # the situation for second hand winner.second_bet *= 2.5 win_with_21.append(f'{winner.name}\'s second hand') elif situation02 == "bigger than host": winner.second_bet *= 2 bigger_than_host.append(f'{winner.name}\'s second hand') elif situation02 == "draw": draw.append(f'{winner.name}\'s second hand') else: winner.second_bet = 0 lost.append(f'{winner.name}\'s second hand') else: pass print("calculating result...\n" + "-" * 20) # just for fun print(result["win_with_21"] + ":\n" + ",".join(win_with_21)) print(result["bigger_than_host"] + ":\n" + ",".join(bigger_than_host)) print(result["lost"] + ":\n" + ",".join(lost)) print(result["draw"] + ":\n" + ",".join(draw)) print("-" * 20) player_display() print(host) print("new game?(yes|no):", end="") game = {"yes": True, "no": False}.get(str(input()).lower(), False) return while game: play() if __name__ == '__main__': blackjack() </code></pre>
[]
[ { "body": "<h2>Lookup for faces</h2>\n\n<p>This:</p>\n\n<pre><code> if self._face == 1:\n face_str = 'A'\n elif self._face == 11:\n face_str = 'J'\n elif self._face == 12:\n face_str = 'Q'\n elif self._face == 13:\n face_str = 'K'\n</code></pre>\n\n<p>would be made simpler and faster if you were to keep a (static) lookup tuple, something like</p>\n\n<pre><code>class Card: # p.s. don't inherit from object if you're in 3.x\n FACES = (\n None, # 0 doesn't have a face\n 'A',\n *range(2, 11), # 2 through 10\n *'JQK'\n )\n\n # ...\n FACES[self._face]\n</code></pre>\n\n<h2>Typo</h2>\n\n<p><code>suite</code> is actually <code>suit</code>.</p>\n\n<h2>Conflating presentation and logic</h2>\n\n<p>This:</p>\n\n<pre><code>Card(suite, face)\nfor suite in '♠♥♣♦'\n</code></pre>\n\n<p>shouldn't require that people outside of <code>Card</code> know the special suit characters. Instead, you should make an <code>enum.Enum</code> whose values are set to those characters, and pass that.</p>\n\n<p>This could look like:</p>\n\n<pre><code>class Suit(Enum):\n SPADE = \"♠\"\n HEART = \"♥\"\n CLUB = \"♣\"\n DIAMOND = \"♦\"\n\n# ...\n\n self._cards = [Card(suit, face) for suit in Suit]\n</code></pre>\n\n<h2>Properties</h2>\n\n<p>This:</p>\n\n<pre><code>@property\ndef not_bust(self):\n return self._not_bust\n\n@not_bust.setter\ndef not_bust(self, value):\n self._not_bust = value\n</code></pre>\n\n<p>is somewhat of a Java-ism. It's not buying you anything. You're better off just making <code>not_bust</code> a \"public\" member variable and doing away with the properties (private-by-underscore is more of a suggestion and is not enforced, anyway).</p>\n\n<h2>Return-from-print</h2>\n\n<p>This:</p>\n\n<pre><code> return print(\"action completed\\n\" + \"-\" * 20)\n</code></pre>\n\n<p>does not do what you think it does. <code>print</code> does not return anything, so you are always returning <code>None</code>, which is equivalent to:</p>\n\n<pre><code>print(\"action completed\\n\" + \"-\" * 20)\nreturn\n</code></pre>\n\n<h2>Input parsing</h2>\n\n<p>This:</p>\n\n<pre><code> ans01 = {\"yes\": True, \"no\": False}.get(str(input(\"do you want to hit once more?(yes|no):\")).lower(),\n False)\n</code></pre>\n\n<p>is more complicated than it needs to be, and is equivalent to</p>\n\n<pre><code>hit_again = input('do you want to hit once more?').lower() == 'yes'\n</code></pre>\n\n<p>Also note that you do not need to explicitly convert the return of <code>input</code> to a string, since it is already; and you need a better variable name.</p>\n\n<h2>Set membership</h2>\n\n<pre><code> elif chosen == \"stand\" or chosen == \"surrender\":\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>elif chosen in {'stand', 'surrender'}:\n</code></pre>\n\n<h2>Booleans and early-return</h2>\n\n<pre><code> if a == b:\n return \"draw\"\n elif a &gt; b and a == 21:\n return \"win with 21\"\n elif a &gt; b and a != 21:\n return \"bigger than host\"\n else:\n return \"lost\"\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>if a == b:\n return 'draw'\nif a &lt; b:\n return 'lost'\nif a == 21:\n return 'win with 21'\nreturn 'bigger than host'\n</code></pre>\n\n<p>Also, this:</p>\n\n<pre><code> if check.face == 1:\n return True\n else:\n return False\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return check.face == 1\n</code></pre>\n\n<h2>Underscore variables</h2>\n\n<pre><code> for _ in players:\n if _.bet &lt;= 0:\n</code></pre>\n\n<p>should not use an underscore. Underscores, by convention, mean \"I won't use this variable\", but you do anyway. So just <code>for player in players</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T08:35:06.427", "Id": "471464", "Score": "0", "body": "Thank you! I would try to modify my code!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T09:59:43.780", "Id": "471474", "Score": "1", "body": "Could you explain the part **conflating representation and logic*** once more please? I don't understand how it actually looks like. Do you mean this? `class Suit(Enum):\n Spade = \"♠\"\n Heart = \"♥\"\n Club = \"♣\"\n Diamond = \"♦\"`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T14:43:28.877", "Id": "471500", "Score": "2", "body": "Yes; edited. Enum constants are capitalized." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T17:43:26.660", "Id": "240351", "ParentId": "240344", "Score": "12" } } ]
{ "AcceptedAnswerId": "240351", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T15:14:24.007", "Id": "240344", "Score": "10", "Tags": [ "python", "python-3.x", "object-oriented" ], "Title": "Any improvement to my completed blackjack game in oop of python?" }
240344
<p>This has been racking my brain for hours now. I will try to explain as much as I can. I'm aware this code is horrendously ungraceful, but I'm new to Fortran and making things more efficient is not easy for me. </p> <p>I am trying to simulate the celestial motion I've specified in the title. I am going to have (before moving to the co-moving frame) the Sun at the origin of coordinates, the Earth at x = <code>149597870d+3</code>meters away (the mean distance from the Sun to the Earth I believe), y = 0. For the moon, I'm having it at the distance from the Moon to Earth (<code>384400d+3</code> meters) plus the distance from the Earth to the Sun, so that we essentially have a situation where all planets are situated on the y = 0 line, with the Earth an astronomical unit away in the x-axis, and the moon a further distance away equal to the distance between the Earth and the moon. </p> <p>I've attempted to illustrate the situation, as well as the free body diagrams, in the following two images. </p> <p><a href="https://i.stack.imgur.com/Mxw0X.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mxw0X.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/eY8md.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eY8md.jpg" alt="enter image description here"></a> </p> <p>From there, I've defined a 12 dimensional array, <code>sol</code>, which holds the x and y positions and velocities of each body such that sol = (x1,y1,x2,y2,x3,y3,dx1/dt,dy1/dt,dx2/dt,dy2/dt,dx3/dt,dy3/dt). I then initialized the array: the sun will have no initial velocities, the Earth will have an initial y velocity equal to its mean orbital velocity around the sun with no initial x velocity, and the moon will have an initial y velocity equal to its mean orbital velocity around the earth and no initial x velocity.</p> <pre><code> inits(1:2) = 0d0 inits(3) = distE inits(4) = 0d0 inits(5) = distE+distM inits(6:9) = 0d0 inits(10) = vE inits(11) = 0d0 inits(12) = vM sol = inits </code></pre> <p>I then attempt to bring everything to a co-moving frame based off the following equation:</p> <p><a href="https://i.stack.imgur.com/EQek1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EQek1.png" alt="enter image description here"></a></p> <pre><code> mf = 0 Mtot = mSun + mEarth + mMoon mf(1:2) = mSun/(Mtot) * mf(1:2) + mEarth/(Mtot) * sol(3:4) + mMoon/(Mtot) * sol(5:6) mf(3:4) = mEarth/(Mtot) * mf(3:4) + mSun/(Mtot) * sol(1:2) + mMoon/(Mtot) * sol(5:6) mf(5:6) = mMoon/(Mtot) * mf(5:6) + mSun/(Mtot) * sol(1:2) + mEarth/(Mtot) * sol(3:4) mf(7:8) = mSun/(Mtot) * mf(7:8) + mEarth/(Mtot) * sol(9:10) + mMoon/(Mtot) * sol(11:12) mf(9:10) = mEarth/(Mtot) * mf(9:10) + mSun/(Mtot) * sol(7:8) + mMoon/(Mtot) * sol(11:12) mf(11:12) = mMoon/(Mtot) * mf(11:12) + mSun/(Mtot) * sol(7:8) + mEarth/(Mtot) * sol(9:10) sol = inits - mf </code></pre> <p>I then use a varied timestep for my calculations based off the equation:</p> <p><a href="https://i.stack.imgur.com/LL8zi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LL8zi.png" alt="enter image description here"></a></p> <pre><code>real*8 function fun_tstepq8(arr) use importants implicit none real*8,dimension(12), intent(in) :: arr real*8::alp,part1,part2,part3,distEtoS,distEtoM,distStoM real*8 :: distEdottoMdot,distEdottoSdot,distSdottoMdot alp = 1d-4 distEtoS = SQRT((sol(3)-sol(1))**2 + (sol(4)-sol(2))**2)**3 distEtoM = SQRT((sol(5)-sol(3))**2 + (sol(6)-sol(4))**2)**3 distStoM = SQRT((sol(5)-sol(1))**2 + (sol(6)-sol(2))**2)**3 distEdottoSdot = SQRT((sol(9)-sol(7))**2 + (sol(10)-sol(8))**2) distEdottoMdot = SQRT((sol(11)-sol(9))**2 + (sol(12)-sol(10))**2) distSdottoMdot = SQRT((sol(11)-sol(7))**2 + (sol(12)-sol(8))**2) part1= distEtoS/distEdottoSdot part2= distEtoM/distEdottoMdot part3= distStoM/distSdottoMdot fun_tstepq8 = alp * MIN(part1,part2,part3) end function </code></pre> <p>Putting that all together, I use a Forward Euler method and calculate the function f from y0 = y0 + hf using the subroutine:</p> <pre><code>subroutine q8RHS(sol) use importants, ONLY: mSun, mEarth,mMoon, F, G implicit none real*8 :: distEtoS,distEtoM,distStoM real*8,dimension(12) :: sol integer :: i distEtoS = SQRT((sol(3)-sol(1))**2 + (sol(4)-sol(2))**2)**3 distEtoM = SQRT((sol(5)-sol(3))**2 + (sol(6)-sol(4))**2)**3 distStoM = SQRT((sol(5)-sol(1))**2 + (sol(6)-sol(2))**2)**3 do i = 1,12 if (i &lt; 7) then F(i) = sol(i+6) elseif (i &lt; 9) then F(i) = G * (mEarth * (sol(i-4) - sol(i-6))/distEtoS + mMoon * (sol(i-2) - sol(i-6))/distStoM) elseif (i &lt; 11) then F(i) = G * mSun * (sol(i-6) - sol(i-8))/distEtoS - mMoon * G *(sol(i-4) - sol(i-6))/distEtoM else F(i) = -G * mSun * (sol(i-6) - sol(i-10))/distStoM -G*mEarth * (sol(i-6) - sol(i-8))/distEtoM endif enddo end subroutine </code></pre> <p>In terms of deriving the <code>q8RHS</code> subroutine, I started with:</p> <p><a href="https://i.stack.imgur.com/sdpvv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sdpvv.png" alt="enter image description here"></a></p> <p>And then this is my work to derive mechanics for one of the planets. Note I use the Euler method here, and derive suitable functions to use for f(x,t) = dx/dt form needed for the Euler method. Note I couldn't use the denominator I derived as at some point x2 = x1 in my simulation if I use this, hence the issue I talked about with the timestep getting tiny enough where the simulation grinds to a halt. </p> <p><a href="https://i.stack.imgur.com/1n2xu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1n2xu.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/tczQ8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tczQ8.jpg" alt="enter image description here"></a></p> <p>Overall, my program looks like this:</p> <pre><code>module importants implicit none integer,parameter::Ndim = 3 integer:: N,N2 real*8, parameter :: G = 6.67408e-11 integer,parameter :: Nbodies = 2 integer::specific_Nbodies = 2*Nbodies real*8,dimension(12) :: inits,sol,F real*8 :: d_j = 778.547200d+9 real*8 :: v_j = 13.1d+3 integer :: rank = Nbodies * Ndim * 2 real*8 :: mSun = 1.989d+30 real*8, dimension(12) :: mf real*8 :: mJup = 1.89819d+27 real*8, parameter :: pi= DACOS(-1.d0) real*8 :: a,P,FF real*8 :: pJ = 374080032d0 real*8, dimension(2) :: QEcompare,QLcompare,QPcompare real*8 :: mEarth = 5.9722d+24 real*8 :: mMoon = 7.34767309d+22 real*8 :: distE = 149597870d+3 ! Dist from sun to earth real*8 :: distM = 384400d+3 ! Dist from earth to moon real*8 :: distMS = 152d+9 real*8 :: vE = 29.78d+3 real*8 :: vM = 1.022d+3 end module program exercise3 use importants implicit none print*,'two' !call solve() !call q3() !call q4() !call q5() !call q5circ() !call q6ecc() !call q6pt2() !call q7() call q8() end program subroutine q8() use importants implicit none !real*8,external :: Epot,Ekin, L real*8,external :: fun_tstepq8 real*8 :: tstep,time,tracker,Mtot,t !real*8,dimension(2) :: Etot,L1,L2 !real*8, dimension(3,2) :: r2 integer :: j,i print*, 'Starting Q8. -------------------------------------------------------' inits(1:2) = 0d0 inits(3) = distE inits(4) = 0d0 inits(5) = distE+distM inits(6:9) = 0d0 inits(10) = vE inits(11) = 0d0 inits(12) = vM sol = inits mf = 0 Mtot = mSun + mEarth + mMoon mf(1:2) = mSun/(Mtot) * mf(1:2) + mEarth/(Mtot) * sol(3:4) + mMoon/(Mtot) * sol(5:6) mf(3:4) = mEarth/(Mtot) * mf(3:4) + mSun/(Mtot) * sol(1:2) + mMoon/(Mtot) * sol(5:6) mf(5:6) = mMoon/(Mtot) * mf(5:6) + mSun/(Mtot) * sol(1:2) + mEarth/(Mtot) * sol(3:4) mf(7:8) = mSun/(Mtot) * mf(7:8) + mEarth/(Mtot) * sol(9:10) + mMoon/(Mtot) * sol(11:12) mf(9:10) = mEarth/(Mtot) * mf(9:10) + mSun/(Mtot) * sol(7:8) + mMoon/(Mtot) * sol(11:12) mf(11:12) = mMoon/(Mtot) * mf(11:12) + mSun/(Mtot) * sol(7:8) + mEarth/(Mtot) * sol(9:10) sol = inits - mf print*, '---------------------------------------------------------------------' print*, 'Beginning fixed t timestep. ' t = 0d0 P = 3.154d+7 time=0 tracker=0 print*, 'P understood as :', P open(70,file='q8.dat') time=0 tracker=0 write(70,*) sol(1),sol(2),sol(3),sol(4),sol(5),sol(6) do while(time.le.P) call q8RHS(sol) tstep=fun_tstepq8(sol) time=time+tstep tracker=tracker+1 print*, tstep do i=1,12 sol(i) = sol(i) + tstep * F(i) enddo write(70,*) sol(1),sol(2),sol(3),sol(4),sol(5),sol(6) enddo end subroutine </code></pre> <p>I know there are a bunch of variables that are not used here, but were used for other subroutines, as this is a bit, ungainly beast of a program I've made. I just know that the previous subroutines and all of their related variables have run fine, and I have no issue with them and they don't interfere with the code I have in mind. </p> <p>Anyway, once I run the program, the time step is immediately made massive, and then the program completes in an iteration or two, as the denominators in my time step function has its denominators become tiny very quickly. Before showing the code I have here, I initially noticed that the Earth and Moon don't interact and the Moon just barrels towards the sun while the Earth orbits the Sun normally. It looked like this (note that this is with a different RHS subroutine, not the one I listed, but just for context):</p> <p><a href="https://i.stack.imgur.com/wlY8V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wlY8V.png" alt="enter image description here"></a></p> <p>I tried to then initially look at the Earth and Moon itself with a fixed time step. I eventually got them to "see eachother" (interact with their gravitational fields in a way that made sense) but as soon as the Moon got close to the Earth it slingshotted back away from it (I think as soon as it went just past the Earth so that it was just barely closer to the Sun than the Earth was) and just kept shooting away. I tried using a varied timestep, but it then had such a small timestep everything slowed down to a half once the Moon got close enough to the Earth. This was using a timestep equation that only considered the x positions of the Moon and Earth. I then tried adjusting the timestep so that it looks like how I've listed it by staring at the equation I've pictured longer, which caused the massive timesteps I've discussed. I then gave up, and brought back the Sun's presence which is the code I've listed here. I'm absolutely stumped. Here's how the trajectories look with the code I have now:</p> <p><a href="https://i.stack.imgur.com/AYcOZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AYcOZ.png" alt="enter image description here"></a></p> <p>What is wrong with my code? What aren't I simulating the orbit properly? What am I doing wrong?</p> <p><strong>UPDATE</strong></p> <p>On the advice of one of the commentors, I made <code>alp</code> smaller. Here is the result:</p> <p><a href="https://i.stack.imgur.com/ySWza.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ySWza.png" alt="enter image description here"></a></p> <p>and a more zoomed in version.</p> <p><a href="https://i.stack.imgur.com/BzFxU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BzFxU.png" alt="enter image description here"></a></p> <p>The Earth gets outright repelled, and the moon is flung towards the Sun. </p> <p><strong>UPDATE 2</strong></p> <p>I believe I corrected a mistake, as I believe the <code>q8RHS</code> bit regarding Earth's Euler function had its signs flipped.</p> <pre><code> elseif (i &lt; 11) then F(i) = -G * mSun * (sol(i-6) - sol(i-8))/distEtoS + mMoon * G *(sol(i-4) - sol(i-6))/distEtoM </code></pre> <p>Since the gravitational pull from the sun should be negative and from the moon positive given the way I've sketched it out. Here is the newest image</p> <p><a href="https://i.stack.imgur.com/WcniG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WcniG.png" alt="enter image description here"></a></p> <p><strong>UPDATE 3</strong></p> <p>I have been made aware that my initial orbital velocity for the Moon was wrong -- it must be the sum of its orbital velocity around the moon plus the Earth's orbital velocity around the sun. My motions are now:</p> <p><a href="https://i.stack.imgur.com/zq8rD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zq8rD.png" alt="enter image description here"></a></p> <p>This was obviously much more reassuring to see, but I'm not sure if the Earth and Moon are behaving properly with regards to eachother. Zooming in, the moon does seem to oscillate to the left and right of the Sun's trajectory, so if the z axis was viewable this might make more sense, but it also might not. </p> <p><a href="https://i.stack.imgur.com/UMC5G.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UMC5G.png" alt="enter image description here"></a></p> <p>The behavior above of the Moon's path moving to the left and right of the Earth's repeats constantly, but I'm not sure if this is still necessarily physically sensible. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T17:32:37.110", "Id": "471404", "Score": "0", "body": "CodeReview is for working code only, to improve clarity, efficiency, and maintainability. It does not appear your code is working yet (but it might be working fine with poor initial conditions, difficult to say), so is off-topic here. Try StackOverflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T19:55:11.050", "Id": "471413", "Score": "2", "body": "I haven't study your code in depth, but \"the moon will have an initial y velocity equal to its mean orbital velocity around the earth\" is definitely wrong. In a fixed reference frame, the moon's initial velocity should be \"mean orbital velocity around earth __plus__ earth mean orbital velocity around the sun\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T19:59:54.443", "Id": "471414", "Score": "0", "body": "@AJNeufeld I don't think (yet) that this code doesn't work. The results _seem_ to be consistent with the initial conditions. The fact that the conditions are wrong does not invalidate the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:32:39.047", "Id": "471444", "Score": "2", "body": "Please can you translate your images to [MathJax](https://math.meta.stackexchange.com/q/5020). Note that we use `\\$` rather than `$` for inline formula. `\\$f\\$` -> \\$f\\$. This increases the accessibility of your post for users with visual impairments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:55:10.557", "Id": "471448", "Score": "0", "body": "@vnp you're quite right about the orbital velocity bit. I'll update with my results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T03:36:29.903", "Id": "471453", "Score": "0", "body": "Your result now is quite sensible. The moon is moving from the far side (full moon) to the near side (new moon) and back to the far side. Those oscillations should have a period of one month." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T10:31:41.687", "Id": "471475", "Score": "0", "body": "@AJNeufeld I see. Is this shown adequately in the images I posted in Update 3?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T14:12:56.450", "Id": "471498", "Score": "1", "body": "Thanks for your efforts, and please keep in mind the code should work *before* posting the first version next time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:29:59.053", "Id": "471510", "Score": "0", "body": "No, it does not adequately show it. You should add larger dots for the positions of the earth & moon (say) every 4 days, so you can visually see snapshots of the relative earth/moon positions." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T15:27:36.747", "Id": "240345", "Score": "3", "Tags": [ "beginner", "recursion", "fortran" ], "Title": "Simulating the orbits of the Earth, Moon and Sun together in Fortran" }
240345
<p><a href="https://leetcode.com/problems/delete-nodes-and-return-forest/" rel="nofollow noreferrer">https://leetcode.com/problems/delete-nodes-and-return-forest/</a></p> <p>Given the root of a binary tree, each node in the tree has a distinct value.</p> <p>After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).</p> <p>Return the roots of the trees in the remaining forest. You may return the result in any order.</p> <p><a href="https://i.stack.imgur.com/HLxRT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HLxRT.png" alt="enter image description here"></a></p> <blockquote> <p>Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] </p> <p>Constraints:</p> <p>The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length &lt;= 1000 to_delete contains distinct values between 1 and 1000.</p> </blockquote> <p>Please review for performance and style.</p> <pre><code>using System.Collections.Generic; using System.Linq; using GraphsQuestions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TreeQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/delete-nodes-and-return-forest/ /// &lt;/summary&gt; [TestClass] public class DeleteNodesAndReturnForestTest { [TestMethod] public void ExampleTest() { var 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); root.right.left = new TreeNode(6); root.right.right=new TreeNode(7); var deleteNodes=new DeleteNodesAndReturnForest(); var res = deleteNodes.DelNodes(root, new[] {3, 5}); Assert.AreEqual(6,res[0].val); Assert.AreEqual(7,res[1].val); Assert.AreEqual(1,res[2].val); Assert.AreEqual(2,res[2].left.val); Assert.AreEqual(4,res[2].left.left.val); Assert.IsNull(res[2].left.right); } } public class DeleteNodesAndReturnForest { List&lt;TreeNode&gt; _forest; public IList&lt;TreeNode&gt; DelNodes(TreeNode root, int[] to_delete) { if (root == null || to_delete == null || to_delete.Length == 0) { return _forest; } _forest = new List&lt;TreeNode&gt;(); Helper(root, to_delete); if (!to_delete.Contains(root.val)) { _forest.Add(root); } return _forest; } private TreeNode Helper(TreeNode root, int[] to_delete) { if (root == null) { return null; } //first do the recursion root.left = Helper(root.left, to_delete); root.right = Helper(root.right, to_delete); //when coming back from recursion(post-order). all the subtrees is already deleted //delete root and add to the forest the left and right leaves if (to_delete.Contains(root.val)) { if (root.left != null) { _forest.Add(root.left); } if (root.right != null) { _forest.Add(root.right); } return null; } return root; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T21:08:59.623", "Id": "471419", "Score": "0", "body": "Just wondering: does `gili` convey any meaning?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T21:33:23.520", "Id": "471424", "Score": "0", "body": "@vnp LOL my name is Gilad just a nick name for temp variable. I forgot to replace." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T15:56:44.453", "Id": "240346", "Score": "0", "Tags": [ "c#", "programming-challenge", "depth-first-search", "binary-tree" ], "Title": "LeetCode: Delete Nodes And Return Forest C#" }
240346
<p>I am working on a react native android app that generates fancy text. Similar to this <a href="https://coolsymbol.com/cool-fancy-text-generator.html" rel="nofollow noreferrer">Fancy Text Generator</a></p> <p>For every letter being typed fancy text will be generated.</p> <p>I implemented everything and it works perfectly however the performance is very slow. Whenever I write text, the fancy text changes very slow and gets slower when the text becomes very large. I think it is the problem with the flatlist being rendered everytime the text changes or maybe with my textgeneration function. I tried everything to optimize it but it was still noticably slower even in the final build of APK file.</p> <p>Here is the function that generates the fancy text:</p> <pre><code>remap = () =&gt; { let newtext = Array(51).fill("") let regText = `${this.state.inputdata}` != "" ? `${this.state.inputdata}` : "example" let normal = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890` let normal2 = `a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0` let normal3 = `a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0` let lent = regText.length for (var i = 0; i &lt; regText.length; i++) { let sliced = regText.slice(i, i + 1) let indexed = normal.indexOf(sliced) let indexed2 = normal2.indexOf(sliced) let indexed3 = normal3.indexOf(sliced) if (normal.includes(sliced)) { newtext[0] += [...fonts.font24][indexed]; newtext[1] += [...fonts.font15][indexed]; newtext[2] += [...fonts.font26][indexed]; newtext[3] += [...fonts.font23][indexed]; newtext[4] += [...fonts.font14][indexed]; newtext[5] += [...fonts.font5][indexed]; //reverse remap newtext[6] += [...fonts.font4][indexed]; newtext[7] += [...fonts.font25][indexed]; newtext[8] += [...fonts.font0][indexed]; newtext[9] += [...fonts.font21][indexed]; newtext[10] += [...fonts.font22][indexed]; newtext[11] += [...fonts.font19][indexed]; newtext[12] += [...fonts.font18][indexed]; newtext[13] += [...fonts.font17][indexed]; newtext[14] += [...fonts.font16][indexed]; newtext[15] += [...fonts.font2][indexed]; newtext[16] += [...fonts.font20][indexed]; newtext[17] += [...fonts.font6][indexed]; newtext[18] += fonts.font3[indexed3] + fonts.font3[indexed3 + 1] + fonts.font3[indexed3 + 2]; newtext[19] += [...fonts.font1][indexed]; newtext[20] += [...fonts.font27][indexed]; newtext[21] += [...fonts.font28][indexed]; newtext[22] += [...fonts.font7][indexed]; newtext[23] += [...fonts.font11][indexed]; newtext[24] += [...fonts.font10][indexed]; newtext[25] += [...fonts.font13][indexed]; newtext[26] += fonts.font8[indexed2] + fonts.font8[indexed2 + 1]; newtext[27] += [...fonts.font9][indexed]; newtext[28] += [...fonts.font12][indexed]; newtext[29] += normal[indexed] + '̲'; newtext[30] += normal[indexed] + '̶'; newtext[31] += normal[indexed] + '͙'; newtext[32] += normal[indexed] + '̟'; newtext[33] += normal[indexed] + '̃'; newtext[34] += normal[indexed] + '͎'; newtext[35] += normal[indexed] + '̺'; newtext[36] += normal[indexed] + '͆'; newtext[37] += normal[indexed] + '̳'; newtext[38] += normal[indexed] + '̈'; newtext[39] += normal[indexed] + '̾'; newtext[40] += normal[indexed] + '͓̽'; newtext[41] += normal[indexed] + '̸'; newtext[42] += normal[indexed] + '҉ '; newtext[43] += normal[indexed] + '҈ '; newtext[44] += [...fonts.font29][indexed]; newtext[45] += [...fonts.font30][indexed]; newtext[46] += [...fonts.font31][indexed]; newtext[47] += [...fonts.font32][indexed]; newtext[48] += [...fonts.font33][indexed]; newtext[49] += [...fonts.font34][indexed]; newtext[50] += [...fonts.font35][indexed]; } else { for (let i = 0; i &lt; 51; i++) newtext[i] += sliced.toString(); } } newtext[5] = newtext[5].split('').reverse().join('') return newtext } </code></pre> <p>And here is my flatlist code:</p> <pre><code> &lt;FlatList ref={component=&gt; this._MyComponent=component} style={{ marginTop: 10 }} data = { this.remap() } //&lt;--Function is called here on every change in text. initialNumToRender={10} keyExtractor={( item, index) =&gt; 'key' + index} renderItem={({ item }) =&gt; ( &lt;TouchableHighlight underlayColor={'#ecf0f1'} style={styles.flatview} onPress={this.getListViewItem.bind(this, item)}&gt; &lt;View style={styles.Listviu}&gt; &lt;Text numberOfLines={1} ellipsizeMode="head" style={styles.item}&gt; {item} &lt;/Text&gt; &lt;TouchableOpacity onPress={this._onPressButton.bind(this, item)}&gt; &lt;Icon name="copy" size={28} color="#7966FE" /&gt; &lt;/TouchableOpacity&gt; &lt;TouchableOpacity onPress={this.shareit.bind(this, item)} style={{paddingLeft: 4}}&gt; &lt;Icon name="share-2" size={28} color="#7966FE" /&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; &lt;/TouchableHighlight&gt; ) } /&gt; </code></pre> <p>Here is how my app looks like:</p> <p><a href="https://i.stack.imgur.com/GEmKs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GEmKs.jpg" alt="enter image description here"></a></p> <p>I have the unicode data in the seperate JSON file which is used by the function.</p> <pre><code>{ "font0": "αвc∂εғgнιנкℓмησρqяsтυvωxүzαвc∂εғgнιנкℓмησρqяsтυvωxүz1234567890", "font1": "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", "font2": "ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ①②③④⑤⑥⑦⑧⑨⓪", "font3": "‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌‌ 1 2 3 4 5 6 7 8 9 0", "font4": "αɓc∂εƒɠɦเʝҡℓɱɳσρφɾรƭµѵωϰყƶαɓc∂εƒɠɦเʝҡℓɱɳσρφɾรƭµѵωϰყƶ1234567890", "font5": "ɐqɔpǝɟƃɥᴉɾʞlɯuodbɹsʇnʌʍxʎz∀ᗺϽᗭƎℲ⅁HIſꞰꞀꟽNOԀΌꞞS⊥ᑎΛMXʎZ1234567890", "font6": "ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘϙʀsᴛᴜᴠᴡxʏᴢᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘϙʀsᴛᴜᴠᴡxʏᴢ1234567890", "font7": "ᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖᵠʳˢᵗᵘᵛʷˣʸᶻᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖᵠʳˢᵗᵘᵛʷˣʸᶻ₁₂₃₄₅₆₇₈₉₀", "font8": "aⷮbⷥcͩdͯeⷦfͩgⷬhⷮiͭjⷭkͪlⷨmͥnⷬoͤpͣqⷬrͤsͫtͨuⷬvⷦwⷦxͪyͭzͭaⷮbⷥcͩdͯeⷦfͩgⷬhⷮiͭjⷭkͪlⷨmͥnⷬoͤpͣqⷬrͤsͫtͨuⷬvⷦwⷦxͪyͭzͭ 1 2 3 4 5 6 7 8 9 0", "font9": "卂乃匚ⅅ乇千G卄丨丿Ҡㄥ爪几ㄖ卩Ɋ尺丂ㄒ凵V山乂ㄚ乙卂乃匚ⅅ乇千G卄丨丿Ҡㄥ爪几ㄖ卩Ɋ尺丂ㄒ凵V山乂ㄚ乙1234567890", "font10": "⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵⑴⑵⑶⑷⑸⑹⑺⑻⑼⒪", "font11": "ค๒ς๔єŦgђเʝкl๓ภ๏ρợгรtยѵฬϰՎzค๒ς๔єŦgђเʝкl๓ภ๏ρợгรtยѵฬϰՎz1234567890", "font12": "₳Ƀ€ƉɆ₣₲ĦƗɈԞⱠM₦Ø₱QɌ$₮ɄV₩Ӿ¥Ƶ₳Ƀ€ƉɆ₣₲ĦƗɈԞⱠM₦Ø₱QɌ$₮ɄV₩Ӿ¥Ƶ1234567890", "font13": "äḅċďệḟġḧïjḳŀṃńöṗqŕṩẗüṿẅẍÿẓÄḄĊĎỆḞĠḦÏJḲĿṂŃÖṖQŔṨṮÜṾẄẌŸẒ1234567890", "font14": "", "font15": "1234567890", "font16": "", "font17": "", "font18": "1234567890", "font19": "ℎ1234567890", "font20": "1234567890", "font21": "❶❷❸❹❺❻❼❽❾⓿", "font22": "ℭℌℑℜℨ1234567890", "font23": "1234567890", "font24": "", "font25": "ℂℍℕℙℚℝℤ", "font26": "ℯℊℴℬℰℱℋℐℒℳℛ1234567890", "font27": "1234567890", "font28": "1234567890", "font29": "1234567890", "font30": "ꋫꃃꏸꁕꍟꄘꁍꑛꂑꀭꀗ꒒ꁒꁹꆂꉣꁸ꒓ꌚ꓅ꐇꏝꅐꇓꐟꁴꋫꃃꏸꁕꍟꄘꁍꑛꂑꀭꀗ꒒ꁒꁹꆂꉣꁸ꒓ꌚ꓅ꐇꏝꅐꇓꐟꁴ1234567890", "font31": "ᗩᗷᑕᗪEᖴGᕼIᒍKᒪᗰᑎOᑭᑫᖇᔕTᑌᐯᗯ᙭YᘔᗩᗷᑕᗪEᖴGᕼIᒍKᒪᗰᑎOᑭᑫᖇᔕTᑌᐯᗯ᙭Yᘔ1234567890", "font32": "ДБCDΞFGHIJҜLMИФPǪЯSΓЦVЩЖУZДБCDΞFGHIJҜLMИФPǪЯSΓЦVЩЖУZ1234567890", "font33": "ąβȼď€ƒǥhɨjЌℓʍɲ๏ρǭя$ţµ˅ώж¥ƶąβȼď€ƒǥhɨjЌℓʍɲ๏ρǭя$ţµ˅ώж¥ƶ1234567890", "font34": "ÃβČĎẸƑĞĤĮĴЌĹϻŇỖƤǪŘŜŤǗϋŴЖЎŻÃβČĎẸƑĞĤĮĴЌĹϻŇỖƤǪŘŜŤǗϋŴЖЎŻ1234567890", "font35": "ᴬᴮᶜᴰᴱᶠᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾᵟᴿˢᵀᵁᵛᵂˣᵞᶻᴬᴮᶜᴰᴱᶠᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾᵟᴿˢᵀᵁᵛᵂˣᵞᶻ1234567890"} </code></pre> <p>Here is the entire <a href="https://github.com/AzizStark/Quiva/blob/master/App.js" rel="nofollow noreferrer">Code</a>.</p> <p>Please help.</p>
[]
[ { "body": "<p>The main problem is here:</p>\n\n<pre><code>for (var i = 0; i &lt; regText.length; i++) {\n // ...\n if (normal.includes(sliced)) {\n newtext[0] += [...fonts.font24][indexed];\n newtext[1] += [...fonts.font15][indexed];\n newtext[2] += [...fonts.font26][indexed];\n // many more\n</code></pre>\n\n<p>For <em>every character</em> of the input, you're spreading <em>every font</em> into a new array. With 28 fonts and 40 characters, that's 1120 arrays that need to be created. before <code>remap</code> is done - and each of those arrays is a font, so it has to iterate through all characters in the font for each such array.</p>\n\n<p>If the <code>fonts.font</code> properties are array-like structures, there should be no need to spread:</p>\n\n<pre><code>newtext[0] += fonts.font24[indexed];\nnewtext[1] += fonts.font15[indexed];\nnewtext[2] += fonts.font26[indexed];\n</code></pre>\n\n<p>If they're <em>not</em> array-like structures, and you really do have to invoke their iterators, invoke the iterators <em>once</em>, at the beginning of the app, rather than on every new input, for every character, see the next code block.</p>\n\n<p>In order to have the <code>fontArrays</code> be persistent over the lifetime of the app, but still only scoped to the <code>remap</code> function, you can make it into an IIFE:</p>\n\n<pre><code>remap = (() =&gt; {\n const fontArrays = [];\n for (let i = 0; i &lt; 36; i++) {\n fontArrays.push([...fonts['font' + i]]);\n }\n return () =&gt; {\n const newtext = Array(51).fill(\"\");\n // ...\n };\n})();\n</code></pre>\n\n<p>Then, replace the lines like</p>\n\n<pre><code>newtext[0] += [...fonts.font24][indexed];\nnewtext[1] += [...fonts.font15][indexed];\nnewtext[2] += [...fonts.font26][indexed];\n</code></pre>\n\n<p>with</p>\n\n<pre><code>newtext[0] += fontArrays[24][indexed];\nnewtext[1] += fontArrays[15][indexed];\nnewtext[2] += fontArrays[26][indexed];\n</code></pre>\n\n<p>If at all possible, it would also be good to change the definition of your <code>fonts.font#</code> properties such that they're an array of fonts, rather than an object of numeric-indexed properties. That is, to reference a font, it'd be nice to be able to do</p>\n\n<pre><code>fonts[24]\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>fonts.font24\n</code></pre>\n\n<p>Other possible improvements to the code:</p>\n\n<p><a href=\"https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75\" rel=\"nofollow noreferrer\">Always use <code>const</code></a> when possible, never use <code>var</code>, use <code>let</code> only when <code>const</code> can't be used - <code>const</code> makes the code more readable, when a reader can be sure that a variable name won't be reassigned.</p>\n\n<p>There's no need to use a template literal to interpolate a single variable and nothing else, as you're doing with:</p>\n\n<pre><code>let regText = `${this.state.inputdata}` != \"\" ? `${this.state.inputdata}` : \"example\"\n</code></pre>\n\n<p>Given how you're using it, it looks like <code>inputdata</code> it's already a string, so instead use</p>\n\n<pre><code>const regText = this.state.inputdata || 'example';\n</code></pre>\n\n<p>(if it's not already a string, call <code>String</code> on it: <code>String(this.state.inputdata) || 'example'</code>)</p>\n\n<p>If you're going to use semicolons (which is a great idea unless you're determined <em>not</em> to use them and are experienced enough to avoid ASI pitfalls), best to use them everywhere - it's good to pick a style and be consistent. Consider using a linter like <a href=\"http://eslint.org/\" rel=\"nofollow noreferrer\">ESLint</a>. (If you don't, and you accidentally miss adding a semicolon or few, you'll occasionally run into <a href=\"https://stackoverflow.com/questions/38050219/es6-array-destructuring-weirdness\">weird bugs</a>)</p>\n\n<p><code>String.prototype.includes</code>, like <code>indexOf</code>, has <code>O(n)</code> complexity. The interpreter has to search through <em>every character</em> of the string to see if there's a match. Since you're already checking <code>normal.indexOf(sliced)</code>, how about comparing that against <code>-1</code> instead of using <code>.includes</code> to do the same thing again?</p>\n\n<p>You can also use the string iterator instead of a <code>for</code> loop, making the code a bit prettier.</p>\n\n<p>It would also be nice not to have the horribly repetitive listing of indicies to <code>+=</code> to <code>newtext</code>. Consider creating an array of font indicies that are iterated over first, to replace all the <code>+= [...fonts.font24][indexed];</code>. Afterwards, you can insert the <em>other</em> parts which don't conform to that pattern, like for <code>newtext[18]</code> and <code>newtext[26]</code>.</p>\n\n<pre><code>const fontOrder = [24, 15, 26, 23, 14, 5 /* ... */ ];\n// these are the characters to for newtext[30] to newtext[43]\nconst otherChars = ['̲', '̶', '͙', '̟', '̃', /* /* ... */ ]\nconst otherCharsNewText = otherChars.map(() =&gt; '');\n\n// define these out here so we're not splice-ing on every iteration below\nlet insertAt18 = '';\nlet insertAt26 = '';\nfor (const char of regText) {\n const indexed = normal.indexOf(char);\n if (indexed !== -1) {\n const indexed2 = normal2.indexOf(char)\n const indexed3 = normal3.indexOf(char)\n\n fontOrder.forEach((fontIndex, i) =&gt; {\n newtext[i] += fontArrays[fontIndex][indexed];\n });\n\n // Then insert the other parts:\n // use slice instead of concatenating indicies:\n insertAt18 += fontArrays[3].slice(indexed3, indexed3 + 3);\n insertAt26 += fontArrays[2].slice(indexed2, indexed2 + 2);\n\n otherChars.forEach((char, i) =&gt; {\n otherCharsNewText[i] += normal[indexed] + char;\n });\n } else {\n for (let i = 0; i &lt; 51; i++) {\n newtext[i] += char;\n }\n }\n}\n// Then insert the insertAt18, insertAt26, and otherCharsNewText into the newtext:\nnewText.splice(18, 0, insertAt18);\nnewText.splice(26, 0, insertAt26);\nnewText.splice(29, 0, ...otherCharsNewText);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:12:22.210", "Id": "471545", "Score": "0", "body": "Thankyou very much.. you are great!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T22:48:51.263", "Id": "240367", "ParentId": "240349", "Score": "1" } } ]
{ "AcceptedAnswerId": "240367", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T16:35:23.440", "Id": "240349", "Score": "2", "Tags": [ "javascript", "react.js", "react-native" ], "Title": "How to change the text in the flatlist items with improved performance?" }
240349
<p>I have recently completed the code challenge for exercise 48 in Learn Python3 the Hard Way. I was looking for any feedback on my solution and any ideas for improvement!</p> <p>The full task can be found <a href="http://cglab.ca/~morin/teaching/1405/lpthw/book/ex48.html" rel="nofollow noreferrer">here</a>:</p> <p>The project involved taking the test code and creating a script that works from it. The test code can be found <a href="https://github.com/alexbozhkov/Learn-Python-The-Hard-Way-ex48/blob/master/tests/ex48_tests.py" rel="nofollow noreferrer">here</a> (not my upload).</p> <p>It passes all the tests, but after at other solutions I doubt my solution. Is my solution effective / efficient?</p> <pre><code>def scan(sentence): rebuild = [] directions = ['north', 'south', 'east'] verbs = ['go', 'kill', 'eat'] stops = ['the', 'in', 'of'] nouns = ['bear', 'princess'] split_line = sentence.split() for word in split_line.copy(): try: if int(word): rebuild.append(("number", int(word))) split_line.remove(word) except ValueError: pass for word in split_line: if word in directions: rebuild.append(("direction", word)) elif word in verbs: rebuild.append(("verb", word)) elif word in stops: rebuild.append(("stop", word)) elif word in nouns: rebuild.append(("noun", word)) else: rebuild.append(("error", word)) return rebuild </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T19:24:27.257", "Id": "471410", "Score": "1", "body": "Your question title is completely meaningless. Also describe what your code is supposed to do please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:23:42.593", "Id": "471442", "Score": "2", "body": "Please can you include the problem statement, currently it's unclear what you are solving. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-26T11:01:38.593", "Id": "473366", "Score": "1", "body": "The problem statement has to be included in the question itself. Links can rot." } ]
[ { "body": "<p><strong>Rule of 3</strong></p>\n\n<p>One of the main things to look for when refactoring code is the same few lines repeated. Some use the <a href=\"https://en.wikipedia.org/wiki/Rule_of_three_(computer_programming)\" rel=\"nofollow noreferrer\">rule of three</a> - if the same section is written more than three times the solution is inefficient. Looking at your code, the if-elif-else block seems like a good start to refactoring.</p>\n\n<p><strong>Some changes I would make:</strong></p>\n\n<ul>\n<li>Move to a dictionary structure to make expansion easier</li>\n<li>Use a <code>for</code> loop over key value pairs</li>\n</ul>\n\n<p><strong>Data Structures</strong></p>\n\n<p>This re-structures your data to be in a key-value format using Python's <a href=\"https://docs.python.org/3/tutorial/datastructures.html#dictionaries\" rel=\"nofollow noreferrer\">dictionaries</a>. This would allow you have the word \"type\" as the key and lookup which words are in the entry for the key. The whole if-elif-else block can be cut down to one for loop. This allows you to expand to more word types without needing to write more if else statements. The for loop would not automatically pick up errors so you can use an <code>else</code> statement. This will run whenever the for loop does not reach a break - this means that no words satisfy the values of the keys.</p>\n\n<p><strong>Reviewed code</strong></p>\n\n<pre><code>def scan(sentence):\n rebuild = []\n word_types = {\n \"directions\": ['north', 'south', 'east'],\n \"verbs\": ['go', 'kill', 'eat']\n \"stops\": ['the', 'in', 'of'],\n \"nouns\": ['bear', 'princess']\n }\n\n split_line = sentence.split()\n\n for word in split_line[:]:\n try:\n if int(word):\n rebuild.append((\"number\", int(word)))\n split_line.remove(word)\n except ValueError:\n pass\n\n for word in split_line:\n for key, value in word_types.items():\n if word in value:\n rebuild.append(key,word)\n break\n else:\n rebuild.append((\"error\", word))\n</code></pre>\n\n<p>I also used <code>[:]</code> to express copying a list, but using <code>.copy()</code> is fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T12:20:06.160", "Id": "471480", "Score": "1", "body": "Thank you, this was really helpful! I had a feeling a dictionary would be a good alternative, so thank you for explaining how and clearly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T11:27:15.977", "Id": "240385", "ParentId": "240355", "Score": "3" } } ]
{ "AcceptedAnswerId": "240385", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T19:21:32.117", "Id": "240355", "Score": "0", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Python User Input" }
240355
<p>Purpose of this small module is to allow memoization of slow URL get requests. I intend to send many of these to download a bunch of files from internal (rather slow, old) website. Some requests may repeat many times - thus the memoization. Website is old so I'm limiting concurrent requests to 100.</p> <p>I would love to hear code review remarks as I'm not a profession programmer but a user of python, so love to learn.</p> <p>Thank you! </p> <pre><code>import os import asyncio import aiohttp import functools import aredis proxy = os.environ.get("https_proxy") redis = aredis.StrictRedis() sem = asyncio.Semaphore(100) async def cache_in(url, body): """Keep url-&gt; body key value in redis""" return await redis.set(url, body) async def cache_out(url): """Get url body out from redis""" return await redis.get(url) def redismem(func): """Redis memoize decorator.""" @functools.wraps(func) async def inner(url): if body := await cache_out(url): return body body = await func(url) await cache_in(url, body) return body return inner @redismem async def get(url): """Get url""" async with aiohttp.ClientSession() as session: async with sem, session.get(url, proxy=proxy) as resp: body = await resp.read() return body </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T04:11:36.613", "Id": "471456", "Score": "0", "body": "If you download files from a remote server, you have I/O bound processing. If your server is slow, you won’t speed up the overall processing with 100 concurrent requests. You may have good results with only one request at a time (w/o concurrency). However, using a cache is a good idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T09:03:20.513", "Id": "471466", "Score": "0", "body": "Thank you Laurent. The server is \"modern\" slow but can support up to ~100 concurrent requests. I have testested this, 100 concurrent requests is almost literally 100 times faster that 100 sequential." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T20:03:53.983", "Id": "240356", "Score": "1", "Tags": [ "python", "async-await", "redis" ], "Title": "Memoization of slow URL get requests" }
240356
<p>I am using <a href="https://github.com/Moya/Moya" rel="nofollow noreferrer">Moya</a> to make network calls in Swift.</p> <p>In my <code>ViewController</code> I am calling the WebService and creating a model from response.</p> <pre><code>import UIKit import Moya class LoginViewController: UIViewController { let provider = MoyaProvider&lt;Api&gt;() override func viewDidLoad() { super.viewDidLoad() generateAccessToken() } private func generateAccessToken() { provider.request(.generateAccessToken( mobile: phoneTextField.text!, countryCode: "91", name: "Saurabh", otp: "9612") ) { result in switch result { case .success(let response): let data = response.data let user = try? JSONDecoder().decode(User.self, from: data) if let authToken = user?.authToken { AuthManager.setToken(token: authToken) } case .failure(let error): print(error.response?.statusCode as Any) } } } </code></pre> <p>I want to move the WebService call to other file, say <code>NetworkManager.swift</code></p> <pre><code>import Foundation import Moya struct NetworkManager { public static let shared = NetworkManager() private let provider = MoyaProvider&lt;Api&gt;() func generateAccessToken(with mobile: String, countryCode: String, name: String, otp: String) { // Get result and return to calling class } } </code></pre> <p>But it is strongly recommended not to use Singleton Class.</p> <p>How should I call my WebService and return the response to the <code>LoginViewController</code>?</p>
[]
[ { "body": "<p>I would recommend looking into MVVM architecture. You can see a simple example in this <a href=\"https://github.com/arifinfrds/iOS-MVVM-Moya\" rel=\"nofollow noreferrer\">repo</a>.</p>\n<p>One problem with it is that its author declares and assigned view models directly in a <code>ViewController</code> which can be a bit problematic when writing tests. A better approach would be to inject view model so it can be easily replaced with mock. To improve that approach you can take a look at coordinators patterns, a bit more advanced example can be found <a href=\"https://academy.realm.io/posts/mobilization-lukasz-mroz-mvvm-coordinators-rxswift/\" rel=\"nofollow noreferrer\">here</a></p>\n<p>In most cases the <code>WebService</code> should go in the <code>ViewModel</code> in the MVVM pattern. Services can be injected to <code>ViewModels</code>, which are responsible for managing data provided by these services. Then when they perform all logical transformations (filtering, ordering, multiplying etc.) they provide this information to a view (<code>ViewController</code> in our case) which just consumes it. It allows us to easily write mocks and tests. There are of course more approaches like state machine, but <code>ViewModel</code> as content provider and meeting point for services is most common and most universal one in my opinion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:06:03.347", "Id": "471530", "Score": "0", "body": "Thanks for this. I have reading about MVVM. Just a quick clarification: should the WebService go in ViewModel in MVVM pattern?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:10:34.343", "Id": "471533", "Score": "0", "body": "In most cases - yes. Services can be injected to ViewModels, which are responsible for managing data provided by these services. Then when they perform all logical transformations (filtering, ordering, multiplying etc.) they provide this information to a view (ViewController in our case) which just consumes it. It allows us to easily write mocks and tests. \n\nThere are of course more approaches like state machine, but ViewModel as content provider and meeting point for services is most common and most universal one in my opinion." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:01:28.090", "Id": "240404", "ParentId": "240357", "Score": "2" } }, { "body": "<p>Could you make the following changes:</p>\n\n<p>1) Create a file named LoginViewModel.swift</p>\n\n<pre><code>func getAccessToken(with mobile: String, code: String, otp: String, name: String, completion: @escaping(Bool, String)-&gt;Void) {\n networkManager.getAccessTokenFrom(mobile: mobile, code: String, otp: code, name: name) { (isSuccess, error) in\n if isSuccess {\n // Do neccessary logic\n // Set access token logic here\n completion(true, \"\")\n }\n else {\n completion(false, error.description)\n }\n }\n}\n</code></pre>\n\n<p>2) Create a similar function in NetworkManager class to interact with Moya framework</p>\n\n<pre><code>let provider = MoyaProvider&lt;Api&gt;()\n\nfunc getAccessTokenFrom(mobile: String, code: String, otp: String, name: String, completion: @escaping(error, String)-&gt;Void) {\n provider.request(.generateAccessToken(\n mobile: mobile,\n countryCode: code,\n name: name,\n otp: otp)\n ) { result in\n switch result {\n case .success(let response):\n let data = response.data\n let user = try? JSONDecoder().decode(User.self, from: data)\n if let authToken = user?.authToken {\n completion(true, authToken)\n }\n case .failure(let error):\n completion(false, error.description)\n\n } \n}}\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>Inside LoginViewController.swift:</li>\n</ol>\n\n<pre><code>let loginViewModel = LoginViewModel()\n\nfunc viewDidload() {\n // start activity loader\n loginViewModel.getAccessToken(with mobile: mobileTField.text, code: codeTField.text, otp: otpTField.text, name: nameTField.text) { (isSuccess, error) in\n if isSuccess {\n // Hide activity loader\n }\n else {\n // Show alert based on the \"error\" variable value\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T16:22:22.760", "Id": "472437", "Score": "2", "body": "Welcome to code review. Good answers are observations about the code, and not necessarily alternate implementations. It would improve your answer, if you explained why each of these modifications are necessary. A good answer MUST include at least one observation about the code, and this answer doesn't contain any observations about the code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T11:40:58.410", "Id": "240788", "ParentId": "240357", "Score": "-1" } }, { "body": "<p>I think what you are missing is dependency injection and dependency inversion.</p>\n\n<p>You should have something like</p>\n\n<pre><code>let keychainService = KeychainService()\nlet apiClient = ApiClient(keychainService: keychainService)\nlet loginService = LoginService(apiClient: apiClient, keychainService: keychainService)\nlet loginViewController = LoginViewController(loginService: loginService)\n</code></pre>\n\n<p>everything about headers and http goes to ApiClient, as well as adding the token to some requests, and retries.\neverything about requesting a new user goes to loginService.\nfor reading and saving tokens and perhaps current user info, you can use KeychainService.</p>\n\n<p>Note that you have to use protocols, so, the view controller relies on an abstraction, not a concrete implementation.</p>\n\n<p>To manage this, you can use factory methods (a method that returns the view controller properly initialised) or frameworks like winject or DIP.</p>\n\n<p>BTW, when using dependency inversion and injection, it is super easy to apply unit testing. You can very easily to create a mock of the login service and test that your view controller works fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-15T19:08:53.117", "Id": "242363", "ParentId": "240357", "Score": "1" } } ]
{ "AcceptedAnswerId": "240404", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T20:14:52.820", "Id": "240357", "Score": "2", "Tags": [ "design-patterns", "swift", "ios", "networking" ], "Title": "I want to take away WebService call from UIViewController" }
240357
<p>I have implemented the calculation of gamma value for RBF SVM as described in Liu et al (2012) [<a href="https://ieeexplore.ieee.org/abstract/document/6246300]" rel="nofollow noreferrer">https://ieeexplore.ieee.org/abstract/document/6246300]</a>. Here's a snapshot of the example from the paper:</p> <p><a href="https://i.stack.imgur.com/piSnM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/piSnM.png" alt="Snapshot showing the calculation of optimal gamma value for RBF SVM"></a></p> <p>Here is my implementation in MATLAB:</p> <pre><code>% Let data be a table type variable with 1st column having class label and % variables X1 ... Xn from 2nd column onwards % Split data by class data_class0 = data{data.Class==0,2:end}; data_class1 = data{data.Class==1,2:end}; % Calculate within class squared Euclidean distances d_within_class0 = squareform(pdist(data_class0, 'squaredeuclidean')); d_within_class1 = squareform(pdist(data_class1, 'squaredeuclidean')); % Calculate between class squared Euclidean distances d_between_class = pdist2(data_class0, data_class1, 'squaredeuclidean'); % Calculate average W and B values W = mean([d_within_class0(:); d_within_class1(:)], 'all'); B = mean(d_between_class(:)); % Calculate optimal gamma if B &gt; W gamma = sqrt((B-W)/(4*log(B/W))); else disp('Gamma cannot be calculated as B &lt; W'); end </code></pre> <p>I am looking for feedback on whether or not this implementation is correct and any thing that might need improvement. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T20:25:27.530", "Id": "240358", "Score": "2", "Tags": [ "machine-learning", "matlab" ], "Title": "Implementation of calculation of gamma for RBF SVM" }
240358
<p><a href="https://leetcode.com/problems/minesweeper/" rel="nofollow noreferrer">https://leetcode.com/problems/minesweeper/</a></p> <p>please review for performance. I really don't like the implementation I made for GetNumberOfMines() function, but within the time limits i did this. it is easy to understand but probably bad in performance.</p> <blockquote> <p>Let's play the minesweeper game (Wikipedia, online game)!</p> <p>You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit ('1' to '8') represents how many mines are adjacent to this revealed square, and finally 'X' represents a revealed mine.</p> <p>Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), return the board after revealing this position according to the following rules:</p> <p>If a mine ('M') is revealed, then the game is over - change it to 'X'. If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively. If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines. Return the board when no more squares will be revealed.</p> </blockquote> <pre><code>Example 1: Input: [['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'M', 'E', 'E'], ['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E']] Click : [3,0] Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] </code></pre> <p><a href="https://i.stack.imgur.com/eq7fa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eq7fa.png" alt="enter image description here"></a></p> <blockquote> <p>Note:</p> <p>The range of the input matrix's height and width is [1,50]. The click position will only be an unrevealed square ('M' or 'E'), which also means the input board contains at least one clickable square. The input board won't be a stage when game is over (some mines have been revealed). For simplicity, not mentioned rules should be ignored in this problem. For example, you don't need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares.</p> </blockquote> <pre><code>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TreeQuestions { [TestClass] public class MineSweeperTest { [TestMethod] public void ExampleTest() { char[][] input = { new []{'E', 'E', 'E', 'E', 'E'}, new []{'E', 'E', 'M', 'E', 'E'}, new []{'E', 'E', 'E', 'E', 'E'}, new []{'E', 'E', 'E', 'E', 'E'} }; char[][] output = { new []{'B', '1', 'E', '1', 'B'}, new []{'B', '1', 'M', '1', 'B'}, new []{'B', '1', '1', '1', 'B'}, new []{'B', 'B', 'B', 'B', 'B'} }; var mineSweeper = new MineSweeper(); var res = mineSweeper.UpdateBoard(input, new[] { 3, 0 }); for (var index = 0; index &lt; res.Length; index++) { CollectionAssert.AreEqual(output[index], res[index]); } } [TestMethod] public void FailedTest() { char[][] input = { new []{'E', 'E', 'E', 'E', 'E','E','E','E'}, new []{'E', 'E', 'E', 'E', 'E','E','E','M'}, new []{'E', 'E', 'M', 'E', 'E','E','E','E'}, new []{'M', 'E', 'E', 'E', 'E','E','E','E'}, new []{'E', 'E', 'E', 'E', 'E','E','E','E'}, new []{'E', 'E', 'E', 'E', 'E','E','E','E'}, new []{'E', 'E', 'E', 'E', 'E','E','E','E'}, new []{'E', 'E', 'M', 'M', 'E','E','E','E'}, }; char[][] output = { new []{'B', 'B', 'B', 'B', 'B','B','1','E'}, new []{'B', '1', '1', '1', 'B','B','1','M'}, new []{'1', '2', 'M', '1', 'B','B','1','1'}, new []{'M', '2', '1', '1', 'B','B','B','B'}, new []{'1', '1', 'B', 'B', 'B','B','B','B'}, new []{'B', 'B', 'B', 'B', 'B','B','B','B'}, new []{'B', '1', '2', '2', '1','B','B','B'}, new []{'B', '1', 'M', 'M', '1','B','B','B'}, }; var mineSweeper = new MineSweeper(); var res = mineSweeper.UpdateBoard(input, new[] { 0, 0 }); for (var index = 0; index &lt; res.Length; index++) { CollectionAssert.AreEqual(output[index], res[index]); } } } public class MineSweeper { public char[][] UpdateBoard(char[][] board, int[] click) { if (board == null || board.Length == 0 || board[0].Length == 0 || click == null || click.Length == 0) { return board; } int row = click[0]; int col = click[1]; if (board[row][col] == 'M') { board[row][col] = 'X'; return board; } DFS(board, row, col); return board; } private void DFS(char[][] board, int row, int col) { if (row &lt; 0 || col &lt; 0 || row &gt;= board.Length || col &gt;= board[0].Length || board[row][col] != 'E') { return; } int numOfMines = GetNumberOfMines(board, row, col); if (numOfMines == 0) { //mark B and continue DFS to neighbors board[row][col] = 'B'; for (int rowIn = row - 1; rowIn &lt;= row + 1; rowIn++) { for (int colIn = col - 1; colIn &lt;= col + 1; colIn++) { if (rowIn == row &amp;&amp; colIn == col) { continue; } DFS(board, rowIn, colIn); } } } else { board[row][col] = numOfMines.ToString()[0]; } } private int GetNumberOfMines(char[][] board, int row, int col) { int mines = 0; for (int rowIn = row - 1; rowIn &lt;= row + 1; rowIn++) { for (int colIn = col-1; colIn &lt;= col+1; colIn++) { if (colIn &lt; 0 || rowIn &lt; 0 || rowIn &gt;= board.Length || colIn &gt;= board[0].Length || rowIn == row &amp;&amp; colIn == col) { continue; } if (board[rowIn][colIn] == 'M' || board[rowIn][colIn] == 'X') { mines++; } } } return mines; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T21:32:25.953", "Id": "471423", "Score": "1", "body": "if you downvote that is ok, just explain why..?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T09:22:36.890", "Id": "471608", "Score": "0", "body": "The downvote isn't mine, but I remember telling you a while back that people may not respond well to the frequency with which you post questions. It makes them look low-effort, and that attracts downvotes. As in, according to the hovertext of the downvote buton, that's exactly what the button is for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T10:32:53.267", "Id": "471612", "Score": "0", "body": "@Mast I totally disagree, I am solving programming challenges, I follow all the guidelines of the site. I am open to hear any feedback, I write unit tests for each one of challenges. these are not findMaxInArray() functions. this site is for improving code. the best and fastest way to be good at coding... is coding and getting reviews from peers such as you. however there is a person which started downvoting each question I post. a true case of A-hole in my opinion, when I have time practice coding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T11:17:37.650", "Id": "471613", "Score": "1", "body": "I'm just saying what it looks like, don't kill the messenger." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T21:25:37.750", "Id": "240360", "Score": "1", "Tags": [ "c#", "programming-challenge", "depth-first-search" ], "Title": "LeetCode:MineSweeper C#" }
240360
<p>My data looks like this:</p> <pre><code>const sleepStages = [ {deep: Array(40)}, {light: Array(40)}, {rem: Array(40)}, {awake: Array(40)}, ] </code></pre> <p>I'm using the key and values separately and am using TypeScript. </p> <pre><code>sleepStages.flatMap((sleepStage) =&gt; { const stageName = Object.keys(sleepStage)[0]; const stageValues = Object.values(sleepStage)[0]; console.log(stageName, stageValues); }); </code></pre> <p>Does this approach make sense? Whenever I type <code>[0]</code> it smells.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T22:58:42.917", "Id": "471430", "Score": "0", "body": "I can speculate that this is not the best way to store your data. However you haven't provided enough code for me to evolve this speculation into anything more. Right now I can think of plenty of different, potentially better or worse, solutions. As such I'm voting to close this as missing context. Whilst answerable, the answers you'll get will be sub-par." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:00:06.780", "Id": "471435", "Score": "2", "body": "This seems like such a harsh criticism and result. What if the data is from an external API? That, and the answer by @CertainPerformance is specifically helpful along with a useful criticism of the data. ‍♂️" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:04:29.983", "Id": "471436", "Score": "1", "body": "If your data is coming from an API then your question is lacking a description at best, deceptive at worst. Either way it's off-topic. Closing a question that is off-topic is not harsh." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:07:41.377", "Id": "471438", "Score": "3", "body": "Was just trying to keep things succinct. I'll do better next time. Thanks for the feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:10:46.673", "Id": "471440", "Score": "0", "body": "Ok. If you avoid being succinct then you should avoid this 'hostility' in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T14:09:28.783", "Id": "471497", "Score": "0", "body": "Unlike Stack Overflow, being overly succinct is actually a problem here. If you keep that in mind for next time, I'm sure it will all be fine. When in doubt, see our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T21:01:18.057", "Id": "471567", "Score": "0", "body": "I'm guessing you meant \"not actually a problem here\". Thanks for the feedback Mast. I'll definitely provide more context in my next question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T12:58:42.327", "Id": "471617", "Score": "1", "body": "@GollyJer No, they wrote what they meant." } ]
[ { "body": "<p>A more concise approach would be to use <code>Object.entries</code> to get the 0th key and value at once:</p>\n\n<pre><code>const [stageName, stageValues] = Object.entries(sleepStage)[0];\n</code></pre>\n\n<p>Yes, the <code>[0]</code> looks weird, but unless you know the keys and/or in advance, you <em>have</em> to use a method which iterates over them, and then you need to extract the first item. In Javascript, there's no good way of avoiding the <code>[0]</code> - there's nothing like <code>Object.prototype.getFirstEntry</code>.</p>\n\n<p>You could nest the destructuring on the left side, but that looks much less readable IMO:</p>\n\n<pre><code>const [[stageName, stageValues]] = Object.entries(sleepStage);\n</code></pre>\n\n<p>Ideally, in this sort of situation, you would fix the input data so that the keys are predictable and static:</p>\n\n<pre><code>const sleepStages = [\n { name: 'deep', values: Array(40) },\n { name: 'light', values: Array(40) },\n { name: 'rem', values: Array(40) },\n { name: 'awake', values: Array(40) },\n]\n</code></pre>\n\n<p>Then, in the loop, you could do:</p>\n\n<pre><code>const { name, values } = sleepStage;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T22:49:35.947", "Id": "471427", "Score": "0", "body": "+1 for the proposed structure improvement. Whenever there is a need to get an index like `[0]` on object keys or value, there is a better way of structuring the data, because object keys are by nature not guaranteed to be ordered. It also allows one of my favorite destructuring construct in modern javascript: `for (const { name, values } of sleepStages) {}`, where `sleepStages: { name: string, values: any[] }[]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T22:51:46.467", "Id": "471428", "Score": "1", "body": "Object property order *is* guaranteed, in all but pathological cases, [as of ES2020](https://stackoverflow.com/a/58444453), and has been effectively implemented in all implementations for years. Still, yeah, it's a code smell to rely on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T22:52:59.210", "Id": "471429", "Score": "0", "body": "wow, good to know, thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:06:12.827", "Id": "471437", "Score": "0", "body": "Thank you. This was super helpful. `.entries` wasn't on my radar until now. I'm using it for now and have asked our data team to update structure of the source data. " } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T22:39:07.220", "Id": "240365", "ParentId": "240364", "Score": "3" } } ]
{ "AcceptedAnswerId": "240365", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T22:34:43.380", "Id": "240364", "Score": "2", "Tags": [ "javascript", "typescript" ], "Title": "Extracting key and array value from javascript object?" }
240364
<p><strong>can anyone give me advice on how i can make my code more compact and efficient, and if you can, an implementation using OOP? Since, i just started learning Object Oriented Programming and it looks real hard.</strong></p> <pre class="lang-py prettyprint-override"><code>def Hangman(): # for MENU print("H A N G M A N") while True: choice = input('Type "play" to play the game, "exit" to quit: ') if choice == "play": hint("option") play_game() if choice == "exit": break def play_game(): # FOr game mechanics import random my_list = ['python', 'java', 'kotlin', 'javascript'] # WORD CHOICES global lives, chosen_word, changed_word, changed_list, hidden_word, hidden_list lives = 8 winner = False chosen_word = random.choice(my_list) changed_word = chosen_word[:] hidden_word = (len(chosen_word))*"-" hidden_list = list((len(chosen_word))*"-") changed_list = [char for char in changed_word] while lives != 0: guess = "-" print('\n', hidden_word, sep="") # gives the word every guess while True: guess = input("Input a letter: ") if len(guess) != 1: print("You should print a single letter\n") continue if guess != guess.lower() or not guess.isalpha(): print("It is not an ASCII lowercase letter\n") continue break if guess not in changed_word: if guess in chosen_word: print('You already typed this letter') continue else: print("No such letter in the word") lives -= 1 hint("check_lives") else: letter_found_count = chosen_word.count(guess) for _ in range(letter_found_count): indexfound = changed_word.find(guess) hidden_list[indexfound] = guess changed_list[indexfound] = "-" hidden_word = "".join(hidden_list) changed_word = "".join(changed_list) if hidden_word == chosen_word: print("\n%s\nYou guessed the word!\nYou survived!" % hidden_word) winner = True break if not winner: print("You are hanged!") if hint_count &gt; 1: print(f"Though you used {str(hint_count)} hints") print() def hint(setting): if setting == "game": global chosen_word, changed_word, changed_list, hidden_word, hidden_list for _ in range(len(changed_list)): guess = changed_list[_] if guess != "-": letter_found_count = chosen_word.count(guess) for _ in range(letter_found_count): indexfound = changed_word.find(guess) hidden_list[indexfound] = guess changed_list[indexfound] = "-" hidden_word = "".join(hidden_list) changed_word = "".join(changed_list) return changed_word, hidden_word, changed_list, hidden_list if setting == "option": global hint_flag, hint_count hint_count = 0 while True: choice = input("With Hints? 'Yes' or 'No': ") if choice.lower() == "yes": hint_flag = True break elif choice.lower() == "no": hint_flag = False break if setting == "check_lives": if lives != 0: if lives &lt; 5: # HINT CONDITION if hint_flag: while True: choice = input("For hint, answer: 'yes' or 'no': ") if choice.lower() == "yes": changed_word, hidden_word, changed_list, hidden_list = hint("game") hint_count += 1 break elif choice.lower() == "no": break Hangman() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T23:17:16.383", "Id": "471434", "Score": "1", "body": "Asking us to change your code to use OOP is off-topic here, as your code does not work as you intended. Getting the correct output isn't the only requirement for things to be classed as 'working as intended'. Your code doesn't expose any classes and so does not follow OOP in any way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T14:00:26.307", "Id": "471494", "Score": "0", "body": "[Related](https://codereview.stackexchange.com/q/240366/52915)" } ]
[ { "body": "<p>I can make some general suggestions. Having code completely rewritten is offtopic here though.</p>\n\n<hr>\n\n<p>In <code>play_game</code>, you import <code>random</code> from within the function. <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">PEP8 notes though that</a>:</p>\n\n<blockquote>\n <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p>\n</blockquote>\n\n<p>It's conceivable that you may want to have an import conditionally happen inside of a function if the import is expensive, and would only rarely be used. That certainly isn't the case here though.</p>\n\n<hr>\n\n<pre><code>changed_list = [char for char in changed_word]\n</code></pre>\n\n<p>This just creates a copy of <code>changed_word</code> in a verbose way. You would be better off doing what you did before:</p>\n\n<pre><code>changed_list = changed_word[:]\n</code></pre>\n\n<hr>\n\n<p>You use far too many global variables. For clarity, those variables making up the state of the game should be explicitly passed to each function that needs them. You could use a <code>dataclass</code> to hold the data, and then pass the state object around.</p>\n\n<p>Having everything as global with complicate testing, and makes your program harder to understand.</p>\n\n<hr>\n\n<p>You have a loop that's written in a confusing way:</p>\n\n<pre><code>while True:\n guess = input(\"Input a letter: \")\n if len(guess) != 1:\n print(\"You should print a single letter\\n\")\n continue\n if guess != guess.lower() or not guess.isalpha():\n print(\"It is not an ASCII lowercase letter\\n\")\n continue\n break\n</code></pre>\n\n<p>You <code>continue</code> in two branches, then <code>break</code> at the bottom. You might as well just use an <code>elif</code> and <code>else</code> to set it up so you only break if both checks were false:</p>\n\n<pre><code>while True:\n guess = input(\"Input a letter: \")\n if len(guess) != 1:\n print(\"You should print a single letter\\n\")\n elif guess != guess.lower() or not guess.isalpha():\n print(\"It is not an ASCII lowercase letter\\n\")\n else:\n break\n</code></pre>\n\n<hr>\n\n<pre><code>\"\\n%s\\nYou guessed the word!\\nYou survived!\" % hidden_word\n</code></pre>\n\n<p>In more modern Python, this can be written more cleanly using f-strings like you use later:</p>\n\n<pre><code>f\"\\n{hidden_word}\\nYou guessed the word!\\nYou survived!\"\n</code></pre>\n\n<hr>\n\n<pre><code>if setting == \"check_lives\":\n if lives != 0:\n if lives &lt; 5: # HINT CONDITION\n if hint_flag:\n</code></pre>\n\n<p>You don't have an <code>else</code> case for any of those checks, so you might as well just <code>and</code> them:</p>\n\n<pre><code>if setting == \"check_lives\" and 0 &lt; lives &lt; 5 and hint_flag:\n</code></pre>\n\n<p>That will cut down on a lot of nesting.</p>\n\n<hr>\n\n<pre><code>list((len(chosen_word))*\"-\")\n</code></pre>\n\n<p>Would make a lot more sense as just:</p>\n\n<pre><code>len(\"chosen_word\") * [\"-\"]\n</code></pre>\n\n<hr>\n\n<pre><code>for _ in range(len(changed_list)):\n guess = changed_list[_]\n</code></pre>\n\n<p>Don't call something <code>_</code> unless you don't use it. If you use it, give it a good, descriptive name. Here though, you should just iterate the word directly:</p>\n\n<pre><code>for letter in changed_list:\n guess = letter # Which mostly gets rid of the need for guess\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-17T20:19:30.640", "Id": "489169", "Score": "0", "body": "[Please refrain from answering questions that are likely to get closed.](https://codereview.meta.stackexchange.com/a/6389/35991)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T23:37:10.403", "Id": "240371", "ParentId": "240369", "Score": "4" } } ]
{ "AcceptedAnswerId": "240371", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T22:52:29.340", "Id": "240369", "Score": "0", "Tags": [ "python", "python-3.x", "object-oriented", "programming-challenge" ], "Title": "A python Hang Man Game" }
240369
<p>Any feedback on this code would be greatly appreciated! I am just trying to improve so I can move on to bigger projects. Thank you so much!</p> <pre><code> import java.util.*; import java.util.Random; public class RockPaperScissors { public static void main(String [] args) { Random rd = new Random(); Scanner kb = new Scanner(System.in); System.out.println("Welcome to Rock Paper Scisscors!"); while(true) { int rock = 1; int paper = 2; int scissors = 3; int conditions [] = {rock, paper, scissors}; int random = (conditions[new Random().nextInt(conditions.length)]); System.out.print("Please Enter: \n1 for Rock, \n2 for Paper, \n3 for Scissors: "); int player1 = kb.nextInt(); if(player1 == rock &amp;&amp; random == rock) { System.out.print("You have tied, computer rock, please try again\n"); } else if(player1 == paper &amp;&amp; random == paper) { System.out.print("You have tied, computer chose paper, please try again"); } else if(player1 == scissors &amp;&amp; random == scissors) { System.out.print("You have tied, computer chose scissors, please try again"); } if(player1 == rock &amp;&amp; random == paper) { System.out.print("Computer chose paper, computer has won"); break; } else if(player1 == paper &amp;&amp; random == rock) { System.out.print("You win!, computer chose rock"); break; } else if(player1 == paper &amp;&amp; random == scissors) { System.out.print("Computer chose scissors, computer has won"); break; } else if(player1 == scissors &amp;&amp; random == paper) { System.out.print("You win, computer chose paper"); break; } else if(player1 == rock &amp;&amp; random == scissors) { System.out.print("You win!, computer chose scissors"); break; } else if(player1 == scissors &amp;&amp; random == rock) { System.out.print("Computer chose rock, computer has won"); break; } if(player1 != rock &amp;&amp; player1 != paper &amp;&amp; player1 != scissors ) { System.out.print("Invalid response"); break; } } } } </code></pre>
[]
[ { "body": "<p>I have some suggestions for you.</p>\n\n<p>Next time, before submitting code, try to format it :)</p>\n\n<h1>Suggestions</h1>\n\n<h2>Unused variable</h2>\n\n<p>The variable <code>rd</code> is not used, you can remove it.</p>\n\n<h2>Put variables that don’t change out of the loop</h2>\n\n<p>In the <code>while</code> loop, the <code>rock</code>, <code>paper</code> and <code>scissors</code> get their value reassigned with the same value each time the loop restart, move them outside of the loop.</p>\n\n<p>I suggest that you put those as class constants, so you will be able to reuse the in other methods.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class RockPaperScissors {\n public static final int ROCK = 1;\n public static final int PAPER = 2;\n public static final int SCISSORS = 3;\n}\n</code></pre>\n\n<h2>Validate the invalid choice first</h2>\n\n<p>In your code, you check if the chosen option is valid at the end of the loop; it will be more efficient if you check the invalid options first. This will prevent to check every other conditions and quit the loop faster.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>System.out.print(\"Please Enter: \\n1 for Rock, \\n2 for Paper, \\n3 for Scissors: \");\nint player1 = kb.nextInt();\n\nif (player1 != rock &amp;&amp; player1 != paper &amp;&amp; player1 != scissors) {\n System.out.print(\"Invalid response\");\n break;\n}\n</code></pre>\n\n<h2>Extract some of the logic into methods</h2>\n\n<p>In your code, you can move some of the logic into method to allow the code to be shorter and easier to read.</p>\n\n<ol>\n<li>I suggest make methods to check if the answer is a rock, paper or scissors; this will allow the conditions to be shorter.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n while (true) {\n //[...]\n if (isRock(player1) &amp;&amp; isRock(random)) {\n //[...]\n }\n //[...]\n }\n}\n\nprivate static boolean isRock(int answer) {\n return answer == ROCK;\n}\n\nprivate static boolean isPaper(int answer) {\n return answer == PAPER;\n}\n\nprivate static boolean isScissor(int answer) {\n return answer == SCISSORS;\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>I suggest that you extract the logic that read the value in a method. </li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n while (true) {\n //[...]\n int player1 = getPlayer1Answer(kb);\n }\n}\n\nprivate static int getPlayer1Answer(Scanner kb) {\n System.out.print(\"Please Enter: \\n1 for Rock, \\n2 for Paper, \\n3 for Scissors: \");\n return kb.nextInt();\n}\n</code></pre>\n\n<p><strong>Bonus</strong></p>\n\n<p>While you are in the method, I suggest to make another loop to verify the validity of the answer; this will make sure the provided choice is valid and ask again if not.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static int getPlayer1Answer(Scanner scanner) {\n int value;\n\n while (true) {\n System.out.print(\"Please Enter: \\n1 for Rock, \\n2 for Paper, \\n3 for Scissors: \");\n value = scanner.nextInt();\n\n if (isRock(value) || isPaper(value) || isScissor(value)) {\n break;\n } else {\n System.out.println(\"Invalid response\");\n }\n }\n\n return value;\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>I suggest that you extract the logic that generates the computer answer in a method. </li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code> private static int getComputerAnswer() {\n int[] conditions = {ROCK, PAPER, SCISSORS};\n return conditions[new Random().nextInt(conditions.length)];\n }\n</code></pre>\n\n<h1>Refactored code</h1>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class RockPaperScissors {\n public static final int ROCK = 1;\n public static final int PAPER = 2;\n public static final int SCISSORS = 3;\n\n public static void main(String[] args) {\n Scanner kb = new Scanner(System.in);\n System.out.println(\"Welcome to Rock Paper Scissors!\");\n\n while (true) {\n int random = getComputerAnswer();\n int player1 = getPlayer1Answer(kb);\n\n if (isRock(player1) &amp;&amp; isRock(random)) {\n System.out.print(\"You have tied, computer rock, please try again\\n\");\n } else if (isPaper(player1) &amp;&amp; isPaper(random)) {\n System.out.print(\"You have tied, computer chose paper, please try again\");\n } else if (isScissor(player1) &amp;&amp; isScissor(random)) {\n System.out.print(\"You have tied, computer chose scissors, please try again\");\n }\n\n if (isRock(player1) &amp;&amp; isPaper(random)) {\n System.out.print(\"Computer chose paper, computer has won\");\n break;\n } else if (isPaper(player1) &amp;&amp; isRock(random)) {\n System.out.print(\"You win!, computer chose rock\");\n break;\n } else if (isPaper(player1) &amp;&amp; isScissor(random)) {\n System.out.print(\"Computer chose scissors, computer has won\");\n break;\n } else if (isScissor(player1) &amp;&amp; isPaper(random)) {\n System.out.print(\"You win, computer chose paper\");\n break;\n } else if (isRock(player1) &amp;&amp; isScissor(random)) {\n System.out.print(\"You win!, computer chose scissors\");\n break;\n } else if (isScissor(player1) &amp;&amp; isRock(random)) {\n System.out.print(\"Computer chose rock, computer has won\");\n break;\n }\n }\n }\n\n private static boolean isRock(int answer) {\n return answer == ROCK;\n }\n\n private static boolean isPaper(int answer) {\n return answer == PAPER;\n }\n\n private static boolean isScissor(int answer) {\n return answer == SCISSORS;\n }\n\n private static int getComputerAnswer() {\n int[] conditions = {ROCK, PAPER, SCISSORS};\n return conditions[new Random().nextInt(conditions.length)];\n }\n\n private static int getPlayer1Answer(Scanner scanner) {\n int value;\n\n while(true) {\n System.out.print(\"Please Enter: \\n1 for Rock, \\n2 for Paper, \\n3 for Scissors: \");\n value = scanner.nextInt();\n\n if(isRock(value) || isPaper(value) || isScissor(value)) {\n break;\n } else {\n System.out.println(\"Invalid response\");\n }\n }\n\n return value;\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:31:06.170", "Id": "240373", "ParentId": "240370", "Score": "1" } }, { "body": "<p>Welcome to Code Review, I have some suggestions for you:</p>\n\n<h2>Logic of the game and a possible implementation</h2>\n\n<p>Starting from your code:</p>\n\n<blockquote>\n<pre><code>int rock = 1;\nint paper = 2;\nint scissors = 3;\n</code></pre>\n</blockquote>\n\n<p>You already identified that rock, paper, and scissors can be represented as three consecutive numbers, a better choice of these three numbers is rock = 0, paper = 1 and scissors = 2. Why ? Because if <code>player1</code> and <code>random</code> are the choices for the player and computer in the range of integers 0, 1, 2 you can determine who is the winner checking the conditions <code>player1 == ((random + 1) % 3)</code> and <code>random == ((player1 + 1) % 3)</code> . If the first one is true player wins, if the second one is true computer wins, if both are false there is a draw.</p>\n\n<p>A possibility to reduce your code is given by creating an <code>Enum</code> Hand:</p>\n\n<pre><code>private enum Hand {ROCK, PAPER, SCISSORS};\n//the method below will print for 0, 1, 2 values for random the Strings ROCK, PAPER, SCISSORS\nString hand = Hand.values()[random].name();\n//with lowercase ROCK, PAPER, SCISSORS strings will become rock, paper, scissors\nString lower = hand.toLowerCase();\n</code></pre>\n\n<p>The good thing about <code>Enum</code> is that <code>ROCK, PAPER, SCISSORS</code> have the default values of 0, 1, 2 so you don't need to define them, so you can define a prototype for your class like this:</p>\n\n<pre><code>public class RockPaperScissors {\n\n private enum Hand {ROCK, PAPER, SCISSORS};\n\n public static void main(String[] args) { /*here your logic*/ }\n}\n</code></pre>\n\n<p>Because you have a lot of repetitive messages about the game differing just for one word you can define String templates like these:</p>\n\n<pre><code>String messageTie = \"You have tied, computer %s, please try again\\n\";\nString messageWin = \"You win, computer chose %s\\n\";\nString messageLost = \"Computer chose %s, computer has won\\n\";\n</code></pre>\n\n<p>Notice that %s can be substituted by the words rock, paper, scissors so the number of messages decreases to three.</p>\n\n<p>You can write your class like this:</p>\n\n<pre><code>public class RockPaperScissors {\n\n private enum Hand {ROCK, PAPER, SCISSORS};\n\n public static void main(String[] args) {\n\n Random rd = new Random();\n String messageTie = \"You have tied, computer %s, please try again\\n\";\n String messageWin = \"You win, computer chose %s\\n\";\n String messageLost = \"Computer chose %s, computer has won\\n\";\n\n try (Scanner kb = new Scanner(System.in)) {\n while (true) {\n System.out.print(\"Please Enter: \\n0 for Rock, \\n1 for Paper, \\n2 for Scissors: \");\n int player1 = kb.nextInt();\n if(player1 &lt; 0 || player1 &gt; 2) {\n System.out.print(\"Invalid response\");\n break;\n }\n //here the logic to determine the winner\n }\n }\n\n}\n</code></pre>\n\n<p>My implementation differs from your's because I'm using the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try with resources statement</a> and legitimate choices for players are numbers 0, 1, 2, different number of another type of input will bring to the termination of the program.</p>\n\n<p>The logic to determine the winner and print the appropriate the right message is the following:</p>\n\n<pre><code>int random = (rd.nextInt(3));\nString messageGame = messageTie;\nif (player1 == ((random + 1) % 3)) {\n messageGame = messageWin;\n} \nif (random == ((player1 + 1) % 3)) {\n messageGame = messageLost;\n}\nString hand = Hand.values()[random].name();\nSystem.out.printf(messageGame, hand.toLowerCase());\n</code></pre>\n\n<p>Initially I'm supposing the game will end with a draw result and it will be printed the draw message, if one of the condition is true the message will change. The method <code>System.out.printf</code> will take the computer <code>hand</code> result as a parameter.</p>\n\n<p>Here the code complete of my version of the class <code>RockPaperScissors</code>:</p>\n\n<h2>RockPaperScissors.java</h2>\n\n<pre><code>public class RockPaperScissors {\n\n private enum Hand {ROCK, PAPER, SCISSORS};\n\n public static void main(String[] args) {\n\n Random rd = new Random();\n String messageTie = \"You have tied, computer %s, please try again\\n\";\n String messageWin = \"You win, computer chose %s\\n\";\n String messageLost = \"Computer chose %s, computer has won\\n\";\n\n try (Scanner kb = new Scanner(System.in)) {\n while (true) {\n System.out.print(\"Please Enter: \\n0 for Rock, \\n1 for Paper, \\n2 for Scissors: \");\n int player1 = kb.nextInt();\n if(player1 &lt; 0 || player1 &gt; 2) {\n System.out.print(\"Invalid response\");\n break;\n }\n int random = (rd.nextInt(3));\n String messageGame = messageTie;\n if (player1 == ((random + 1) % 3)) {\n messageGame = messageWin;\n } \n if (random == ((player1 + 1) % 3)) {\n messageGame = messageLost;\n }\n String hand = Hand.values()[random].name();\n System.out.printf(messageGame, hand.toLowerCase());\n }\n }\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:04:41.623", "Id": "240411", "ParentId": "240370", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T23:10:42.490", "Id": "240370", "Score": "2", "Tags": [ "java", "beginner", "rock-paper-scissors", "eclipse" ], "Title": "Rock Paper Scissors in Java (I just want to know whatever feedback you have :) Thank you!)" }
240370
<p>I have the following Connect 4 implementation. Is there a way to refactor it and maybe make it better. It's a fully working solution. However, I see that the correct result is not returned in certain cases like the following. In this case 1 should have won since there are <code>four_in_a_row</code> from the right hand side: </p> <pre><code>Team 0: Your turn, please choose column: 2 [' ', ' ', ' ', ' ', ' ', ' ', ' '] [' ', ' ', ' ', ' ', ' ', ' ', '0'] [' ', ' ', ' ', ' ', ' ', '0', '1'] [' ', ' ', ' ', ' ', ' ', '1', '0'] ['0', ' ', ' ', ' ', '1', '0', '1'] ['0', '0', ' ', '1', '1', '1', '0'] </code></pre> <p>I might be missing some edge cases and would be great if I could get this code reviewed and some sample code of how to refactor the same. My <code>get_diagonals</code> function might be the one causing the issue. The following is the code: </p> <pre><code>""" Module Docstring This is an implementation of the Connect 4 game, where each user Can enter 0 and 1. A user wins if There is 4 in a row match either Horizontally, vertically or diagonally. """ class ConnectFour(): def __init__(self, height, width): self.height = height self.width = width self.board = [[' ' for x in range(width)] for y in range(height)] def get_column(self, index): """ Returns a column at the specified index :param index: int Index at which column will be returned :return: List[String] """ return [i[index] for i in self.board] def get_row(self, index): """ Returns a row at the specified index :param index: Index at which row will be returned :return: """ return self.board[index] def get_diagonals(self): """ :return: List of all digonal positions from top right to bottom left and from top left to bottom right """ diagonals = [] # For all diagonals from (3,0) top right to (0,3) bottom left for i in range(self.height + self.width - 1): diagonals.append([]) for j in range(max(i - self.height + 1, 0), min(i + 1, self.height)): diagonals[i].append(self.board[self.height - (i - j + 1)][j]) # For all diagonals from (0,0) top left to (3,3) bottom right for i in range(self.height + self.width - 1): diagonals.append([]) for j in range(max(i - self.height + 1, 0), min(i + 1, self.height)): diagonals[i].append(self.board[i - j][j]) return diagonals def make_move(self, team, col): """ Simply a move and places 1/0 is the specified postion for the team in turn :param team: String The team currently playing either '0' or '1' :param col: String The col selected by the team :return: board: List[List[Str]] """ if ' ' not in self.get_column(col): return self.board i = self.height - 1 # check if current index is empty while self.board[i][col] != ' ': i -= 1 self.board[i][col] = team return self.board def check_win(self): """ :return: String the board and returns winning team that contain matched 4 in a row determining the team that won """ four_in_a_row = [['0','0','0','0'],['1','1','1','1']] # Check for 4 in a row in rows for i in range(self.height): for j in range(self.width -3): if self.get_row(i)[j:j+4] in four_in_a_row: return self.board[i][j] # Check for 4 in a row in cols for i in range(self.width): for j in range(self.height - 3): if self.get_column(i)[j:j+4] in four_in_a_row: return self.board[j][i] # Check for 4 in a row in diagonals for i in self.get_diagonals(): for j, _ in enumerate(i): if i[j:j + 4] in four_in_a_row: return i[j] #Otherwise if no case wins return None def start_game(self, game): """ The method that simulates the gameplay and returns which team won :param board: The board in which the game is currently being played :return: String The team that won """ while True: for i in game.board: print(i) if game.check_win() is not None: break col = int(input("Team 0: Your turn, please choose column: ")) - 1 game.make_move('0',col) for i in game.board: print(i) if game.check_win() is not None: break col = int(input("Team 1: Your turn please choose column: ")) - 1 game.make_move('1',col) if game.check_win(): print(f'Congrats team {game.check_win()} !') return f'Team {game.check_win()} has won. Thank you for playing!!!' else: return None if __name__ == '__main__': height = 6 width = 7 game = ConnectFour(height, width) game.start_game(game) </code></pre> <p>Thanks a lot in advance for all the advice! </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T01:54:21.393", "Id": "471588", "Score": "2", "body": "If your code isn't working as intended, this is probably better off at Stack Overflow. See [on topic for CR](https://codereview.stackexchange.com/help/on-topic). I'm having trouble reconciling \"It's a fully working solution. However, I see that the correct result is not returned in certain cases\"." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-11T23:56:32.573", "Id": "240372", "Score": "3", "Tags": [ "python", "python-3.x", "connect-four" ], "Title": "A game implementation in Python" }
240372
<p>This class is for calculating the shortest path in a 2D World (without minding obstacles).</p> <p>I'm using the A* algorithm and 2D Vectors (from the SFML Framework). It is working but takes (a lot of) time for higher amount of coordinates.</p> <p>It takes 4 seconds to calculate the path from one edge of the map to the other.</p> <p>Example from my Logs: (so you can see the coordinate range i meant)</p> <blockquote> <p>Searching from : [Vector2i] X(100) Y(100) to: [Vector2i] X(3945) Y(4046)</p> <p>Time needed: 4003ms</p> </blockquote> <p>This is a lot for real time interaction and it's not even checking for obstacles.</p> <p>I'm probably doing it not very efficient, so i hope you have some advice for me.</p> <p>EDIT: Changed code to use Sets instead of Lists</p> <pre><code> public static class AStar { protected class Location: IComparable&lt;Location&gt; { public Vector2i pos; public int f; public int g; public int h; public int weight; public Location parent; public Location(Vector2i pos) { this.pos = pos; f = 0; g = 0; h = 0; weight = 1; parent = null; } public override bool Equals(object obj) { Location other = obj as Location; return this.pos.X == other.pos.X &amp;&amp; this.pos.Y == other.pos.Y; } public int CompareTo([AllowNull] Location other) { if (this.Equals(other)) { return 0; } else if (other.f &lt; this.f) { return 1; } else { return -1; } } } public static Path Search(Vector2i start, Vector2i target) { Location current = null; SortedSet&lt;Location&gt; openList = new SortedSet&lt;Location&gt;(); HashSet&lt;Location&gt; closedList = new HashSet&lt;Location&gt;(); Location targetLocation = new Location(target); openList.Add(new Location(start)); while (openList.Any()) { current = openList.First(); closedList.Add(current); openList.Remove(current); if (current.Equals(targetLocation)) { return CreateResultPath(current); } List&lt;Location&gt; possibleNeighbors = GetPossibleNeighbors(current); foreach (Location neighbor in possibleNeighbors) { // neighbor must not be in closedSet if (closedList.FirstOrDefault(location =&gt; location.Equals(neighbor)) == null) { // calculating neighbor neighbor.g = current.g + neighbor.weight; neighbor.h = CalcDistance(neighbor.pos, target); neighbor.f = neighbor.g + neighbor.h; neighbor.parent = current; Location oldNeighbor = openList.FirstOrDefault(location =&gt; location.Equals(neighbor)); if (oldNeighbor == null) { openList.Add(neighbor); } // neighbor is already in openList, checking if this path is better else { if (neighbor.g &lt; oldNeighbor.g) { openList.Remove(oldNeighbor); openList.Add(neighbor); } } } } } return null; } private static Path CreateResultPath(Location result) { List&lt;Vector2i&gt; resultPath = new List&lt;Vector2i&gt;(); while (result != null) { resultPath.Add(result.pos); result = result.parent; } resultPath.Reverse(); return new Path(resultPath.ToArray()); } private static List&lt;Location&gt; GetPossibleNeighbors(Location current) { Vector2i currentPos = current.pos; List&lt;Location&gt; possibleNeighbors = new List&lt;Location&gt;(); possibleNeighbors.Add(new Location(new Vector2i(currentPos.X - 1, currentPos.Y + 1))); possibleNeighbors.Add(new Location(new Vector2i(currentPos.X - 1, currentPos.Y - 1))); possibleNeighbors.Add(new Location(new Vector2i(currentPos.X - 1, currentPos.Y))); possibleNeighbors.Add(new Location(new Vector2i(currentPos.X, currentPos.Y + 1))); possibleNeighbors.Add(new Location(new Vector2i(currentPos.X, currentPos.Y - 1))); possibleNeighbors.Add(new Location(new Vector2i(currentPos.X + 1, currentPos.Y + 1))); possibleNeighbors.Add(new Location(new Vector2i(currentPos.X + 1, currentPos.Y - 1))); possibleNeighbors.Add(new Location(new Vector2i(currentPos.X + 1, currentPos.Y))); return possibleNeighbors; } private static int CalcDistance(Vector2i current, Vector2i target) { return Math.Abs(target.X - current.X) + Math.Abs(target.Y - current.Y); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T03:56:39.293", "Id": "471454", "Score": "2", "body": "You should not use `List` for `openList` and `closedList`: for each processed vertex, you iterate over the entire `openList` (twice!) to find the minimum element in linear time, and for each neighbour, you iterate over the entire `closedList`... They should probably be `SortedSet`s instead (`HashSet` might do for `closedList`). The line `neighbor.f = neighbor.g = neighbor.h` seems to have a bug (should use a `+`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T08:42:58.030", "Id": "471465", "Score": "0", "body": "@mypronounismonicareinstate With Sorted Set it actually takes more time than before even though i can now just say openSet.First() instead of min and then First(minObject).\nI think adding an element to the SortedList takes more time than it saves." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T09:27:59.943", "Id": "471468", "Score": "1", "body": "It should be logarithmic (constant-ish for `HashSet`) in time complexity if used correctly though. Could you show your code with `SortedSet`s instead of `List`s? (and have you fixed the `neighbor.f = neighbor.g = neighbor.h` line?) Priority queues can also be used for the same time complexity with `SortedSet`s, but a noticeably lower constant factor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T09:52:04.957", "Id": "471472", "Score": "0", "body": "@mypronounismonicareinstate i've edited the code in the original post. And yes i did fix the neighbor.f line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T09:54:21.987", "Id": "471473", "Score": "1", "body": "I think the guess I had was correct: `FirstOrDefault` on sets still iterates over the set in linear time, with a higher constant factor than regular `List`s. I can't recall what methods are used for searching in sets in C#, but that should be easy to find." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T11:20:53.257", "Id": "471477", "Score": "0", "body": "@mypronounismonicareinstate You were right. FirstOrDefault() from System.Linq doesnt perform well on Sets.\nInstead i used only methods given by the set itself instead of those extension methods.\nThe given example which took 6 seconds now only takes 50ms. It saves time over an factor of 100." } ]
[ { "body": "<p>Solution suggested by @mypronounismonicareinstate.</p>\n\n<p>The time save is a bit more than factor 100. The average calculation time was ~6s now it's ~50-60ms.</p>\n\n<p>First of all using Sets instead of Lists. In terms of iterating and removing items, Sets are way more faster.</p>\n\n<p>Second: Using SortedSet to save the check for the minimum f in OpenList. And use HashSet for closedList.</p>\n\n<p>Im my original solution this took 2 times iterating the whole list.</p>\n\n<p>Third: Not using System.Linq in Combination with Sets if you want to iterate.\nSystem.Linq will always iterate through the whole set.</p>\n\n<p>The final code:</p>\n\n<pre><code>public static class AStar\n {\n protected class Location: IComparable&lt;Location&gt;\n {\n public Vector2i pos;\n public int f;\n public int g;\n public int h;\n public int weight;\n public Location parent;\n\n public Location(Vector2i pos)\n {\n this.pos = pos;\n f = 0;\n g = 0;\n h = 0;\n weight = 1;\n parent = null;\n }\n\n public override bool Equals(object obj)\n {\n Location other = obj as Location;\n return this.pos.X == other.pos.X &amp;&amp; this.pos.Y == other.pos.Y;\n }\n\n public int CompareTo([AllowNull] Location other)\n {\n if (this.Equals(other))\n {\n return 0;\n }\n else if (other.f &lt; this.f)\n {\n return 1;\n }\n else\n {\n return -1;\n }\n }\n }\n\n public static Path Search(Vector2i start, Vector2i target)\n {\n Location current = null;\n SortedSet&lt;Location&gt; openList = new SortedSet&lt;Location&gt;();\n HashSet&lt;Location&gt; closedList = new HashSet&lt;Location&gt;();\n Location targetLocation = new Location(target);\n openList.Add(new Location(start));\n while (openList.Any())\n {\n current = openList.First();\n closedList.Add(current);\n openList.Remove(current);\n if (current.Equals(targetLocation))\n {\n return CreateResultPath(current);\n }\n List&lt;Location&gt; possibleNeighbors = GetPossibleNeighbors(current);\n foreach (Location neighbor in possibleNeighbors)\n {\n // neighbor must not be in closedSet\n if (!closedList.Contains(neighbor)) \n {\n // calculating neighbor\n neighbor.g = current.g + neighbor.weight;\n neighbor.h = CalcDistance(neighbor.pos, target);\n neighbor.f = neighbor.g + neighbor.h;\n neighbor.parent = current;\n\n openList.TryGetValue(neighbor, out Location oldNeighbor);\n if (oldNeighbor == null)\n {\n openList.Add(neighbor);\n }\n // neighbor is already in openList, checking if this path is better\n else\n {\n if (neighbor.g &lt; oldNeighbor.g)\n {\n openList.Remove(oldNeighbor);\n openList.Add(neighbor);\n }\n }\n }\n }\n }\n return null;\n }\n\n private static Path CreateResultPath(Location result)\n {\n List&lt;Vector2i&gt; resultPath = new List&lt;Vector2i&gt;();\n while (result != null)\n {\n resultPath.Add(result.pos);\n result = result.parent;\n }\n resultPath.Reverse();\n return new Path(resultPath.ToArray());\n }\n\n private static List&lt;Location&gt; GetPossibleNeighbors(Location current)\n {\n Vector2i currentPos = current.pos;\n List&lt;Location&gt; possibleNeighbors = new List&lt;Location&gt;();\n possibleNeighbors.Add(new Location(new Vector2i(currentPos.X - 1, currentPos.Y + 1)));\n possibleNeighbors.Add(new Location(new Vector2i(currentPos.X - 1, currentPos.Y - 1)));\n possibleNeighbors.Add(new Location(new Vector2i(currentPos.X - 1, currentPos.Y)));\n possibleNeighbors.Add(new Location(new Vector2i(currentPos.X, currentPos.Y + 1)));\n possibleNeighbors.Add(new Location(new Vector2i(currentPos.X, currentPos.Y - 1)));\n possibleNeighbors.Add(new Location(new Vector2i(currentPos.X + 1, currentPos.Y + 1)));\n possibleNeighbors.Add(new Location(new Vector2i(currentPos.X + 1, currentPos.Y - 1)));\n possibleNeighbors.Add(new Location(new Vector2i(currentPos.X + 1, currentPos.Y)));\n return possibleNeighbors;\n }\n\n // Chebyshev Distance\n private static int CalcDistance(Vector2i current, Vector2i target)\n {\n return Math.Max(Math.Abs(target.X - current.X), Math.Abs(target.Y - current.Y));\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:10:16.747", "Id": "471525", "Score": "0", "body": "I have noticed what seems to be another bug: your GetPossibleNeighbors function seems to generate neighbours on a grid with Chebyshev distance (as in, moving like a chess king; \\$\\max(\\Delta x, \\Delta y)\\$), but the heuristic uses the rectilinear/taxicab/Manhattan distance (as in, moving to any of the 4 neighbours with a common side; \\$\\Delta x + \\Delta y\\$). This makes the heuristic non-admissible (it overestimates diagonal paths) and voids your warranty and you don't necessarily get shortest paths." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:02:35.253", "Id": "471528", "Score": "0", "body": "@mypronounismonicareinstate yes you are right. I'm going to adjust the CalcDistance Function then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:10:47.413", "Id": "471534", "Score": "0", "body": "@mypronounismonicareinstate the CalcDistance Function should be correct now." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T12:13:06.280", "Id": "240388", "ParentId": "240374", "Score": "2" } } ]
{ "AcceptedAnswerId": "240388", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:42:15.283", "Id": "240374", "Score": "4", "Tags": [ "c#", "algorithm", ".net", "pathfinding", "a-star" ], "Title": "A* pathfinding for integer Vectors" }
240374
<p>This code will read in double values from a file and store them in a 2-D array. I'm practicing using only arrays (not ArrayLists). The maximum number of lines that will be stored is 10, 10 values max per line. Values in the file are separated by a single white space character. Any feedback would be appreciated as well as any suggestions to make this more efficient.</p> <pre><code>import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class twoDArrayPractice { public static void main(String[] args) { try { File file = new File("test.txt"); Scanner inputFile; inputFile = new Scanner(file); final int ROWS = 10; final int COLS = 10; String[][] numString = new String[ROWS][COLS]; // 2-d array of strings StringBuilder tempString = new StringBuilder(); int i = 0, j = 0; // stores contents from file into numString while (inputFile.hasNextLine() &amp;&amp; i &lt; 10) { tempString.append(inputFile.nextLine()); if (!(tempString.toString().trim().isEmpty())) { numString[i] = removeSpaces(tempString.toString().split(" ")); i++; } tempString.setLength(0); } inputFile.close(); i = 0; // counts and stores number of non-null rows from numString //in i variable while (i != 10 &amp;&amp; numString[i][0] != null) { i++; } Double[][] doubleMatrix = new Double[i][]; int doubleMatrixLength = doubleMatrix.length, numStringLength = 0; //takes elements in numString, parses them to //double and stores them in doubleMatrix for (i = 0; i &lt; doubleMatrixLength; i++) { numStringLength = numString[i].length; for (j = 0; j &lt; numStringLength; j++) { if (j == 0) { doubleMatrix[i] = new Double[numString[i].length]; } try { doubleMatrix[i][j] = Double.parseDouble(numString[i][j]); } catch (NumberFormatException e) { System.out.println("Couldn't convert to double"); } catch (NullPointerException e) { System.out.println("Can't convert Null value"); } } } //print contents of doubleMatrix for (i = 0; i &lt; doubleMatrix.length; i++) { for (j = 0; j &lt; doubleMatrix[i].length; j++) { System.out.print(doubleMatrix[i][j] + " "); } System.out.println(); } } catch (FileNotFoundException e) { System.out.println("File not found"); } } //returns new array with spaces removed from stringArray public static String[] removeSpaces(String[] stringArray) { String[] newArray; int newLength = 0, oldLength = stringArray.length; //counts number of non-empty elements in string array for (int i = 0; i &lt; oldLength; i++) { if (!(isBlankString(stringArray[i]))) { newLength++; } } newArray = new String[newLength]; int j = 0; //copies over elements from stringArray to newArray for (int i = 0; i &lt; oldLength; i++) { if (!(isBlankString(stringArray[i]))) { newArray[j] = stringArray[i]; j++; } } return newArray; } //checks if str is blank as well as if its a double public static boolean isBlankString(String str) { return str == null || str.isEmpty() || !isDouble(str); } public static boolean isDouble(String str) { try { double d = Double.parseDouble(str); } catch (NumberFormatException e) { return false; } return true; } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Welcome to Code Review. I have some suggestions for you and I modified part of your code in your <code>main</code> , using just only arrays as you said:</p>\n\n<p>Starting from your class declaration:</p>\n\n<blockquote>\n<pre><code>public class twoDArrayPractice { ... }\n</code></pre>\n</blockquote>\n\n<p>Java classes always start with an uppercase letter, you can rename it:</p>\n\n<pre><code>public class TwoDArrayPractice { ... }\n</code></pre>\n\n<p>Use of <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try with resources</a> statement, why worry about closing of one file if there is a construct automatically doing it for you ? So instead of :</p>\n\n<blockquote>\n<pre><code>try {\n File file = new File(\"test.txt\");\n Scanner inputFile;\n inputFile = new Scanner(file);\n inputFile.close();\n} catch (FileNotFoundException e) {\n System.out.println(\"File not found\");\n}\n</code></pre>\n</blockquote>\n\n<p>You can rewrite it like this:</p>\n\n<pre><code>try (Scanner inputFile = new Scanner(new File(\"test.txt\"))) { /* here your code */ }\n</code></pre>\n\n<p>Some minor changes to your <code>main</code> method to improve readibility:</p>\n\n<pre><code>public static void main(String[] args) throws FileNotFoundException {\n\n final int ROWS = 10;\n final int COLS = 10;\n String[][] numString = new String[ROWS][COLS]; // 2-d array of strings\n\n try (Scanner inputFile = new Scanner(new File(\"test.txt\"))) { /* here your code */ }\n}\n</code></pre>\n\n<p>You have the following code:</p>\n\n<blockquote>\n<pre><code>while (inputFile.hasNextLine() &amp;&amp; i &lt; 10) {\n tempString.append(inputFile.nextLine());\n if (!(tempString.toString().trim().isEmpty())) {\n numString[i] = removeSpaces(tempString.toString().split(\" \"));\n i++;\n }\n tempString.setLength(0);\n}\n</code></pre>\n</blockquote>\n\n<p>Rewrite it in a more readable way:</p>\n\n<pre><code>for (int i = 0; inputFile.hasNextLine() &amp;&amp; i &lt; 10; ++i) {\n String line = inputFile.nextLine();\n if (!line.trim().isEmpty()) {\n numString[i] = removeSpaces(line.split(\" \"));\n }\n}\n</code></pre>\n\n<p>Same approach for this code:</p>\n\n<pre><code>for (i = 0; i &lt; doubleMatrixLength; i++) {\n numStringLength = numString[i].length;\n for (j = 0; j &lt; numStringLength; j++) {\n if (j == 0) {\n doubleMatrix[i] = new Double[numString[i].length];\n }\n try {\n doubleMatrix[i][j] = Double.parseDouble(numString[i][j]);\n } catch (NumberFormatException e) {\n System.out.println(\"Couldn't convert to double\");\n } catch (NullPointerException e) {\n System.out.println(\"Can't convert Null value\");\n }\n}\n</code></pre>\n\n<p>You can rewrite like this:</p>\n\n<pre><code>for (int i = 0; i &lt; doubleMatrix.length; i++) {\n int numStringLength = numString[i].length;\n doubleMatrix[i] = new Double[numStringLength];\n for (int j = 0; j &lt; numStringLength; j++) {\n try {\n doubleMatrix[i][j] = Double.parseDouble(numString[i][j]);\n } catch (NumberFormatException e) {\n System.out.println(\"Couldn't convert to double\");\n } catch (NullPointerException e) {\n System.out.println(\"Can't convert Null value\");\n }\n}\n</code></pre>\n\n<p>Here the complete version of method <code>main</code>:</p>\n\n<pre><code>public static void main(String[] args) throws FileNotFoundException {\n\n final int ROWS = 10;\n final int COLS = 10;\n String[][] numString = new String[ROWS][COLS]; // 2-d array of strings\n\n try (Scanner inputFile = new Scanner(new File(\"test.txt\"))) {\n\n // stores contents from file into numString\n for (int i = 0; inputFile.hasNextLine() &amp;&amp; i &lt; 10; ++i) {\n String line = inputFile.nextLine();\n if (!line.trim().isEmpty()) {\n numString[i] = removeSpaces(line.split(\" \"));\n }\n }\n\n // counts and stores number of non-null rows from numString \n //in n variable\n int n = 0;\n while (n != 10 &amp;&amp; numString[n][0] != null) { n++; }\n\n\n Double[][] doubleMatrix = new Double[n][];\n\n //takes elements in numString, parses them to \n //double and stores them in doubleMatrix\n for (int i = 0; i &lt; doubleMatrix.length; i++) {\n int numStringLength = numString[i].length;\n doubleMatrix[i] = new Double[numStringLength];\n for (int j = 0; j &lt; numStringLength; j++) {\n try {\n doubleMatrix[i][j] = Double.parseDouble(numString[i][j]);\n } catch (NumberFormatException e) {\n System.out.println(\"Couldn't convert to double\");\n } catch (NullPointerException e) {\n System.out.println(\"Can't convert Null value\");\n }\n }\n }\n\n //print contents of doubleMatrix\n for (n = 0; n &lt; doubleMatrix.length; n++) {\n for (int j = 0; j &lt; doubleMatrix[n].length; j++) {\n System.out.print(doubleMatrix[n][j] + \" \");\n }\n System.out.println();\n }\n }\n\n}\n</code></pre>\n\n<p>With <code>List</code> and generally dynamic structures the code would be extremely simpler.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T09:52:11.400", "Id": "240435", "ParentId": "240375", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T00:51:55.413", "Id": "240375", "Score": "3", "Tags": [ "java" ], "Title": "Storing numbers from a file into a 2-D array" }
240375
<h3>What I made</h3> <p>I used Tkinter to write a GUI to run some HPLC pumps for my work. The application sends some messages to the pumps via serial connections, reads a response, then logs data to a csv file. <a href="https://i.stack.imgur.com/tayXE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tayXE.png" alt="main window of program"></a></p> <p>I use Matplotlib to plot the data in real time, and to let the user plot several sets of data at once. </p> <p>This is mostly a personal project I am doing in my free time at work, but I am trying to make a good-practices learning experience out of it. Nobody else is going to develop this code, but I am trying to write it to a shareable standard, such that I could include this in a portfolio of sorts one day.</p> <p>I have already linted the code up to PEP8, with maybe an exception or two. </p> <h3>How it is used</h3> <p>The typical workflow is to start a test and afk while it logs and visualizes data. Occasionally, I like to plot several sets of data for comparison. The menu bar > make new plot functionality lets me do this. The plotter window takes file paths and titles to use in the plot legend. Because I make the same plot often (or versions of it) it is helpful to be able to store those file paths and titles (rather than the image itself). I accomplish this by pickling a list to a ".plt" file that I can unpickle later to repopulate the plotter window. <a href="https://i.stack.imgur.com/h5IEE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h5IEE.png" alt="enter image description here"></a></p> <p>I am the only person using this program, but I am trying to build it in such a way that others could learn my job function and use it too. To this end, I am trying to make it pretty and intuitive. </p> <p>Since you won't have the equipment connected some buttons won't work, but most of the app should be available for prodding. </p> <h3>My main areas of concern</h3> <ul> <li>Readability <ul> <li>I did lint the code, but it still hurts my eyes in some spots... - what do?</li> </ul></li> <li>Design <ul> <li>UI elements and logic elements are kind of mixed - what do? it's not a massive app, but most lines of code are setting up GUI elements</li> <li>I would like to separate the UI and logic more, but I'm not sure how, or if doing so would be "astronaut architecture" for a project of this size</li> </ul></li> <li>Object-orientedness <ul> <li>I am unsure of if I am using self.foo too much or not enough</li> <li>I can't help but feel the way I am inheriting objects and using them is wrong, such as <a href="https://github.com/teauxfu/pct-scalewiz/blob/e1755bf497407a478b4dd4a35e071d0241ebc2c6/source/plotter.py#L169" rel="nofollow noreferrer">here</a></li> <li>eg. I don't fully grasp the meaning of what this is doing</li> <li><pre><code> def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) ...``` </code></pre></li> </ul></li> <li>Portability <ul> <li>the code currently imports from the Winsounds module which is only available for Windows machines :(</li> <li>the startup time (and file size) for one-file bundles seems to rapidly grow with additional module imports. is using python in this way to make executables just a bad practice?</li> <li>I want someone else to be able to drop this file on their computer and it "just works"</li> </ul></li> </ul> <h3>The layout of the code</h3> <ul> <li>core.py is the entry point <ul> <li>imports then creates an instance of MainWindow</li> <li>has a thread_pool_executor attribute to handle a blocking loop we make in MainWindow</li> </ul></li> <li>mainwindow.py is the bulk of the application <ul> <li>imports then creates an instance of MenuBar</li> <li>has some tkinter widgets for user input / data visualization</li> </ul></li> <li>menubar.py <ul> <li>the menubar for the MainWindow</li> <li>lets user set project directory</li> <li>can create a Plotter object (new tkinter toplevel)</li> </ul></li> <li>plotter.py <ul> <li>imports and makes a bunch of SeriesEntry objects (customer tkinter widget)</li> <li>can pickle/unpickle the contents of the SeriesEntry objects </li> </ul></li> <li>seriesentry.py <ul> <li>custom tkinter widget for selecting csv files and which column of data to be plotted</li> </ul></li> </ul> <h3>The code</h3> <p><a href="https://github.com/teauxfu/pct-scalewiz/" rel="nofollow noreferrer">Here's my GitHub repo for the code.</a> </p> <p>There's some sample csv data in the demo/sample_data repo folder if you want to try the plotting feature </p> <h2>Thanks for your time!</h2> <p>Here's mainwindow.py</p> <pre class="lang-py prettyprint-override"><code>"""The main window of the application. - imports then creates an instance of MenuBar - has some tkinter widgets for user input / data visualization """ import csv # logging the data from datetime import datetime # logging the data import matplotlib.pyplot as plt # plotting the data from matplotlib.animation import FuncAnimation from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk from matplotlib.ticker import MultipleLocator from pandas import DataFrame, read_csv # reading data from csv import os # handling file paths import serial # talking to the pumps import sys # handling file paths import tkinter as tk # GUI from tkinter import ttk import time # sleeping from winsound import Beep # beeping when the test ends from menubar import MenuBar class MainWindow(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent # define test parameters self.port1 = tk.StringVar() # COM port for pump1 self.port2 = tk.StringVar() # COM port for pump2 self.timelimit = tk.DoubleVar() self.failpsi = tk.IntVar() self.chem = tk.StringVar() self.conc = tk.StringVar() self.savepath = tk.StringVar() # output directory self.project = tk.StringVar() # used for window title self.plotpsi = tk.StringVar() # for which pump's data to plot self.plotstyle = tk.StringVar() # set initial self.paused = True self.timelimit.set(90) self.failpsi.set(1500) self.savepath.set(os.getcwd()) self.plotpsi.set('PSI 2') self.plotstyle.set('seaborn-colorblind') self.outfile = f"{self.chem.get()}_{self.conc.get()}.csv" self.build_window() def build_window(self): """Make all the tkinter widgets""" self.menu = MenuBar(self) # build the main frame self.tstfrm = tk.Frame(self.parent) self.entfrm = tk.LabelFrame(self.tstfrm, text="Test parameters") # this spacing is to avoid using multiple labels self.outfrm = tk.LabelFrame(self.tstfrm, text="Elapsed, Pump1, Pump2") self.cmdfrm = tk.LabelFrame(self.tstfrm, text="Test controls") # define the self.entfrm entries self.p1 = ttk.Entry( master=self.entfrm, width=14, textvariable=self.port1, justify=tk.CENTER ) self.p2 = ttk.Entry( master=self.entfrm, width=14, textvariable=self.port2, justify=tk.CENTER ) self.tl = ttk.Entry( master=self.entfrm, width=30, justify=tk.CENTER, textvariable=self.timelimit ) self.fp = ttk.Entry( master=self.entfrm, width=30, justify=tk.CENTER, textvariable=self.failpsi ) self.ch = ttk.Entry( master=self.entfrm, width=30, justify=tk.CENTER, textvariable=self.chem ) self.co = ttk.Entry( master=self.entfrm, width=30, justify=tk.CENTER, textvariable=self.conc ) self.strtbtn = ttk.Button( master=self.entfrm, text="Start", command=self.init_test ) # grid entry labels into self.entfrm self.comlbl = ttk.Label(master=self.entfrm, text="COM ports:") self.comlbl.grid(row=0, sticky=tk.E) ttk.Label( master=self.entfrm, text="Time limit (min):" ).grid(row=1, sticky=tk.E) ttk.Label( master=self.entfrm, text="Failing pressure (psi):" ).grid(row=2, sticky=tk.E) ttk.Label( master=self.entfrm, text="Chemical:" ).grid(row=3, sticky=tk.E) ttk.Label( master=self.entfrm, text="Concentration:" ).grid(row=4, sticky=tk.E) # grid entries into self.entfrm self.p1.grid(row=0, column=1, sticky=tk.E, padx=(9, 1)) self.p2.grid(row=0, column=2, sticky=tk.W, padx=(5, 3)) self.tl.grid(row=1, column=1, columnspan=3, pady=1) self.fp.grid(row=2, column=1, columnspan=3, pady=1) self.ch.grid(row=3, column=1, columnspan=3, pady=1) self.co.grid(row=4, column=1, columnspan=3, pady=1) self.strtbtn.grid(row=5, column=1, columnspan=2, pady=1) cols = self.entfrm.grid_size() for col in range(cols[0]): self.entfrm.grid_columnconfigure(col, weight=1) # build self.outfrm PACK scrollbar = tk.Scrollbar(self.outfrm) self.dataout = tk.Text( master=self.outfrm, width=39, height=12, yscrollcommand=scrollbar.set, state='disabled' ) # TODO: try calling tk.Scrollbar(self.outfrm) directly scrollbar.config(command=self.dataout.yview) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.dataout.pack(fill=tk.BOTH) # build self.cmdfrm 4x3 GRID self.runbtn = ttk.Button( master=self.cmdfrm, text="Run", command=lambda: self.run_test(), width=15 ) self.endbtn = ttk.Button( master=self.cmdfrm, text="End", command=lambda: self.end_test(), width=15 ) self.runbtn.grid(row=1, column=1, padx=5, pady=2, sticky=tk.W) self.endbtn.grid(row=1, column=2, padx=5, pady=2, sticky=tk.E) tk.Label( master=self.cmdfrm, text="Select data to plot:" ).grid(row=0, column=0, padx=5) tk.Radiobutton( master=self.cmdfrm, text="PSI 1", variable=self.plotpsi, value='PSI 1' ).grid(row=0, column=1, padx=5) tk.Radiobutton( master=self.cmdfrm, text="PSI 2", variable=self.plotpsi, value='PSI 2' ).grid(row=0, column=2, padx=5) # disable the controls to prevent starting test w/o parameters if self.paused: for child in self.cmdfrm.winfo_children(): child.configure(state="disabled") # set up the plot area self.pltfrm = tk.LabelFrame( master=self.tstfrm, text=("Style: " + self.plotstyle.get()) ) self.fig, self.ax = plt.subplots(figsize=(7.5, 4), dpi=100) plt.subplots_adjust(left=0.10, bottom=0.12, right=0.97, top=0.95) # TODO: explicitly clarify some of these args self.canvas = FigureCanvasTkAgg(self.fig, master=self.pltfrm) toolbar = NavigationToolbar2Tk(self.canvas, self.pltfrm) toolbar.update() self.canvas.get_tk_widget().pack() self.ani = FuncAnimation(self.fig, self.animate, interval=1000) # grid stuff into self.tstfrm self.entfrm.grid(row=0, column=0, sticky=tk.NSEW, pady=2) self.pltfrm.grid(row=0, column=1, rowspan=3, sticky=tk.NSEW, padx=2) self.outfrm.grid(row=1, column=0, sticky=tk.NSEW, pady=2) self.cmdfrm.grid(row=2, column=0, sticky=tk.NSEW, pady=2) # widget bindings self.co.bind("&lt;Return&gt;", self.init_test) self.comlbl.bind("&lt;Button-1&gt;", lambda _: self.findcoms()) self.tstfrm.grid(padx=3) self.findcoms() self.ch.focus_set() def findcoms(self): """Looks for COM ports and disables the controls if two aren't found""" self.to_log("Finding COM ports...") ports = ["COM" + str(i) for i in range(15)] useports = [] for i in ports: try: if serial.Serial(i).is_open: self.to_log(f"Found an open port at {i}") useports.append(i) serial.Serial(i).close except serial.SerialException: pass if useports == []: self.to_log("No COM ports found...") self.to_log("Click 'COM ports:' to try again.") useports = ["??", "??"] try: self.port1.set(useports[0]) self.port2.set(useports[1]) if self.port1.get() == "??" or self.port2.get() == "??": self.strtbtn['state'] = ['disable'] else: self.strtbtn['state'] = ['enable'] except IndexError: pass except AttributeError: pass def init_test(self): """Collects all the user data from the GUI widgets""" self.port1.set(self.p1.get()) self.port2.set(self.p2.get()) self.timelimit.set(self.tl.get()) self.failpsi.set(self.fp.get()) self.chem.set(self.ch.get()) self.conc.set(self.co.get()) self.outfile = f"{self.chem.get()}_{self.conc.get()}.csv" self.psi1, self.psi2, self.elapsed = 0, 0, 0 # the timeout values are an alternative to using TextIOWrapper self.pump1 = serial.Serial(self.port1.get(), timeout=0.01) print(f"Opened a port at {self.port1.get()}") self.pump2 = serial.Serial(self.port2.get(), timeout=0.01) print(f"Opened a port at {self.port2.get()}") # set up output file outputpath = os.path.join(self.savepath.get(), self.outfile) print(f"Creating output file at {outputpath}") with open(os.path.join(self.savepath.get(), self.outfile), "w") as f: csv.writer(f, delimiter=',').writerow( [ "Timestamp", "Seconds", "Minutes", "PSI 1", "PSI 2" ] ) # disable the entries for test parameters for child in self.entfrm.winfo_children(): child.configure(state="disabled") # enable the commands for starting/stopping the test for child in self.cmdfrm.winfo_children(): child.configure(state="normal") def to_log(self, msg): """Logs a message to the Text widget in MainWindow's outfrm""" self.dataout['state'] = 'normal' self.dataout.insert('end', f"{msg}" + "\n") self.dataout['state'] = 'disabled' self.dataout.see('end') def end_test(self): """Stops the pumps and closes their COM ports, then swaps the button states for the entfrm and cmdfrm widgets""" self.paused = True self.pump1.write('st'.encode()) self.pump1.close() self.pump2.write('st'.encode()) self.pump2.close() msg = "The test finished in {0:.2f} minutes".format(self.elapsed/60) self.to_log(msg) for child in self.entfrm.winfo_children(): child.configure(state="normal") for child in self.cmdfrm.winfo_children(): child.configure(state="disabled") def run_test(self): """Submits a test loop to the thread_pool_executor""" if self.paused: self.pump1.write('ru'.encode()) self.pump2.write('ru'.encode()) self.paused = False # let the pumps warm up before we start recording data time.sleep(3) self.parent.thread_pool_executor.submit(self.take_reading) def take_reading(self): """loop to be handled by the thread_pool_executor""" starttime = datetime.now() while ( (self.psi1 &lt; self.failpsi.get() or self.psi2 &lt; self.failpsi.get()) and self.elapsed &lt; self.timelimit.get()*60 and not self.paused ): rn = time.strftime("%I:%M:%S", time.localtime()) self.pump1.write("cc".encode()) self.pump2.write("cc".encode()) time.sleep(0.1) self.psi1 = int(self.pump1.readline().decode().split(',')[1]) self.psi2 = int(self.pump2.readline().decode().split(',')[1]) thisdata = [ rn, self.elapsed, # as seconds '{0:.2f}'.format(self.elapsed/60), # as minutes self.psi1, self.psi2 ] outputpath = os.path.join(self.savepath.get(), self.outfile) with open((outputpath), "a", newline='') as f: csv.writer(f, delimiter=',').writerow(thisdata) nums = ((self.elapsed/60), self.psi1, self.psi2) logmsg = ("{0:.2f} min, {1} psi, {2} psi".format(nums)) self.to_log(logmsg) time.sleep(0.9) self.elapsed = (datetime.now() - starttime).seconds if not self.paused: self.end_test() for i in range(3): Beep(750, 500) time.sleep(0.5) def animate(self, i): """The animation function for the current test's data""" try: data = read_csv(os.path.join(self.savepath.get(), self.outfile)) except FileNotFoundError as e: data = DataFrame(data={'Minutes': [0], 'PSI 1': [0], 'PSI 2': [0]}) # TODO: this plt stuff can probably go elsewhere plt.rcParams.update(plt.rcParamsDefault) # refresh the style # https://stackoverflow.com/questions/42895216 with plt.style.context(self.plotstyle.get()): self.pltfrm.config(text=("Style: " + self.plotstyle.get())) self.ax.clear() self.ax.set_xlabel("Time (min)") self.ax.set_ylabel("Pressure (psi)") self.ax.set_ylim(top=self.failpsi.get()) self.ax.yaxis.set_major_locator(MultipleLocator(100)) self.ax.set_xlim(left=0, right=self.timelimit.get()) y = data[self.plotpsi.get()] x = data['Minutes'] self.ax.plot(x, y, label=(f"{self.chem.get()}_{self.conc.get()}")) self.ax.grid(color='grey', alpha=0.3) self.ax.set_facecolor('w') self.ax.legend(loc=0) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:44:10.467", "Id": "471541", "Score": "0", "body": "Dude, this is really impressive." } ]
[ { "body": "<h2>Data vis considerations</h2>\n\n<p>Currently you seem to have a fixed time-axis range. Consider scaling it as time passes. I have also written an industrial control project with some features similar to this, but my time display was rendered differently and could give you some ideas:</p>\n\n<ul>\n<li>The newest data actually appear at the right edge of the graph</li>\n<li>The time axis ranges from a negative earliest-seen time to zero, interpretable as \"seconds/minutes/etc. ago\"</li>\n<li>The time axis dynamically changes its units based on how much time has elapsed</li>\n</ul>\n\n<p>Unfortunately the code wouldn't be of much use to you since it's in Mono/GTK2, but the algorithm could be used.</p>\n\n<p>Also, your data appear to be exponential in nature. If that holds true I would suggest making the vertical axis logarithmic.</p>\n\n<p>p.s. once your graph is properly scaled you will find that the legend position may need to move to either upper-left or lower-right to avoid occluding your curves.</p>\n\n<h2>Mixing logic and presentation</h2>\n\n<p><code>MainWindow</code> was doing good, adhering to GUI-only tasks - right up until <code>findcoms</code>. This is pretty clearly a business logic concern and should be separated into a different class and/or module.</p>\n\n<p><code>init_test</code> is a big mix of UI and logic, which you should also attempt to decouple.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:10:51.290", "Id": "471544", "Score": "1", "body": "Thanks for your consideration! I’ll play around with putting the vertical axis on a log scale and see how it presents. Since this is pressure vs time data though a logarithmic unit might be confusing to interpret. I’ll look into cleaning up findcoms/ init_test. I think a simple import statement should let me separate the second half of mainwindow into just test logic. Thanks for your time!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:12:33.507", "Id": "471547", "Score": "1", "body": "Log scales are easy enough to interpret as long as some basic rules are followed - use a radix of 10; show sub-ticks; show a pale sub-grid and a normal-opacity primary grid; etc. This should be easy to do with `matplotlib`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:01:24.590", "Id": "240410", "ParentId": "240378", "Score": "2" } } ]
{ "AcceptedAnswerId": "240410", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T03:04:47.763", "Id": "240378", "Score": "5", "Tags": [ "python", "gui", "tkinter", "data-visualization", "matplotlib" ], "Title": "Tkinter GUI for running HPLC pumps, real-time data visualization" }
240378
<p>I'm using <a href="https://github.com/bvaughn/react-window" rel="nofollow noreferrer"><code>react-window</code></a> to virtualize a list. My list is supposed to fill in the container's completely and the container's width and height are 30vh and 100vh. Since the dimensions are dynamic and react-window requires me to provide constant dimensions, I'm hooking into the <code>onresize</code> event and updating the state of the component to pass the dimensions to the <code>FixedSizeList</code> component. </p> <p>I was wondering if there was a better way to do this.</p> <pre><code>import React, { useEffect, useRef, useState } from 'react' import { FixedSizeList } from 'react-window' import InfiniteLoader from 'react-window-infinite-loader' const MyList = () =&gt; { const { items, hasOlder, loadOlder } = mobxStore const divRef = useRef&lt;HTMLDivElement&gt;(null) const [height, setHeight] = useState(divRef.current?.clientHeight || 800) const [width, setWidth] = useState(divRef.current?.clientWidth || 400) useEffect(() =&gt; { const handler = () =&gt; { const h = divRef.current.clientHeight const w = divRef.current.clientWidth if (height !== h) setHeight(h) if (width !== w) setWidth(w) } window.addEventListener('resize', handler) return () =&gt; window.removeEventListener('resize', handler) }, []) const itemCount = items.length + (hasOlder ? 1 : 0) return ( &lt;div className="items" ref={divRef}&gt; &lt;InfiniteLoader isItemLoaded={index =&gt; index &lt; items.length} itemCount={itemCount} loadMoreItems={loadOlder} &gt; {({ onItemsRendered, ref }) =&gt; ( &lt;FixedSizeList onItemsRendered={onItemsRendered} ref={ref} itemCount={itemCount} itemSize={60} height={divRef.current?.clientHeight || height} width={divRef.current?.clientWidth || width} overscanCount={10} &gt; {({ index, style }) =&gt; { const item = items[index] if (!item) return &lt;div className="loading" style={style}&gt;Loading...&lt;/div&gt; return &lt;div style={style}&gt;{renderItem(item)}&lt;/div&gt; }} &lt;/FixedSizeList&gt; )} &lt;/InfiniteLoader&gt; &lt;/div&gt; ) } export default MyList </code></pre> <p>EDIT: Found out the library author recommends using <code>react-virtualized-auto-sizer</code> instead</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T06:26:26.840", "Id": "240380", "Score": "1", "Tags": [ "javascript", "react.js", "typescript" ], "Title": "React virtualized list dynamic width/height" }
240380
<p>I am generating View and setting constraints programmatically in <code>UIViewController</code></p> <pre><code>import UIKit import SnapKit class LoginViewController: UIViewController { lazy var topImageView = UIImageView() lazy var centerStackView = UIStackView() lazy var phoneTextField = UITextField() lazy var sendOTPButton = UIButton() lazy var bottomStackView = UIStackView() lazy var separatorLine = UILabel() lazy var signUpButton = UIButton() override func viewDidLoad() { super.viewDidLoad() makeUI() } private func makeUI() { self.view.backgroundColor = .white self.view.addSubview(topImageView) topImageView.backgroundColor = UIColor.magenta.withAlphaComponent(0.4) topImageView.snp.makeConstraints {(make) -&gt; Void in make.width.equalToSuperview() make.height.equalTo(225) make.topMargin.equalToSuperview() make.centerX.equalToSuperview() } centerStackView.translatesAutoresizingMaskIntoConstraints = false centerStackView.axis = .vertical centerStackView.distribution = .fillEqually self.view.addSubview(phoneTextField) self.view.addSubview(sendOTPButton) self.view.addSubview(centerStackView) centerStackView.addArrangedSubview(phoneTextField) centerStackView.addArrangedSubview(sendOTPButton) phoneTextField.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2) phoneTextField.delegate = self sendOTPButton.setTitle("Send OTP", for: .normal) sendOTPButton.addTarget(self, action: #selector(generateAccessToken), for: .touchUpInside) sendOTPButton.backgroundColor = .blue centerStackView.snp.makeConstraints { (make) in make.center.equalToSuperview() make.width.equalToSuperview() make.height.equalTo(100) } bottomStackView.translatesAutoresizingMaskIntoConstraints = false bottomStackView.axis = .vertical bottomStackView.distribution = .fillProportionally self.view.addSubview(separatorLine) self.view.addSubview(signUpButton) self.view.addSubview(bottomStackView) bottomStackView.addArrangedSubview(separatorLine) bottomStackView.addArrangedSubview(signUpButton) separatorLine.backgroundColor = .white signUpButton.backgroundColor = .orange bottomStackView.snp.makeConstraints { (make) in make.bottomMargin.equalTo(additionalSafeAreaInsets) make.width.equalToSuperview() make.height.equalTo(80) } } </code></pre> <p>The <code>makeUI</code> functions essentially creates the views, adds them to <code>UIController</code>'s view (as a subview) and set constraints on them (AutoLayout). But the ViewController become bulky if more <code>UIView</code>s are added.</p> <p>My question is:</p> <ul> <li>Should I move the UI code to another file (say <code>LoginView.swift</code>)? Or is it recommended to keep the UI code in <code>UIViewController</code> as they are tightly coupled?</li> </ul>
[]
[ { "body": "<p>You can move setting properties to lazy var declarations eg. </p>\n\n<pre><code>lazy var centerStackView: UIStackView = {\n let stackView = UIStackView()\n stackView.translatesAutoresizingMaskIntoConstraints = false\n stackView.axis = .vertical\n stackView.distribution = .fillEqually\n return stackView\n}()\n</code></pre>\n\n<p>This will divide your code nicely. In my opinion, extracting views to separate files has a sense only if they have a more complex structure and you want to reuse them in other places. What is important is keeping functions short and on point. Also, try to use more empty lines to visually divide logic blocks, eg. adding subview and setting constraints to it from another subview. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:56:30.160", "Id": "471527", "Score": "0", "body": "Thanks a lot. I have done the first part. For not extracting out the UI code, it makes the View Controller massive. Is that okay?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:05:47.133", "Id": "471529", "Score": "0", "body": "As long as code is readable and divided, so every element can be easily found and modified, shared properties like magic numbers (common paddings, alphas, margins etc.) are extracted - in my opinion, it's not a problem. The golden rule is to extract logic from ViewControllers, but views and constraints has to be defined somewhere. \n\nVery minor suggestion; I would rename makeUI to setupUI ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:07:44.893", "Id": "471531", "Score": "0", "body": "Thanks. +1\nSo what would be the downsides of crating a View file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:18:27.077", "Id": "471536", "Score": "0", "body": "Basically YAGNI rule ( https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it ) and over fragmentation of the code. When you have all connected parts in one file (as long as they conform to rules above) it's easier to comprehend them. If to get full overview of view you need to go through 5 separate files - it gives more problems than advantages. It's something that you start to notice when reading other people's code. \n\nExtraction makes sense when it solves redundancy issues, or like mentioned, part's are re-used in multiple places." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:18:53.133", "Id": "471537", "Score": "0", "body": "Aside of that, I think over half of this code are addSubview and constraints methods which need to be in VC anyway." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:52:44.370", "Id": "240402", "ParentId": "240381", "Score": "4" } }, { "body": "<p>The other obvious alternative, which you haven’t contemplated here, is to design it right in the storyboard or NIB in Interface Builder, which would eliminate all of this code. </p>\n\n<p>The only view creation related code that I would put in the view controller is those just-in-time adjustments/subviews that cannot be determined at design-time, but rather are dictated by the presence or absence of relevant model data. </p>\n\n<p>Anyway, if you do that, then the view controller can focus on its <a href=\"https://developer.apple.com/documentation/uikit/uiviewcontroller\" rel=\"nofollow noreferrer\">core responsibilities</a>:</p>\n\n<blockquote>\n <p>A view controller’s main responsibilities include the following:</p>\n \n <ul>\n <li>Updating the contents of the views, usually in response to changes to the underlying data.</li>\n <li>Responding to user interactions with views.</li>\n <li>Resizing views and managing the layout of the overall interface.</li>\n <li>Coordinating with other objects—including other view controllers—in your app.</li>\n </ul>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:46:46.163", "Id": "471574", "Score": "0", "body": "Hi thanks for this perspective! But we have moved away from Storyboards and creating UI programmatically for various reasons" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:49:29.580", "Id": "471575", "Score": "0", "body": "I gathered as much, but wanted to add this for the sake of future readers. Happy coding." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:44:38.583", "Id": "240421", "ParentId": "240381", "Score": "3" } }, { "body": "<p>It is good practice to extract the UI as smaller components in smaller classes and use UIViewController only to bring them together. You should try to imagine each component as an independent unity which could be reused across your application in multiple places.</p>\n\n<p>Writing code by UI brings more clarity but it is a matter of person choice and takes time getting used to it.</p>\n\n<p>We have been writing apps by writing UI by code from past few years and we don't regret it. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T10:12:12.790", "Id": "242691", "ParentId": "240381", "Score": "2" } } ]
{ "AcceptedAnswerId": "240402", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T06:42:25.187", "Id": "240381", "Score": "1", "Tags": [ "design-patterns", "swift", "ios" ], "Title": "Create UIView programmatically in Swift" }
240381
<h1>The Problem</h1> <p>I wanted to create a program that is able to convert roman numbers to arabic numbers and vice versa.</p> <p>Roman numerals consist of the following symbols:</p> <pre><code>| Symbol | I | V | X | L | C | D | M | |--------|---|---|----|----|-----|-----|------| | Value | 1 | 5 | 10 | 50 | 100 | 500 | 1000 | </code></pre> <p>One of the fundamental rules of roman numbers says that it is not possible to use the same symbol more than three times in a row. So it is possible to write III = 3, but it is not possible to write IIII = 4.</p> <p>To write these kind of numbers, you can use the following so called subtractive notation: If a symbol is in front of another, whose value is greater than the value of the first symbol, than the the first value is subtracted from the second value. </p> <p>For example: IV = 4, XL = 40, but for example VI = 6 and not -4.</p> <h1>The Solution</h1> <p>Here's the code:</p> <pre><code>import java.util.Scanner; public class RomanNumbers { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int decision = getInput(); if(decision == 1) { String number = getRoman(); System.out.println(romanToArabic(number)); } else { int number = getInt(); System.out.println(arabicToRoman(number)); } scanner.close(); } public static int romanToArabic(String number) { if(!number.matches("[IVXLCDM]+") || number.equals("") || number == null) { return -1; } int length = number.length(); int result = 0; for(int i = 0; i &lt; length; i++) { //Illegal Character if(getValue(number.charAt(i)) == -1) { return -1; } //More than 3 same Characters successively if(i &lt; length - 3) { if(number.charAt(i) == number.charAt(i + 1) &amp;&amp; number.charAt(i) == number.charAt(i + 2) &amp;&amp; number.charAt(i) == number.charAt(i + 3)) { return - 1; } } //Applying rules if(i &lt; length - 1) { int currentChar = getValue(number.charAt(i)); int nextChar = getValue(number.charAt(i + 1)); if(currentChar &lt; nextChar) { result = result + nextChar - currentChar; i++; } else { result = result + currentChar; } } else { result = result + getValue(number.charAt(i)); } } return result; } public static String arabicToRoman(int number) { if(number &lt; 1 || number &gt; 3999) { return "Error"; } String result = ""; int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] romanNumerals = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; int i = 0; //Here happens the main task while(i &lt; values.length) { if(number &gt;= values[i]) { result += romanNumerals[i]; number = number - values[i]; } else { i++; } } return result; } //Returns value of roman numeral private static int getValue(char c) { char[] array = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; int[] arr = {1, 5, 10, 50, 100, 500, 1000}; for(int i = 0; i &lt; array.length; i++) { if(c == array[i]) { return arr[i]; } } return -1; } //Gets input - (1) or (2) private static int getInput() { System.out.print("Roman to Arabic (1) or Arabic to Roman (2)?"); int decision = scanner.nextInt(); if(decision != 1 &amp;&amp; decision != 2) { return getInput(); } return decision; } //gets roman number as input and checks if it only consists of roman numerals private static String getRoman() { String number = ""; while(!number.matches("[IVXLCDM]+")) { number = scanner.nextLine(); if(!number.matches("[IVXLCDM]+")) { System.out.println("Enter roman number:"); } } return number; } //gets integer between 1 and 3999 as input private static int getInt() { int number = 0; System.out.println("Enter number:"); try { number = scanner.nextInt(); } catch(Exception e) { scanner.nextLine(); } if(number &gt; 3999 || number &lt; 1) { return getInt(); } return number; } } </code></pre> <h1>Testing</h1> <p>For testing purposes I wrote the following class:</p> <pre><code> public class Test { public static void main(String[] args) { //Testing romanToArabic() boolean test1 = true; String[] input1 = { "", "I", "V", "XXXIII", "DCCXLVII", "CMXXIX", "MCCXXXII", "MMMCMXCIX", "MMMMXI", "KMXI"}; int[] expectedOutput1 = {-1, 1, 5, 33, 747, 929, 1232, 3999, -1, -1}; for(int i = 0; i &lt; input1.length; i++) { if(RomanNumbers.romanToArabic(input1[i]) != expectedOutput1[i]) { test1 = false; } } System.out.println("Roman to Arabic: " + test1); //Testing arabicToRoman() boolean test2 = true; int[] input2 = {-1, 1, 5, 33, 747, 929, 1232, 3999, 4000}; String[] expectedOutput2 = {"Error", "I", "V", "XXXIII", "DCCXLVII", "CMXXIX", "MCCXXXII", "MMMCMXCIX", "Error"}; for(int i = 0; i &lt; input2.length; i++) { if(!(RomanNumbers.arabicToRoman(input2[i])).equals(expectedOutput2[i])) { test2 = false; } } System.out.println("Roman to Arabic: " + test2); } } </code></pre> <h1>Question</h1> <p>How can I improve both, the main-Class and the testing class?</p> <p>I would appreciate any suggestions.</p> <hr> <p>You can find the follow-up question on unit-testing <a href="https://codereview.stackexchange.com/questions/240490/junit-unit-testing">here</a>.</p>
[]
[ { "body": "<h1>Magic Numbers</h1>\n\n<p>From <code>main()</code>, we can see <code>getInput()</code> returns <code>1</code> or some other value. What input does <code>getInput()</code> get? What does <code>1</code> mean? What is the other value?</p>\n\n<p>Consider using named constants, such as:</p>\n\n<pre><code>private final static int ROMAN_TO_ARABIC = 1;\nprivate final static int ARABIC_TO_ROMAN = 2;\n</code></pre>\n\n<p>And change <code>getInput()</code> to something more meaning full, like perhaps <code>getConversionDirection()</code>.</p>\n\n<p>The variable <code>decision</code> is equally cryptic. What decision? Did the program decide something, or was it a command from the user and not actually a decision by the program? Maybe <code>conversion_direction</code>, or simply <code>direction</code>.</p>\n\n<p>The <code>if</code>/<code>else</code> statement would be better served by a case statement:</p>\n\n<pre><code>switch (conversion_direction) {\n case ROMAN_TO_ARABIC: {\n ...\n } break;\n case ARABIC_TO_ROMAN: {\n ...\n } break;\n}\n</code></pre>\n\n<p>This makes it very clear what the choice is all about.</p>\n\n<p>Even better: instead of named integer constants, use an <code>enum</code>:</p>\n\n<pre><code>public enum ConversionDirection { ROMAN_TO_ARABIC, ARABIC_TO_ROMAN };\n</code></pre>\n\n<h1>try-with-resources</h1>\n\n<p>Manually closing resources, like the <code>scanner</code> is tedious. And error prone, especially when exceptions might be raised.</p>\n\n<p>You should use the <code>try-with-resources</code> construct, which automatically closes resources for you.</p>\n\n<pre><code>try (Scanner scanner = new Scanner(System.in) {\n // .... use the scanner here ...\n}\n// Scanner is automatically closed at this point, even if an exception is raised\n</code></pre>\n\n<h1>Too much validation</h1>\n\n<p><code>getRoman()</code> can only return a string which matches <code>\"[IVXLCDM]+\"</code>. This precluded <code>null</code> and the <code>\"\"</code>. Then, <code>romanToArabic()</code> redundantly checks for these conditions. (Incorrectly, actually. If <code>number == null</code>, the first part of the expression would generate a <code>NullPointerException</code> before the <code>null</code> check at the end!) Then, each character of string is yet again tested by <code>getValue()</code> to see if it is in the set <code>IVXLCDM</code>.</p>\n\n<h1>Redundant queries</h1>\n\n<p>The expression <code>number.charAt(i)</code> occurs 6 times inside the <code>while</code> loop. This would be a good place to use a temporary variable at the start of the loop:</p>\n\n<pre><code>char ch = number.charAt(i);\n</code></pre>\n\n<h1>Insufficient validation</h1>\n\n<p><code>IC</code>, <code>IL</code>, <code>IC</code>, <code>ID</code>, <code>IM</code>, <code>VX</code>, <code>VV</code>, <code>DD</code>, <code>XD</code>, <code>XM</code>, <code>VX</code>, and so on are all improper Roman numerals. Only <code>I</code>, <code>X</code>, and <code>C</code> are legal subtractive prefixes, and only in front of <code>V</code> &amp; <code>X</code> for <code>I</code>, <code>L</code> &amp; <code>C</code> for <code>X</code>, and <code>D</code> &amp; <code>M</code> for <code>C</code>. </p>\n\n<p>Moreover, <code>IX</code> is valid, <code>XIII</code> is valid, but <code>IXIII</code> is not valid. A subtractive prefix may not be followed by the same suffix, adding what was subtracted.</p>\n\n<p><code>getInt()</code> will catch any exception (it should only catch <code>InputMismatchException</code>), and clear the invalid line. <code>getInput()</code> doesn’t catch any exception and a bad input will crash the program.</p>\n\n<h1>Recursion</h1>\n\n<p><code>getInt()</code> and <code>getInput()</code> recursively call themselves if out-of-range input is given. You should use a loop, not recursion.</p>\n\n<h1>Testing</h1>\n\n<p>Testing can be improved by leveraging the <a href=\"https://junit.org/junit5/\" rel=\"noreferrer\"><code>JUnit</code></a> testing framework. And adding more tests, such as the invalid cases mentioned above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T09:50:15.107", "Id": "471757", "Score": "1", "body": "Thanks for your answer, I just posted a follow-up question at https://codereview.stackexchange.com/questions/240490/junit-unit-testing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T04:58:21.223", "Id": "240430", "ParentId": "240382", "Score": "5" } } ]
{ "AcceptedAnswerId": "240430", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T07:46:09.463", "Id": "240382", "Score": "3", "Tags": [ "java", "roman-numerals" ], "Title": "Roman Numbers in Java" }
240382
<p>I wrote an express API for a document management service (repo to be found <a href="https://github.com/doc-sys/docsys" rel="nofollow noreferrer">here</a>) and even though I understand the importance of unit-testing I never quite managed to wrap my head around how I would test an API like this. I have no idea if my test are actually testing something useful or are covering everything that could be tested:</p> <pre><code>describe('User', () =&gt; { before((done) =&gt; { user.deleteMany({}, (err) =&gt; { done() }) }) describe('/POST signup', () =&gt; { it('should not create a new user with invalid mail syntax', (done) =&gt; { let body = { username: 'test_user', password: 'test_password', mail: 'invalid', diplayName: 'Testi Test', } chai .request(server) .post('/user/signup') .send(body) .end((err, res) =&gt; { res.should.have.status(500) res.body.should.be.a('object') res.body.payload.should.have.a.property('message') res.body.payload.message.should.be.a('string') done() }) }) it('should create a new user with valid syntax', (done) =&gt; { let body = { username: 'test_user', password: 'test_password', mail: 'test@test.de', diplayName: 'Testi Test', } chai .request(server) .post('/user/signup') .send(body) .end((err, res) =&gt; { res.should.have.status(200) res.body.should.be.a('object') res.body.payload.should.have.a.property('user') res.body.payload.should.have.a.property('token') res.body.payload.user.should.be.a('object') res.body.payload.token.should.be.a('string') done() }) }) }) describe('/POST login', () =&gt; { it('should not login without password or username', (done) =&gt; { let body = { username: 'test_user', } chai .request(server) .post('/user/login') .send(body) .end((err, res) =&gt; { res.should.have.status(401) res.body.should.be.a('object') res.body.payload.should.have.a.property('message') res.body.payload.message.should.be.a('string') }) body = { password: 'test_password', } chai .request(server) .post('/user/login') .send(body) .end((err, res) =&gt; { res.should.have.status(401) res.body.should.be.a('object') res.body.payload.should.have.a.property('message') res.body.payload.message.should.be.a('string') }) done() }) it('should not login with wrong credentials', (done) =&gt; { body = { username: 'wrong_name', password: 'test_password' } chai .request(server) .post('/user/login') .send(body) .end((err, res) =&gt; { res.should.have.status(401) res.body.should.be.a('object') res.body.payload.should.have.a.property('message') res.body.payload.message.should.be.a('string') done() }) }) it('should login with correct credentials', (done) =&gt; { body = { username: 'test_user', password: 'test_password' } chai .request(server) .post('/user/login') .send(body) .end((err, res) =&gt; { res.should.have.status(200) res.body.should.be.a('object') res.body.payload.should.have.a.property('user') res.body.payload.should.have.a.property('token') res.body.payload.user.should.be.a('object') res.body.payload.token.should.be.a('string') done() }) }) }) }) </code></pre> <p>These are the routes to be tested:</p> <pre><code>router .route('/login') /** * @api {post} /user/login User login * @apiName userLogin * @apiGroup User * @apiDescription Logs user in and returns the user and API token * @apiParam {String} username * @apiParam {String} password * @apiSuccess {Object} user User profile * @apiSuccess {String} token API token * @apiError (401) {String} LoginFailed */ .post(async (req, res) =&gt; { try { let result = await user.getAuthenticated( req.body.username, req.body.password ) const token = await jwt.sign(result.toJSON(), process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES, }) res.status(200).json({ payload: { user: result, token: token } }) } catch (error) { res.status(401).json({ payload: { message: 'Login failed' } }) } }) router .route('/signup') /** * @api {post} /user/signup User signup * @apiName userSignup * @apiGroup User * @apiDescription Signs user up and logs in automatically * @apiParam {String} username Username * @apiParam {String} password Password according to policy * @apiParam {String} mail Valid email * @apiParam {String} displayName Full name * @apiSuccess {Object} user User profile * @apiSuccess {String} token API token * @apiError (500) {String} InternalError Something went wrong during signup. Most likely to be during validation. * @apiDeprecated Users should not be allowed to sign up by themselfes but rather be invited to use docSys */ .post(async (req, res) =&gt; { try { let newUser = new user({ username: req.body.username, password: req.body.password, mail: req.body.mail, settings: { language: 'en', displayName: req.body.displayName, }, }) const token = jwt.sign(newUser.toObject(), process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES, }) await newUser.save() res.status(200).json({ payload: { user: newUser, token: token } }) } catch (error) { res.status(500).json({ payload: { message: error.message } }) } }) </code></pre> <p>My questions are:</p> <ol> <li>Are these tests sufficient to cover these routes? </li> <li>Am I testing the mongoose model in a seperate test or can I just assume that it's doing its thing correctly if tests like these pass? </li> </ol> <p>I know it's quite stupid to write tests after big portions of the API have already been written, but I figured I'll have to start at some point.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T14:07:02.660", "Id": "471496", "Score": "0", "body": "\"Are these tests sufficient to cover these routes?\" Are you aware there are automated tools that test your coverage? You should still read up on the basics so you understand what you're actually doing, but it looks like you're asking us to verify the correctness of your tests. Did you try running them? Do you have any metrics on them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:57:58.293", "Id": "471518", "Score": "0", "body": "Thank for your comment. I'm more asking if this is the correct way of testing an API: specifying \"use cases\", because wouln't that just test the scenarios I could think of? I'm aware of test coverage and still trying to get into it. As said I'm more thinking of the amount of scenarios to test for each route. The tests are running great and are passing." } ]
[ { "body": "<p>First, I suggest separating the tests of each endpoint to a different file.</p>\n\n<h2>Signup tests</h2>\n\n<p>Do you have <strong>validations</strong> for other fields except for the email? If so add tests for them. Examples: duplicate email, duplicate user name, weak password.</p>\n\n<p>You can also test what happens if the <strong>structure</strong> of the request is wrong. For example missing fields. </p>\n\n<p>You can add more tests with different invalid emails according to the email validation logic. But I suggest testing this in unit tests. </p>\n\n<h2>Login tests</h2>\n\n<p>I think you should have the following tests: </p>\n\n<ul>\n<li>Login without Signup </li>\n<li>Login with a wrong username (after signup)</li>\n<li>Login with a wrong password (after signup)</li>\n<li>Successful login</li>\n</ul>\n\n<p>You should have a <strong>setup</strong> of <strong>signup</strong> in those tests. Which makes me wonder how <code>'should login with correct credentials'</code> works?</p>\n\n<p>I saw in the code you have a mechanism for too many wrong login attempts so you should add tests for it.</p>\n\n<h2>Assertions</h2>\n\n<p>I see you are checking the <strong>status code</strong> and the <strong>structure</strong> of the payload but not its content. </p>\n\n<h2>Failures Tests</h2>\n\n<p>Since you are writing tests after the code is written, you can write tests for failures looking at the code and understand its assumptions. a simple example: what happens if the DB is down. </p>\n\n<hr>\n\n<p>In this answer, I am Ignoring the effort of writing those tests. It is your job to decide which worth the effort and which not.</p>\n\n<p>You said </p>\n\n<blockquote>\n <p>I know it's quite stupid to write tests after big portions of the API have already been written</p>\n</blockquote>\n\n<p><strong>So I encourage you to try TDD for your next API endpoint :-)</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T16:22:08.913", "Id": "472056", "Score": "0", "body": "Thanks a lot for your comment, it already is very helpful to me! What exactyl do you mean by a setup of signup?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T16:41:07.037", "Id": "472057", "Score": "0", "body": "@FelixWieland in order to test login you need to perform signup. All the operations in a test done before the tested function are called setup." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T18:55:05.237", "Id": "472076", "Score": "0", "body": "Ah ok, shouldnt the order of my tests already satisfy that requirement? I'm creating a test user in my db that I am then again using to check the login function. The db is only cleared at the very beginning of my test run." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T19:10:01.733", "Id": "472079", "Score": "1", "body": "@FelixWieland you shouldn't make test depand on other test executing. Each test should be able to run alone. Also when those tests run in the build you want to be able to run them in parallel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-24T16:13:01.730", "Id": "473167", "Score": "0", "body": "I'll add to shanif's comment – when your db can be fully torn down and setup with fixtures before each test, it's a beautiful thing. Your logical units of code are truly independent and can perform their single responsibility." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T11:05:43.790", "Id": "240552", "ParentId": "240384", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T10:38:07.460", "Id": "240384", "Score": "4", "Tags": [ "javascript", "unit-testing", "node.js", "express.js", "mocha" ], "Title": "Correct way to unit-test express API" }
240384
<p>I have a massive set of latitude, longitude pairs. I also have a list of <a href="https://geojson.org/" rel="nofollow noreferrer">GeoJson</a> formatted locations. I want to find out which location each pair of coordinates lies in.</p> <p>I have some code to do this, but it's super slow and won't work against my dataset in it's current format:</p> <pre><code># Load Dataset CHICAGO_CRIME = '/content/drive/My Drive/CA683_Assignment_Additional/2010-crime.csv' CHICAGO_COMMUNITY_AREAS = '/content/drive/My Drive/CA683_Assignment_Additional/Boundaries - Community Areas (current).geojson' # Load crime data-set crime_df = pd.read_csv(CHICAGO_CRIME, parse_dates=True) # Load community areas with open(CHICAGO_COMMUNITY_AREAS) as f: chicago_community_areas = json.load(f) # Store polygon objects for feature in chicago_community_areas['features']: feature['polygon'] = (shape(feature['geometry'])) def find_community_area(point): closest_point_distance = float('inf') closest_ward = None # check each polygon to see if it contains the point for feature in chicago_community_areas['features']: polygon = feature['polygon'] # Return the name associated with this polygon if polygon.contains(point): return feature['properties']['area_numbe'] # If we get here, we couldn't find the point # Get the closest one for feature in chicago_community_areas['features']: polygon = shape(feature['geometry']) # Returns a tuple, we only want the first value closest_point, p2 = nearest_points(polygon, point) point_distance = closest_point.distance(point) if point_distance &lt; closest_point_distance: closest_point_distance = point_distance closest_ward = feature['properties']['area_numbe'] return closest_ward # %%timeit community_areas = [] for index, row in crime_df.iterrows(): community_area = find_community_area(row["point"]) community_areas.append(community_area) # 1 loop, best of 3: 503 ms per loop </code></pre> <hr> <p><em>Note</em>: These are only for additional information, they are not for review.</p> <p>At first I tried a couple of ways to solve this, however they were super slow. Whilst my current code is better I'm still not happy with the performance.</p> <pre class="lang-py prettyprint-override"><code>%%timeit crime_df['community'] = crime_df.apply(lambda x:find_community_area(Point(x.Longitude, x.Latitude)), axis=1) 1 loop, best of 3: 1.62 s per loop </code></pre> <pre class="lang-py prettyprint-override"><code>%%timeit community_areas = [] for index, row in crime_df.iterrows(): community_area = find_community_area(Point(row["Longitude"],row["Latitude"])) community_areas.append(community_area) 1 loop, best of 3: 1.64 s per loop </code></pre> <p>Additionally when trying to improve performance I ran into some errors. The above code <em>works as intended</em>, only these endeavors failed.<br> I tried to vectorize the process:</p> <pre class="lang-py prettyprint-override"><code>%%timeit # Vectorized implementation crime_df['community'] = find_community_area(crime_df['point'].values) 16 def _validate(self, ob, stop_prepared=False): ---&gt; 17 if ob is None or ob._geom is None: 18 raise ValueError("Null geometry supports no operations") 19 if stop_prepared and hasattr(ob, 'prepared'): AttributeError: 'numpy.ndarray' object has no attribute '_geom' </code></pre> <p>I tried using <code>GeoDataFrame</code>:</p> <pre class="lang-py prettyprint-override"><code>gdf = geopandas.GeoDataFrame(crime_df, geometry = geopandas.points_from_xy(crime_df.Longitude, crime_df.Latitude)) crime_df['community'] = find_community_area(gdf.geometry.values) AttributeError: 'GeometryArray' object has no attribute '_geom' </code></pre> <hr> <p>Can the performance of my code be improved?</p> <p><strong>Format of data</strong></p> <p><a href="https://data.cityofchicago.org/Public-Safety/Crimes-Map/dfnk-7re6" rel="nofollow noreferrer">Source Data</a> (warning, very very large, approx 7 million samples):</p> <pre class="lang-none prettyprint-override"><code>Date Block IUCR Primary Type Description Location Description Arrest Domestic Beat Ward FBI Code X Coordinate Y Coordinate Year Latitude Longitude Location 6/19/2015 13:00 029XX W DEVON AVE 810 THEFT OVER $500 PARKING LOT/GARAGE(NON.RESID.) FALSE FALSE 2412 50 6 1155359 1942303 2015 41.99748655 -87.70384887 (41.997486552, -87.70384887) 6/19/2015 16:55 011XX W PRATT BLVD 460 BATTERY SIMPLE RESIDENCE PORCH/HALLWAY FALSE FALSE 2432 49 08B 1167327 1945336 2015 42.00555929 -87.65973545 (42.005559291, -87.659735453) 6/18/2015 18:30 064XX S HONORE ST 820 THEFT $500 AND UNDER RESIDENCE FALSE TRUE 726 15 6 1165122 1861901 2015 41.77665465 -87.67022008 (41.776654652, -87.670220081) </code></pre> <p><a href="https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Community-Areas-current-/cauq-8yn6" rel="nofollow noreferrer">Community Area Data</a>:</p> <p>Shared gist <a href="https://gist.github.com/TomSelleck/73da640de2b9dbce9b6a878a7c8834e3" rel="nofollow noreferrer">here</a> as it's very large.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:43:28.083", "Id": "471515", "Score": "1", "body": "Could you show some examples of the data that you are processing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:48:46.470", "Id": "471516", "Score": "0", "body": "@Reinderien IMO your edit only harms the readability of the post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:54:52.837", "Id": "471517", "Score": "0", "body": "@Reinderien Updated post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:59:36.367", "Id": "471520", "Score": "0", "body": "I disagree, considering some of the highlighted text is not actually code at all. But, shrug." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:04:54.203", "Id": "471522", "Score": "0", "body": "@Reinderien I fail to see how the benefit of not highlighting a couple of numbers outweigh the benefit of highlighting the _Python code_. The code is illegible to me without the syntax highlighting, but some pretty numbers don't matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:10:03.977", "Id": "471532", "Score": "0", "body": "Why has the community area data been shared on gist when it is also hosted by the City of Chicago? Did you process it somehow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:28:01.230", "Id": "471538", "Score": "0", "body": "Nope no processing, just wanted to share the raw json without forcing you to download it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:32:56.140", "Id": "471539", "Score": "0", "body": "Looking at the website, they offer exports in CSV and JSON, etc., but none of those resemble the sample you have shown, which seems to be missing any delimiters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:39:27.867", "Id": "471540", "Score": "0", "body": "That sample copied into the editor as tab-delimited, it should be comma delimited" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T02:12:44.463", "Id": "471590", "Score": "0", "body": "How fast does it need to be? 7M records in 500ms doesn't leave much room for improvement. Each lookup is independent, so you could try the multiprocessing library to take advantage of multiple cores. Can you do the calculations once and save the results to a local database/file? Then periodically add new crimes to the local file/database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T09:03:35.027", "Id": "471606", "Score": "0", "body": "@RootTwo It's 500ms a loop, not for 7M records :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T21:38:01.900", "Id": "471703", "Score": "0", "body": "@TomSelleck The `%%timeit` magic times execution of the entire cell, so at the end of the first code block, it looks like it times the entire for-loop, which includes processing all of `crime_df`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T10:10:12.600", "Id": "471758", "Score": "0", "body": "Ah, my mistake - thanks. The times I have are for a tiny subset of the whole dataset so the question still stands" } ]
[ { "body": "<p>I think what you need is to replace this:</p>\n\n<pre><code> for feature in chicago_community_areas['features']:\n polygon = feature['polygon']\n\n # Return the name associated with this polygon\n if polygon.contains(point):\n return feature['properties']['area_numbe']\n</code></pre>\n\n<p>with a fundamentally different algorithm. The loop above is O(n), which is - as you have noticed - impractical for the quantity of data you need to process. You need a <a href=\"https://en.wikipedia.org/wiki/Spatial_database#Spatial_index\" rel=\"nofollow noreferrer\">spatial index</a> to reduce the time complexity of this lookup to be sublinear. For Python in particular, there is <a href=\"https://geopandas.org/\" rel=\"nofollow noreferrer\">GeoPandas</a>, although I have not tried it so cannot speak to its quality or application to your task. This will require some research on your behalf, and I'm afraid that there is no easy answer other than to do a bunch of reading and experimentation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T19:46:53.947", "Id": "240524", "ParentId": "240389", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T12:33:14.547", "Id": "240389", "Score": "3", "Tags": [ "python", "performance", "time-limit-exceeded", "pandas", "geospatial" ], "Title": "Checking which polygon a set of coordinates lie inside" }
240389
<p>I am learning Python, and this is one of the program assignments I have to do.</p> <p>I need to write code to prompt user to enter Fibonacci numbers continuously until it's greater than 50. If everything correct, screen show <code>'Well done'</code>, otherwise <code>'Try again'</code>.</p> <p>While my code is working correctly, I would like to know how I should write it better.</p> <p>My code:</p> <pre><code># Init variables t = 0 prev_2 = 1 prev_1 = 0 run = 1 # Run while loop to prompt user enter Fibonacci number while (run): text = input('Enter the next Fibonacci number &gt;') if (text.isdigit()): t = int(text) if t == prev_2 + prev_1: if t &lt;= 50: prev_2 = prev_1 prev_1 = t else: print('Well done') run = 0 else: print('Try again') run = 0 else: print('Try again') run = 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T11:47:08.277", "Id": "471615", "Score": "0", "body": "Great job. I think your code would benefit from naming variables more clearly, to a point where it should be possible to understand what it is without having to look at the code. t have already been mentioned in the answers. I would say that prev_1 is the last Fibonacci number, and prev_2 is the one before that, but according to the code it's the other way around. Naming them fibonacci_last and fibonacci_second_to_last, or prev_highest and prev_lowest or something similar makes it clearer how they are used." } ]
[ { "body": "<p>A few minor tips on making the code more compact:</p>\n\n<ol>\n<li><p>Remove unneeded variables/initializations. In particular your <code>t</code> variable doesn't need to be initialized outside the loop since its value is always set within the loop before it's used.</p></li>\n<li><p>The <code>run</code> variable can also be eliminated; make the loop <code>while True</code> and use a <code>break</code> to escape it when you're done.</p></li>\n<li><p>Instead of doing <code>text.isdigit()</code> just do the <code>int</code> conversion inside a <code>try</code> block.</p></li>\n<li><p>Combine your two \"Try again\" cases into a single block of code rather than repeating yourself.</p></li>\n</ol>\n\n<p>With those changes the code looks like:</p>\n\n<pre><code># Init previous two values of Fibonacci sequence\nprev_2 = 1\nprev_1 = 0\n\n# Run while loop to prompt user enter Fibonacci number\nwhile True:\n try:\n t = int(input('Enter the next Fibonacci number &gt;'))\n if t != prev_2 + prev_1:\n raise ValueError('not the next Fibonacci number!')\n if t &gt; 50:\n print('Well done')\n break\n # move to next value in the sequence\n prev_2, prev_1 = prev_1, t\n except ValueError:\n print('Try again')\n break\n</code></pre>\n\n<p>A larger tip on improving the code would be to separate the two distinct tasks the code is doing: computing the Fibonacci sequence up to 50, and quizzing the user on it. Here's how I might write that:</p>\n\n<pre><code># Init Fibonacci sequence up to first value past 50 (shfifty-five)\nfib = [0, 1]\nwhile fib[-1] &lt;= 50:\n fib.append(fib[-2] + fib[-1])\n\n# Prompt the user for all those values (after the initial 0, 1)\nfor n in fib[2:]:\n try:\n if int(input('Enter the next Fibonacci number &gt;')) != n:\n raise ValueError('not the next Fibonacci number!')\n except ValueError:\n print('Try again')\n break\nelse:\n print('Well done')\n</code></pre>\n\n<p>Now the code is in two smaller parts that are each a lot simpler than the previous version -- the first few lines compute the Fibonacci sequence in a very straightforward way, and the rest of the code simply iterates over the sequence and checks the input against it.</p>\n\n<p>In a larger project you'd probably take these two \"chunks\" of code and define them as functions (you'd have one function that generates the sequence and another that handles the quizzing), but even within a function it's valuable to think about how you can break a problem does into distinct simple parts (and once you've done that, the next step of refactoring it into smaller functions becomes easy).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T04:50:59.837", "Id": "471593", "Score": "0", "body": "Thank you very much for your help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:34:37.080", "Id": "240395", "ParentId": "240391", "Score": "6" } }, { "body": "<p>First, <code>run</code> should be a Boolean value (<code>True</code> or <code>False</code>). <code>1</code> and <code>0</code> work, but they're far less clear. Note how much more sense this makes:</p>\n\n<pre><code>. . .\nrun = True\n\nwhile (run):\n text = input('Enter the next Fibonacci number &gt;')\n if (text.isdigit()):\n t = int(text)\n if t == prev_2 + prev_1:\n if t &lt;= 50:\n prev_2 = prev_1\n prev_1 = t\n else:\n print('Well done')\n run = False\n else:\n print('Try again')\n run = False\n else:\n print('Try again')\n run = False\n</code></pre>\n\n<hr>\n\n<p>Instead of using a <code>run</code> flag though to exit the loop, I think it would be a lot cleaner to just <code>break</code> when you want to leave:</p>\n\n<pre><code>while (True):\n text = input('Enter the next Fibonacci number &gt;')\n if (text.isdigit()):\n t = int(text)\n if t == prev_2 + prev_1:\n if t &lt;= 50:\n prev_2 = prev_1\n prev_1 = t\n else:\n print('Well done')\n break\n else:\n print('Try again')\n break\n else:\n print('Try again')\n break\n</code></pre>\n\n<hr>\n\n<p>Instead of doing a <code>isdigit</code> check, you can just catch the <code>ValueError</code> that <code>int</code> raises:</p>\n\n<pre><code>while (True):\n text = input('Enter the next Fibonacci number &gt;')\n try:\n t = int(text)\n except ValueError:\n print('Try again')\n break\n\n if t == prev_2 + prev_1:\n if t &lt;= 50:\n prev_2 = prev_1\n prev_1 = t\n else:\n print('Well done')\n break\n else:\n print('Try again')\n break\n</code></pre>\n\n<p>This goes with Python's \"It's better to ask for forgiveness than permission\" philosophy.</p>\n\n<hr>\n\n<p>Some other things:</p>\n\n<ul>\n<li><p>Don't put parenthesis around the condition of <code>while</code> and <code>if</code> statements unless you <em>really</em> feel that they help readability in a particular case.</p></li>\n<li><p>You don't need to have <code>t</code> assigned outside of the loop. I'd also give <code>t</code> a better name like <code>user_input</code>:</p>\n\n<pre><code>prev_2 = 1\nprev_1 = 0\n\n# Run while loop to prompt user enter Fibonacci number\nwhile True:\n text = input('Enter the next Fibonacci number &gt;')\n try:\n user_input = int(text)\n except ValueError:\n print('Try again')\n break\n\n if user_input == prev_2 + prev_1:\n if user_input &lt;= 50:\n prev_2 = prev_1\n prev_1 = user_input\n else:\n print('Well done')\n break\n else:\n print('Try again')\n break\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T04:49:04.887", "Id": "471592", "Score": "0", "body": "Thank you very much for your help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:37:42.077", "Id": "240396", "ParentId": "240391", "Score": "5" } }, { "body": "<p>Welcome to CodeReview! This is a great first question.</p>\n\n<h2>Breaking out of a loop</h2>\n\n<p>You don't necessarily need to have a condition at the declaration of the loop, like <code>while (run):</code>. Instead, </p>\n\n<pre><code># Run while loop to prompt user enter Fibonacci number\nwhile True:\n text = input('Enter the next Fibonacci number &gt;')\n if text.isdigit():\n t = int(text)\n if t == prev_2 + prev_1:\n if t &lt;= 50:\n prev_2 = prev_1\n prev_1 = t\n else:\n print('Well done')\n break\n else:\n print('Try again')\n break\n else:\n print('Try again')\n break\n</code></pre>\n\n<p>Two other answers just popped up so I will leave this here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T04:51:56.777", "Id": "471594", "Score": "0", "body": "Thank you very much for your help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T19:00:39.807", "Id": "471682", "Score": "1", "body": "This has two problems. prev_2 and prev_1 are not inititalized. Two of the break statements should be continue instead (only goal reached should end the program). At this moment, all answers recommending while True: seem to have the 'break instead of continue' problem," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T20:24:49.540", "Id": "471700", "Score": "1", "body": "It may be that the code doesn't do the right thing, but the right thing wasn't the direct intent; the intent was to replicate what the OP was doing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:38:26.670", "Id": "240398", "ParentId": "240391", "Score": "4" } }, { "body": "<p>The 3 answers already given are great. I'd just like to point out a minor bug with the original code not mentioned in these 3 answers. </p>\n\n<p>The <code>str.isdigit()</code> function can yield false positives. If the user enters <code>1²₃</code>, the <code>isdigit()</code> method will return <code>True</code> because all the characters are Unicode digits, but <code>int(...)</code> will raise an exception because the characters are not all <strong>decimal</strong> digits. </p>\n\n<p>The function you wanted was <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=isdecimal#str.isdecimal\" rel=\"noreferrer\"><code>str.isdecimal()</code></a>.</p>\n\n<pre><code>&gt;&gt;&gt; text = \"1²₃\"\n&gt;&gt;&gt; text.isdigit()\nTrue\n&gt;&gt;&gt; int(text)\nTraceback (most recent call last):\n module __main__ line 141\n traceback.print_exc()\n module &lt;module&gt; line 1\n int(text)\nValueError: invalid literal for int() with base 10: '1²₃'\n&gt;&gt;&gt; text.isdecimal()\nFalse\n&gt;&gt;&gt; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T04:52:11.213", "Id": "471595", "Score": "0", "body": "Thank you very much for your help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T10:26:24.447", "Id": "471611", "Score": "1", "body": "\"Easier to ask for forgiveness than permission\" is a common Python coding style. In this instance you would write `try: int(text) except ValueError: ...`. It could have prevented this bug because it doesn't require the writer to know the circumstances under which int() will fail." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:06:37.913", "Id": "471664", "Score": "1", "body": "@kangalioo Two of the other three answers had already more than adequately covered the `try: int(text) except ValueError:` \"_easier to ask forgiveness than permission_\" approach. I was just pointing out an actual bug in the OP's \"_ask permission_\" code that had not been noticed or mentioned. At some point, the OP may need the `.isdecimal()` function for some other code, and may remember this answer and not erroneously use `.isdigit()`. Or they might actually need the broader `.isdigit()` functionality and remember it already exists. Know how to use all the tools in the toolbox." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T20:43:56.167", "Id": "471701", "Score": "0", "body": "True, sorry. I suppose I should have read the other answers before making that comment" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:46:36.700", "Id": "240399", "ParentId": "240391", "Score": "6" } }, { "body": "<p>Others have given many great suggestions on the code style, but I'd like to point out that your code's behavior does not exactly match your description of what it should do. You said:</p>\n\n<blockquote>\n <p>I need to write code to prompt user to enter Fibonacci numbers\n continuously until it's greater than 50. If everything correct, screen\n show 'Well done', otherwise 'Try again'.</p>\n</blockquote>\n\n<p>Based on this description, it sounds like the code should be prompting for numbers continuously, even if they give you a wrong answer, until they give you a number greater than 50. Only then would you reveal whether they had gotten it correct or not.</p>\n\n<p>I didn't see anyone else point this out, and the hardest part of programming is understanding exactly what your program should do. I may be understanding the description wrong, of course, but I would double-check that your program meets the problem specification.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T17:22:59.377", "Id": "471908", "Score": "0", "body": "Hi, I mean the software prompt the user input the Fibonacci number in the series. If the input number is correct, software will prompt user to enter the next one. Until it greater than 50 and print 'Well done'. If input number is wrong, software will print 'Try again' and quit." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:18:27.597", "Id": "240513", "ParentId": "240391", "Score": "0" } } ]
{ "AcceptedAnswerId": "240396", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T13:56:24.763", "Id": "240391", "Score": "4", "Tags": [ "python", "beginner", "fibonacci-sequence" ], "Title": "Asking for Fibonacci numbers, up till 50" }
240391
<p>I am building Twitter. People can follow each other, and hence I have 2 tables, <code>users</code> and <code>followers</code>. </p> <p>My current problem is that I feel like I'm doing too many <code>SELECTs</code> before doing anything useful. Is it common to have a <code>SELECT</code> on users to find the current user each time? </p> <h1>I have:</h1> <p><strong>models.py</strong></p> <pre><code>class User(Base): """Table schema containing profiles.""" __tablename__ = "users" id = Column(String, primary_key=True) username = Column(String) created_date = Column(DateTime) following = relationship('User', secondary='followers', primaryjoin='User.id==Follower.user_id', secondaryjoin='Follower.follows_user_id==User.id' ) followers = relationship( 'User', secondary='followers', primaryjoin='User.id==Follower.follows_user_id', secondaryjoin='User.id==Follower.user_id' ) class Follower(Base): __tablename__ = 'followers' user_id = Column(String, ForeignKey('users.id'), primary_key=True) follows_user_id = Column(String, ForeignKey('users.id'), primary_key=True) created_date = Column(DateTime) updated_date = Column(DateTime) active = Column(Boolean, default=True) user_creating_following = relationship("User", primaryjoin="Follower.user_id==User.id") user_being_followed = relationship("User", primaryjoin="Follower.follows_user_id==User.id") </code></pre> <p>To follow a user, I created an endpoint, which ends up calling <code>follow_user()</code> function.</p> <pre><code>def follow_user(session, user_id, username_to_follow): # first check if user already follows the person trying to follow user_to_follow = session.query(User).filter(User.username==username_to_follow).first() if not user_to_follow: raise BadRequest("The user you are trying to follow doesnt exist") # Check not performing action on yourself if user_to_follow.id == user_id: # Can not perform this action on yourself raise BadRequest("You cannot follow yourself") follow = session.query(Follower).filter( and_( Follower.user_id==user_id, Follower.follows_user_id==user_to_follow.id ) ).first() if follow: # Update the existing follow record follow.active = True follow.updated_date = datetime.now() else: # if the follow doesn't already exist, create it follow = Follower( user_id=user_id, follows_user_id=user_to_follow.id, created_date=datetime.now(), updated_date=datetime.now(), active=True ) session.add(follow) session.commit() return </code></pre> <p>I wish I could write something like:</p> <pre><code>follow = session.query(Follower)\ .filter(Follower.user_creating_following.id==user_id)\ .filter(Follower.user_receiving_following.username==username_to_follow) </code></pre> <p>This would allow me to avoid the first query on the <code>User</code> altogether, but returns the error:</p> <pre><code>AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Follower.user_creating_following has an attribute 'id' </code></pre> <p>Any other input is greatly appreciated. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:23:56.757", "Id": "471509", "Score": "1", "body": "_I am building Twitter_ - I have bad news - someone may have beaten you to it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T14:16:04.197", "Id": "240392", "Score": "1", "Tags": [ "python", "sqlalchemy" ], "Title": "Python: SQL Alchemy. Managing a many-to-many self related table" }
240392
<p>I wrote a simplified pig latin translator in APL and I would like some feedback on it, as I am not sure my implementation is neat enough.</p> <p>The simplified pig latin translation follows the following rules, where only <code>'aeiouAEIOU'</code> are considered vowels:</p> <ul> <li>one-letter words have <code>'way'</code> appended to them; e.g. <code>'I'</code> becomes <code>'Iway'</code></li> <li>2 or more letter words starting with a vowel have <code>'ay'</code> appended to them; e.g. <code>'awesome'</code> becomes <code>'awesomeay'</code></li> <li>2 or more letter words starting with a consonant have the consonants in front of the first vowel moved to the back, and then <code>'ay'</code> is appended; e.g. <code>'cool'</code> becomes <code>'oolcay'</code></li> </ul> <p>The problem statement (<a href="https://www.dyalogaplcompetition.com/?goto=P2" rel="nofollow noreferrer">problem 3 of the second easy problem set</a>) specified that input might be a scalar (i.e. a single character) or a (possibly empty) character vector.</p> <p>This is the code I wrote:</p> <pre><code>PigLatin ← { ⍝ Monadic function expecting character scalar or character vector and returning character vector. ⍝ Translates an English sentence into Pig lating. ⍝ e.g. 'I always run fast' becomes 'Iway alwaysay unray astfay'. vowels ← 'aeiouAEIOU' words ← ' ' (≠⊆⊢) ,⍵ ⍝ Rotate all words until a vowel is at the front. rotated ← {⍵ ⌽⍨ ¯1+⊃⍸ ⍵∊vowels}¨ words ⍝ Append a 'w' to words of length 1. suffixed ← (,∘'w')¨@(1∘=≢¨) rotated ⍝ Append 'ay ' to all words, join and drop last ' '. ¯1↓∊ (,∘'ay ')¨ suffixed } </code></pre> <h3>Questions</h3> <ul> <li><p>The basic idea is that I split the input sentence into words, apply the rules to each word and then join them together; this seems sensible, right? This feels like a very standard algorithm but I don't know if APL is suitable for another type of approach.</p></li> <li><p>Following the idea outlined above, my first version had this final line <code>∊ {⍺' '⍵}/ (,∘'ay')¨ suffixed</code> instead of the current <code>¯1↓ ∊(,∘'ay ')¨ suffixed</code>; but this meant my code didn't work for empty inputs <code>''</code> because it tried running <code>{⍺' '⍵}/</code> on an empty vector and raised a DOMAIN ERROR. My workaround for this was appending <code>'ay '</code> to every word, instead of just <code>'ay'</code> and then dropping the final extra <code>' '</code> with <code>¯1↓</code>;</p> <ul> <li>Is this a good way of handling the edge case <code>''</code>?</li> <li>Would it be better if I had a dfn guard for the <code>''</code> case?</li> <li>Would you handle it in a different way?</li> </ul></li> <li><p>Is <code>≠⊆⊢</code> an idiom in APL to split the right vector on the left arguments? It even shows in the tooltip for the Partition <code>⊆</code> glyph.</p></li> <li><p>Any further comments, suggestions, etc that don't necessarily address my questions are also welcome.</p></li> </ul>
[]
[ { "body": "<h2>Overall</h2>\n\n<p>Your approach is fine, and your code (including <code>≠⊆⊢</code>) is fairly idiomatic. Handling the edge case by always appending a space and dropping it at the end is standard procedure, so no, you don't need a <a href=\"https://stackoverflow.com/a/11227902/5306507\">branch</a> here.</p>\n\n<h3>Split up your code in sections</h3>\n\n<p>You begin with setting up a couple of constants. Consider inserting a blank line to gently separate these from the main code.</p>\n\n<h3>Inline comments</h3>\n\n<p>Well-written APL code tends to have short lines, so there's generally enough space to include comments. This allows a simple hierarchy of comments:</p>\n\n<ul>\n<li>Full-line comments for introductions to sections.</li>\n<li>End-of-line comments for code explanations.</li>\n</ul>\n\n<h3>Consistency</h3>\n\n<p>You use intermediary variables for rotating and appending \"w\" but not for appending \"ay \".</p>\n\n<h3>Array approach to conditional concatenation</h3>\n\n<p><code>(,∘'w')¨@(1∘=≢¨)</code> does two loops:</p>\n\n<ol>\n<li><code>(1∘=≢¨)</code> (which could be <code>(1=≢¨)</code> too) to determine which words need appending.</li>\n<li><code>(,∘'w')¨</code> (which could be <code>,∘'w'¨</code> or <code>'w',¨⍨</code> too) to do the appending.</li>\n</ol>\n\n<p>A more holistic array approach is to append <em>to every</em> word, and instead modify <em>what</em> is appended. That is, <em>collapse the appendix to shape 0 for words of length different from 1</em>. Rephrased, this becomes <em>keep the appendix as-is for words of length equal to 1</em>, or <code>'w'/⍨1=≢</code>. It becomes a <em>\"conditionally\" append</em> function in the form of <code>⊢,'w'/⍨1=≢</code>, which you could then apply to each with <code>(⊢,'w'/⍨1=≢)¨</code>. However, you might want to…</p>\n\n<h3>Reduce ¨pepper¨</h3>\n\n<p>Some APLers call code with too many <code>¨</code>s \"too peppered\" referring to the many tiny dots in foods that contain lots of black pepper. You may want to consider fusing the loops by defining the constituent transformation functions and applying them together in a single loop. Appropriate naming of the functions allows shortening the comments to become clarifications of the names, which can even make a comment obsolete.</p>\n\n<h2>Revised code</h2>\n\n<pre><code>PigLatin←{\n ⍝ Monadic function expecting character scalar or character vector and returning character vector.\n ⍝ Translates an English sentence into Pig Latin.\n ⍝ e.g. 'I always run fast' becomes 'Iway alwaysay unray astfay'.\n\n vowels ← 'aeiouAEIOU'\n Words ← ' '(≠⊆⊢),\n\n Rotate ← {⍵ ⌽⍨ ¯1+⊃⍸ ⍵∊vowels} ⍝ all words until a vowel is at the front\n Add_w ← ⊢,'w'/⍨1=≢ ⍝ if word has length 1\n Add_ay ← ,∘'ay '\n\n ¯1↓∊ Add_ay∘Add_w∘Rotate¨ Words ⍵\n}\n</code></pre>\n\n<h2>Other approaches</h2>\n\n<p>Writing APL is fun<a href=\"https://chat.stackexchange.com/search?q=apl+is+fun&amp;user=&amp;room=52405\">*</a>, so APLers tend to write everything from scratch every time, instead of using the tools at hand. In this case, Perl-style regular expressions might be a help.</p>\n\n<h3>Using regex to process words</h3>\n\n<p>It is easy to apply a function to each word using <code>'\\w+' ⎕R {MyFn ⍵.Match}</code>:</p>\n\n<pre><code>PigLatinWord←{\n vowels ← 'aeiouAEIOU'\n\n Rotate ← {⍵ ⌽⍨ ¯1+⊃⍸ ⍵∊vowels}\n W ← ⊢,'w'/⍨1=≢\n Ay ← ,∘'ay'\n\n Ay W Rotate ⍵\n}\nPigLatinRegex ← '\\w+' ⎕R {PigLatinWord ⍵.Match}\n</code></pre>\n\n<p>The <code>\\w+</code> pattern matches runs of <strong>w</strong>ord characters.</p>\n\n<p>If this was a common thing, we could define a utility operator that applies a text transformation on words:</p>\n\n<pre><code>_OnWords ← {'\\w+' ⎕R (⍺⍺{⍺⍺ ⍵.Match}) ⍵}\nPigLatinOnWords ← PigLatinWord _OnWords\n</code></pre>\n\n<p>An alternative coding which avoids passing the operand multiple times:</p>\n\n<pre><code>_OnWords ← {'\\w+' ⎕R (⍺⍺⍎∘'Match') ⍵}\nPigLatinOnWords ← PigLatinWord _OnWords\n</code></pre>\n\n<h3>Doing the entire job with regexes</h3>\n\n<p>That said, <code>⎕R</code> actually has a fancy feature that allows running multiple search patterns in parallel (for every starting character the patterns are tested in order) each with their own substitution pattern. This makes it easy to catch and process edge cases before the main transformations have a chance to kick in.</p>\n\n<pre><code>PigLatinRegexes ← '\\w\\b' '([^aeiou ]*)(\\w+)' ⎕R '&amp;way' '\\2\\1ay' ⍠1\n</code></pre>\n\n<p>Here, we have two patterns:</p>\n\n<ol>\n<li><code>\\w\\b</code> <strong>w</strong>ord character, word <strong>b</strong>oundary: a 1-character word.</li>\n<li><code>([^aeiou ]*)(\\w+)</code> any consonants (group 1), <strong>w</strong>ord characters (group 2): any other word</li>\n</ol>\n\n<p>And the corresponding substitution patterns:</p>\n\n<ol>\n<li><code>&amp;way</code> the match followed by \"way\"</li>\n<li><code>\\2\\1ay</code> group 2, group 1 (which can be empty), \"ay\"</li>\n</ol>\n\n<p>Finally, <code>⍠1</code> makes the derived function ignore case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:30:41.543", "Id": "471569", "Score": "0", "body": "Adám, in your array approach to conditional concatenation, the 3 final snippets of code all have an extra `,` and a missing rho, I believe!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:34:46.453", "Id": "471570", "Score": "0", "body": "@RGS Indeed. I've now made it `/` instead of `⍴` too as that is more general; it works for vector appendices too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:44:14.717", "Id": "471572", "Score": "0", "body": "i.e. with `/` I could append `'www'` or any other character vector, right? That was a really clever hint!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:44:40.407", "Id": "471573", "Score": "0", "body": "@RGS That's correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T22:31:27.647", "Id": "472236", "Score": "0", "body": "In the subsection `Using regex to process words` I think you missed a `+` in the regex when you say _\"It is easy to apply a function to each word using `'\\w' ⎕R {MyFn ⍵.Match}`\"_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T21:08:50.653", "Id": "472324", "Score": "0", "body": "@RGS Fixed.Thanks." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T21:29:02.947", "Id": "240417", "ParentId": "240397", "Score": "3" } }, { "body": "<h2>Think about edge cases</h2>\n\n<p>Although the original problem statement doesn't mention it (nor the test cases provided), I can think of at least two kinds of edge cases:</p>\n\n<ul>\n<li>Handling extraneous spaces (leading spaces, trailing spaces, or multiple spaces between words, e.g. <code>__I___like__blanks___</code>)</li>\n<li>Handling capitalization (e.g. <code>Creep -&gt; eepCray</code> or <code>Eepcray</code>?)</li>\n</ul>\n\n<p>Notably, your solution does not preserve spaces (except for single space between words) while <a href=\"https://codereview.stackexchange.com/a/240417/182436\">Adám's regex solution</a> preserves all spaces. How would you preserve spaces without regex? There are multiple ways to chunk a string into words, preserving spaces:</p>\n\n<ul>\n<li>Allow multiple leading blanks on each word: <code>'__I' '___like' '__blanks' '___'</code>. Alternatively, allow multiple trailing blanks: <code>'__' 'I___' 'like__' 'blanks___'</code>.</li>\n<li>Allow single leading (resp. trailing) blank on each word: <code>'_' '_I' '_' '_' '_like' ...</code>.</li>\n<li>Allow blanks to form their own chunks: <code>'__' 'I' '___' 'like' ...</code>. See <a href=\"http://dfns.dyalog.com/n_words.htm\" rel=\"nofollow noreferrer\"><code>dfns.words</code></a>.</li>\n</ul>\n\n<p>Each choice can make some parts easy but some other parts harder. Be sure to explore various possibilities and pick the one you like the most.</p>\n\n<h2>Nitpicking: Avoid unnecessary <code>⍸</code></h2>\n\n<p>In your code, <code>¯1+⊃⍸</code> is essentially counting leading zeros on a boolean array. But the monadic <code>⍸</code> is pretty heavy, and requires <code>⎕IO</code> adjustment. <a href=\"https://aplcart.info/?q=leading%20zero#\" rel=\"nofollow noreferrer\">APLcart</a> gives the entry <code>(⊥⍨0=⌽)Bv</code> for the query \"leading zero\". By unpacking the train, you can use boolean negation <code>~</code> instead of <code>0=</code>:</p>\n\n<pre><code>⍝ Instead of this\n¯1+⊃⍸ ⍵∊vowels\n⍝ Do this\n⊥⍨⌽ ~⍵∊vowels\n</code></pre>\n\n<p>Note that <code>⊥⍨</code> on a boolean vector is a (very clever) idiom for \"count trailing ones\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T18:35:11.063", "Id": "471677", "Score": "0", "body": "Nice use of the APL Cart! I like the ⊥⍨ :D" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T01:42:04.997", "Id": "240425", "ParentId": "240397", "Score": "3" } } ]
{ "AcceptedAnswerId": "240417", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T15:38:16.593", "Id": "240397", "Score": "2", "Tags": [ "natural-language-processing", "pig-latin", "apl" ], "Title": "Simplified Pig Latin translator in APL" }
240397
<p>I am working on a basic <strong><a href="https://github.com/Ajax30/lightblog" rel="nofollow noreferrer">blog application</a></strong> with Codeigniter 3.1.8 and Bootstrap 4.</p> <p>The application has users (authors) and posts (articles). Every article:</p> <ul> <li>has an author,</li> <li>belongs to a category,</li> <li>has a default (generic) main image that is displayed unless the author assigns a specific image to it.</li> </ul> <p>The structure of the posts table can be seen below:</p> <p><a href="https://i.stack.imgur.com/sbiZY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sbiZY.png" alt="enter image description here"></a></p> <p>I am interested in evaluating the quality of the code I have written for the <em>Create</em>, <em>Update</em> and <em>Delete</em> operations. Also, In the post image management.</p> <p>In the Post controller I have:</p> <pre><code>public function create() { // Only logged in users can create posts if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $data = $this-&gt;get_data(); $data['tagline'] = "Add New Post"; if ($data['categories']) { foreach ($data['categories'] as &amp;$category) { $category-&gt;posts_count = $this-&gt;Posts_model-&gt;count_posts_in_category($category-&gt;id); } } $this-&gt;form_validation-&gt;set_rules('title', 'Title', 'required'); $this-&gt;form_validation-&gt;set_rules('desc', 'Short description', 'required'); $this-&gt;form_validation-&gt;set_rules('body', 'Body', 'required'); $this-&gt;form_validation-&gt;set_error_delimiters('&lt;p class="error-message"&gt;', '&lt;/p&gt;'); if($this-&gt;form_validation-&gt;run() === FALSE){ $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('dashboard/create-post'); $this-&gt;load-&gt;view('partials/footer'); } else { // Create slug (from title) $slug = url_title(convert_accented_characters($this-&gt;input-&gt;post('title')), 'dash', TRUE); $slugcount = $this-&gt;Posts_model-&gt;slug_count($slug, null); if ($slugcount &gt; 0) { $slug = $slug."-".$slugcount; } // Upload image $config['upload_path'] = './assets/img/posts'; $config['allowed_types'] = 'jpg|jpeg|png'; $config['max_size'] = '2048'; $this-&gt;load-&gt;library('upload', $config); if(!$this-&gt;upload-&gt;do_upload()){ $errors = array('error' =&gt; $this-&gt;upload-&gt;display_errors()); // Dysplay upload validation errors // only if a file is uploaded and there are errors if (empty($_FILES['userfile']['name'])) { $errors = []; } if (empty($errors)) { $post_image = 'default.jpg'; } else { $data['upload_errors'] = $errors; } } else { $data = array('upload_data' =&gt; $this-&gt;upload-&gt;data()); $post_image = $_FILES['userfile']['name']; } if (empty($errors)) { $this-&gt;Posts_model-&gt;create_post($post_image, $slug); $this-&gt;session-&gt;set_flashdata('post_created', 'Your post has been created'); redirect('/'); } else { $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('dashboard/create-post'); $this-&gt;load-&gt;view('partials/footer'); } } } public function edit($id) { // Only logged in users can edit posts if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $data = $this-&gt;get_data(); $data['post'] = $this-&gt;Posts_model-&gt;get_post($id); if (($this-&gt;session-&gt;userdata('user_id') == $data['post']-&gt;author_id) || $this-&gt;session-&gt;userdata('user_is_admin')) { $data['tagline'] = 'Edit the post "' . $data['post']-&gt;title . '"'; $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('dashboard/edit-post'); $this-&gt;load-&gt;view('partials/footer'); } else { /* If the current user is not the author of the post do not alow edit */ redirect('/' . $id); } } public function update() { // Form data validation rules $this-&gt;form_validation-&gt;set_rules('title', 'Title', 'required', array('required' =&gt; 'The %s field can not be empty')); $this-&gt;form_validation-&gt;set_rules('desc', 'Short description', 'required', array('required' =&gt; 'The %s field can not be empty')); $this-&gt;form_validation-&gt;set_rules('body', 'Body', 'required', array('required' =&gt; 'The %s field can not be empty')); $this-&gt;form_validation-&gt;set_error_delimiters('&lt;p class="error-message"&gt;', '&lt;/p&gt;'); $id = $this-&gt;input-&gt;post('id'); // Update slug (from title) if ($this-&gt;form_validation-&gt;run()) { $slug = url_title(convert_accented_characters($this-&gt;input-&gt;post('title')), 'dash', TRUE); $slugcount = $this-&gt;Posts_model-&gt;slug_count($slug, $id); if ($slugcount &gt; 0) { $slug = $slug."-".$slugcount; } } else { $slug = $this-&gt;input-&gt;post('slug'); } // Upload image $config['upload_path'] = './assets/img/posts'; $config['allowed_types'] = 'jpg|jpeg|png'; $config['max_size'] = '2048'; $this-&gt;load-&gt;library('upload', $config); if (isset($_FILES['userfile']['name']) &amp;&amp; $_FILES['userfile']['name'] != null) { // Use name field in do_upload method if (!$this-&gt;upload-&gt;do_upload('userfile')) { $errors = array('error' =&gt; $this-&gt;upload-&gt;display_errors()); // Display upload validation errors // only if a file is uploaded and there are errors if (empty($_FILES['userfile']['name'])) { $errors = []; } if (!empty($errors)) { $data['upload_errors'] = $errors; } } else { $data = $this-&gt;upload-&gt;data(); $post_image = $data['raw_name'].$data[ 'file_ext']; } } else { $post_image = $this-&gt;input-&gt;post('postimage'); } if ($this-&gt;form_validation-&gt;run() &amp;&amp; empty($errors)) { $this-&gt;Posts_model-&gt;update_post($id, $post_image, $slug); $this-&gt;session-&gt;set_flashdata('post_updated', 'Your post has been updated'); redirect('/' . $slug); } else { $this-&gt;form_validation-&gt;run(); $this-&gt;session-&gt;set_flashdata('errors', validation_errors()); $this-&gt;session-&gt;set_flashdata('upload_errors', $errors); redirect('/dashboard/posts/edit/' . $slug); } } public function delete($slug) { // Only logged in users can delete posts if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $data['post'] = $this-&gt;Posts_model-&gt;get_post($slug); if (($this-&gt;session-&gt;userdata('user_id') == $data['post']-&gt;author_id) || $this-&gt;session-&gt;userdata('user_is_admin')) { $this-&gt;Posts_model-&gt;delete_post($slug); $this-&gt;session-&gt;set_flashdata('post_deleted', 'The post has been deleted'); redirect('/'); } else { /* If the current user is not the author of the post do not alow delete */ $this-&gt;session-&gt;set_flashdata('no_permission_to_delete_post', 'You are not authorized to delete this post'); redirect('/' . $slug); } } public function deleteimage($id) { $this-&gt;load-&gt;model('Posts_model'); $this-&gt;Posts_model-&gt;delete_post_image($id); redirect($this-&gt;agent-&gt;referrer()); } </code></pre> <p>In the Posts_model model:</p> <pre><code>// Create, post public function create_post($post_image, $slug) { $data = [ 'title' =&gt; $this-&gt;input-&gt;post('title'), 'slug' =&gt; $slug, 'description' =&gt; $this-&gt;input-&gt;post('desc'), 'content' =&gt; $this-&gt;input-&gt;post('body'), 'post_image' =&gt; $post_image, 'author_id' =&gt; $this-&gt;session-&gt;userdata('user_id'), 'cat_id' =&gt; $this-&gt;input-&gt;post('category'), 'created_at' =&gt; date('Y-m-d H:i:s') ]; return $this-&gt;db-&gt;insert('posts', $data); } // Update post public function update_post($id, $post_image, $slug) { $data = [ 'title' =&gt; $this-&gt;input-&gt;post('title'), 'slug' =&gt; $slug, 'description' =&gt; $this-&gt;input-&gt;post('desc'), 'content' =&gt; $this-&gt;input-&gt;post('body'), 'post_image' =&gt; $post_image, 'cat_id' =&gt; $this-&gt;input-&gt;post('category'), 'updated_at' =&gt; date('Y-m-d H:i:s') ]; $this-&gt;db-&gt;where('id', $id); return $this-&gt;db-&gt;update('posts', $data); } //Delete post public function delete_post($slug) { $this-&gt;db-&gt;where('slug', $slug); $this-&gt;db-&gt;delete('posts'); return true; } public function delete_post_image($id) { $this-&gt;db-&gt;update('posts', array('post_image'=&gt;'default.jpg'), ['id'=&gt;$id]); } </code></pre> <p>The create-post.php view:</p> <pre><code>&lt;div class="row"&gt; &lt;?php $this-&gt;load-&gt;view("dashboard/partials/sidebar-single");?&gt; &lt;div class="col-sm-7 col-md-9"&gt; &lt;div class="card bg-light"&gt; &lt;h6 class="card-header text-dark"&gt;New Post&lt;/h6&gt; &lt;div class="card-body bg-white"&gt; &lt;?php echo form_open_multipart(base_url('dashboard/posts/create')); ?&gt; &lt;div class="form-group &lt;?php if(form_error('title')) echo 'has-error';?&gt;"&gt; &lt;input type="text" name="title" id="title" class="form-control" value="&lt;?php echo set_value('title')?&gt;" placeholder="Title"&gt; &lt;?php if(form_error('title')) echo form_error('title'); ?&gt; &lt;/div&gt; &lt;div class="form-group &lt;?php if(form_error('desc')) echo 'has-error';?&gt;"&gt; &lt;input type="text" name="desc" id="desc" class="form-control" value="&lt;?php echo set_value('desc')?&gt;" placeholder="Short decription"&gt; &lt;?php if(form_error('desc')) echo form_error('desc'); ?&gt; &lt;/div&gt; &lt;div class="form-group &lt;?php if(form_error('body')) echo 'has-error';?&gt;"&gt; &lt;textarea name="body" id="body" cols="30" rows="5" class="form-control" placeholder="Add post body"&gt; &lt;?php echo set_value('body')?&gt; &lt;/textarea&gt; &lt;?php if(form_error('body')) echo form_error('body'); ?&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;select name="category" id="category" class="form-control"&gt; &lt;?php foreach ($categories as $category): ?&gt; &lt;option value="&lt;?php echo $category-&gt;id; ?&gt;"&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt; &lt;/div&gt; &lt;label for="postimage" id="imageUploader"&gt;Upload an image&lt;/label&gt; &lt;div class="form-group"&gt; &lt;input type="file" name="userfile" id="postimage" size="20"&gt; &lt;div class="error-messages"&gt; &lt;?php if(isset($upload_errors)){ foreach ($upload_errors as $upload_error) { echo $upload_error; } }?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group d-flex"&gt; &lt;div class="w-50 pr-1"&gt; &lt;input type="submit" value="Save" class="btn btn-block btn-md btn-success"&gt; &lt;/div&gt; &lt;div class="w-50 pl-1"&gt; &lt;a href="&lt;?php echo base_url('dashboard'); ?&gt;" class="btn btn-block btn-md btn-success"&gt;Cancel&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php echo form_close(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The edit-post.php view:</p> <pre><code>&lt;div class="row"&gt; &lt;?php $this-&gt;load-&gt;view("dashboard/partials/sidebar-single");?&gt; &lt;div class="col-sm-7 col-md-9"&gt; &lt;div class="card bg-light"&gt; &lt;h6 class="card-header text-dark"&gt;Edit post&lt;/h6&gt; &lt;div class="card-body bg-white"&gt; &lt;?php if ($this-&gt;session-&gt;flashdata('errors')) { $errors = $this-&gt;session-&gt;flashdata('errors'); echo '&lt;div class="error-group alert alert-warning alert-dismissible"&gt;' . "\n"; echo '&lt;button type="button" class="close" data-dismiss="alert"&gt;&amp;times;&lt;/button&gt;' . "\n"; echo $errors; echo '&lt;p class="error-message"&gt;We have restored the post.&lt;/p&gt;'; echo '&lt;/div&gt;'; } ?&gt; &lt;?php echo form_open_multipart(base_url('dashboard/posts/update')); ?&gt; &lt;input type="hidden" name="id" id="pid" value="&lt;?php echo $post-&gt;id; ?&gt;"&gt; &lt;input type="hidden" name="slug" id="slug" value="&lt;?php echo $post-&gt;slug; ?&gt;"&gt; &lt;div class="form-group &lt;?php if(form_error('title')) echo 'has-error';?&gt;"&gt; &lt;input type="text" name="title" id="title" class="form-control" placeholder="Title" value="&lt;?php echo $post-&gt;title; ?&gt;"&gt; &lt;?php if(form_error('title')) echo form_error('title'); ?&gt; &lt;/div&gt; &lt;div class="form-group &lt;?php if(form_error('desc')) echo 'has-error';?&gt;"&gt; &lt;input type="text" name="desc" id="desc" class="form-control" placeholder="Short decription" value="&lt;?php echo $post-&gt;description; ?&gt;"&gt; &lt;?php if(form_error('desc')) echo form_error('desc'); ?&gt; &lt;/div&gt; &lt;div class="form-group &lt;?php if(form_error('body')) echo 'has-error';?&gt;"&gt; &lt;textarea name="body" id="body" cols="30" rows="5" class="form-control" placeholder="Add post body"&gt;&lt;?php echo $post-&gt;content; ?&gt;&lt;/textarea&gt; &lt;?php if(form_error('body')) echo form_error('body'); ?&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;select name="category" id="category" class="form-control"&gt; &lt;?php foreach ($categories as $category): ?&gt; &lt;?php if ($category-&gt;id == $post-&gt;cat_id): ?&gt; &lt;option value="&lt;?php echo $category-&gt;id; ?&gt;" selected&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/option&gt; &lt;?php else: ?&gt; &lt;option value="&lt;?php echo $category-&gt;id; ?&gt;"&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/option&gt; &lt;?php endif; ?&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt; &lt;/div&gt; &lt;input type="hidden" name="postimage" id="postimage" value="&lt;?php echo $post-&gt;post_image; ?&gt;"&gt; &lt;label for="postimage" id="imageUploader"&gt;Upload an image&lt;/label&gt; &lt;div class="form-group"&gt; &lt;input type="file" name="userfile" id="postimage" size="20"&gt; &lt;?php if ($upload_errors = $this-&gt;session-&gt;flashdata('upload_errors')) { if ($this-&gt;session-&gt;flashdata('upload_errors')) { ?&gt; &lt;div class="error-messages"&gt; &lt;?php if(isset($upload_errors)){ foreach ($upload_errors as $upload_error) { echo $upload_error; } }?&gt; &lt;/div&gt; &lt;?php } } ?&gt; &lt;/div&gt; &lt;div class="form-group d-flex"&gt; &lt;div class="w-50 pr-1"&gt; &lt;input type="submit" value="Update" class="btn btn-block btn-md btn-success"&gt; &lt;/div&gt; &lt;div class="w-50 pl-1"&gt; &lt;a href="&lt;?php echo base_url('dashboard'); ?&gt;" class="btn btn-block btn-md btn-success"&gt;Cancel&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php echo form_close(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The sidebar-single.php partial (that displays the post image):</p> <pre><code>&lt;div class="card-list-group card bg-light mb-3"&gt; &lt;h6 class="card-header text-dark"&gt;Featured Image&lt;/h6&gt; &lt;div class="card-body p-0 bg-white"&gt; &lt;?php if (isset($post-&gt;post_image) &amp;&amp; $post-&gt;post_image !== 'default.jpg'): ?&gt; &lt;img src="&lt;?php echo base_url('assets/img/posts/') . $post-&gt;post_image; ?&gt;" alt="Main Image of &lt;?php echo $post-&gt;title; ?&gt;" class="img-fluid"&gt; &lt;?php else: ?&gt; &lt;img src="&lt;?php echo base_url('assets/img/posts/') . 'default.jpg'; ?&gt;" alt="Default Post Image" class="img-fluid"&gt; &lt;?php endif ?&gt; &lt;/div&gt; &lt;div class="card-footer p-2 bg-white text-center"&gt; &lt;a href="#&lt;?php echo isset($post-&gt;post_image) &amp;&amp; $post-&gt;post_image !== 'default.jpg' ? '' : 'imageUploader' ?&gt;" &lt;?php echo isset($post-&gt;post_image) &amp;&amp; $post-&gt;post_image !== 'default.jpg' ? 'data-pid="' . $post-&gt;id . '"' : '' ?&gt; id="postImage" class="smooth-scroll"&gt; &lt;?php echo isset($post-&gt;post_image) &amp;&amp; $post-&gt;post_image !== 'default.jpg' ? 'Delete' : 'Add' ?&gt; image &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Posts deleting is dome via jQuery Ajax:</p> <pre><code>//Delete Posts $('.delete-post').on('click', function(evt){ evt.preventDefault(); var deleteUrl = $(this).attr('href'); var slug = $(this).data('slug'); var postsCount = Number($("#posts_count").text()); if(confirm('Delete this post?')) { if ($(this).hasClass("ajax-btn")) { $.ajax({ url: baseUrl + '/dashboard/posts/delete/' + slug, method: 'GET', dataType: 'html', success: function(deleteMsg){ postsCount = postsCount - 1; $('tr[data-slug="' + slug +'"]').fadeOut('250'); $("#posts_count").text(postsCount); $('#post_delete_msg').text("The post has been deleted"); $('#post_delete_msg').slideDown(250).delay(2500).slideUp(250); } }); } else { window.location.href = deleteUrl; } } }); </code></pre> <p>The post image management (more exactly, deleteing the current post image) also makes use of jQuery Ajax:</p> <pre><code>$('#postImage').on('click', function(evt){ evt.preventDefault(); if (this.hash === "") { var $this = $(this); var $postImage = $this.closest('.card').find('img'); var $hiddenPostImage = $('input[name="postimage"]'); var defaultPostImage = baseUrl + 'assets/img/posts/default.jpg'; //Get post ID var id = $(this).data('pid'); if(confirm("Delete the post's featured image?")) { $.ajax({ url: baseUrl + 'dashboard/posts/deleteimage/' + id, method: 'GET', dataType: 'html', success: function(deleteMsg){ $postImage.attr('src', defaultPostImage); $hiddenPostImage.val(defaultPostImage); $this.text('Add image'); $this.attr('href', '#imageUploader'); } }); } } }); </code></pre> <p>What could I have done better an how? :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T01:45:01.590", "Id": "471587", "Score": "0", "body": "The title of the question must never be your concern about about your scripting, it is meant to uniquely express what your scripting does. Please edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:05:12.103", "Id": "471618", "Score": "0", "body": "I started to write a review, but then after I tried to refactor the `if(!$this->upload->do_upload()){` condition block in the `create()` method of your Post controller, I fear that not all possibilities are accounted for and that your script may be working properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:17:53.477", "Id": "471621", "Score": "0", "body": "It looks like `$tagline` and the `$category->posts_count` property is never used. I think you should try to tighen up the logic a bit more before dumping so much code for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:48:25.197", "Id": "471632", "Score": "0", "body": "@mickmackusa `$tagline` is used in the application. I can't add all my code here. Click the link to he Github repo." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:49:39.373", "Id": "471634", "Score": "0", "body": "Ugh, no thanks. It was already a large/broad review. I'm out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T23:03:09.510", "Id": "471833", "Score": "0", "body": "I’m voting to close this question because the posted scripts do not contain the full working script. Volunteers should never need to go anywhere else to find missing portions of scripts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T00:10:47.740", "Id": "471837", "Score": "2", "body": "@mickmackusa This is already one of the provided close reasons. Under \"Authorship of code\" there's the section \"that the code be [embedded directly](https://codereview.meta.stackexchange.com/a/3653)\". Please don't needlessly use custom close reasons. Additionally there is enough code to write a review IMO, voting to close this just seems like you're reaching." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T00:26:03.627", "Id": "471839", "Score": "0", "body": "@Peilonrayz Right you are, I overlooked that close reason. I started reviewing and found while dissecting the first script that some things were missing. This is a relatively large review for volunteers already. I have insights to share, but I can not confidently do so when bits are missing. I feel that I am justified in closing for this reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T00:32:06.627", "Id": "471840", "Score": "1", "body": "@mickmackusa I agree, from your perspective closing seems correct and just. But I still think my perspective is correct too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T06:15:56.197", "Id": "471982", "Score": "0", "body": "That is a pretty bundle of code to review. Can you guide our focus, do you have any particular concerns? (From what I remember from peer reviews, observing the programmer is at least as helpful in identifying problem areas as is inspecting code - albeit a bit difficult in this setting.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:18:46.400", "Id": "472569", "Score": "0", "body": "I’m voting to close this question because there are so many different things to review. Consider splitting up this post into parts. Review the controllers, and FE code separately, for example." } ]
[ { "body": "<p>Use Entities to represent you domain concerns and business rule.</p>\n\n<p>Use repositories to comunicate with the database.</p>\n\n<p>Upgrade to CodeIgniter 4</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T00:03:14.987", "Id": "240471", "ParentId": "240400", "Score": "2" } } ]
{ "AcceptedAnswerId": "240471", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:19:13.597", "Id": "240400", "Score": "1", "Tags": [ "php", "codeigniter" ], "Title": "Codeigniter 3 CMS (blogging) application" }
240400
<p>Python script that can downloads public and private profiles images and videos, like Gallery with photos or videos. It saves the data in the folder.</p> <p>How it works:</p> <ul> <li><p>Log in in instragram using selenium and navigate to the profile</p></li> <li><p>Checking the availability of Instagram profile if it's private or existing</p></li> <li><p>Creates a folder with the name of your choice</p></li> <li><p>Gathering urls from images and videos</p></li> <li><p>Using threads and multiprocessing improving the execution speed</p></li> </ul> <p>My code:</p> <pre><code>from pathlib import Path import requests import time from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, TimeoutException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from multiprocessing.dummy import Pool from concurrent.futures import ThreadPoolExecutor from typing import * import argparse import shutil class PrivateException(Exception): pass class InstagramPV: MAX_WORKERS: int = 8 N_PROCESSES: int = 8 def __init__(self, username: str, password: str, folder: Path, profile_name: str): """ :param username: Username or E-mail for Log-in in Instagram :param password: Password for Log-in in Instagram :param folder: Folder name that will save the posts :param profile_name: The profile name that will search """ self.username = username self.password = password self.folder = folder self.http_base = requests.Session() self.profile_name = profile_name self.links: List[str] = [] self.pictures: List[str] = [] self.videos: List[str] = [] self.url: str = 'https://www.instagram.com/{name}/' self.posts: int = 0 self.driver = webdriver.Chrome() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.http_base.close() self.driver.close() def check_availability(self) -&gt; None: """ Checking Status code, Taking number of posts, Privacy and followed by viewer Raise Error if the Profile is private and not following by viewer :return: None """ search = self.http_base.get(self.url.format(name=self.profile_name), params={'__a': 1}) search.raise_for_status() load_and_check = search.json() self.posts = load_and_check.get('graphql').get('user').get('edge_owner_to_timeline_media').get('count') privacy = load_and_check.get('graphql').get('user').get('is_private') followed_by_viewer = load_and_check.get('graphql').get('user').get('followed_by_viewer') if privacy and not followed_by_viewer: raise PrivateException('[!] Account is private') def create_folder(self) -&gt; None: """Create the folder name""" self.folder.mkdir(exist_ok=True) def login(self) -&gt; None: """Login To Instagram""" self.driver.get('https://www.instagram.com/accounts/login') WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'form'))) self.driver.find_element_by_name('username').send_keys(self.username) self.driver.find_element_by_name('password').send_keys(self.password) submit = self.driver.find_element_by_tag_name('form') submit.submit() """Check For Invalid Credentials""" try: var_error = WebDriverWait(self.driver, 4).until(EC.presence_of_element_located((By.CLASS_NAME, 'eiCW-'))) raise ValueError(var_error.text) except TimeoutException: pass try: """Close Notifications""" notifications = WebDriverWait(self.driver, 20).until( EC.presence_of_element_located((By.XPATH, '//button[text()="Not Now"]'))) notifications.click() except NoSuchElementException: pass """Taking cookies""" cookies = { cookie['name']: cookie['value'] for cookie in self.driver.get_cookies() } self.http_base.cookies.update(cookies) """Check for availability""" self.check_availability() self.driver.get(self.url.format(name=self.profile_name)) self.scroll_down() def posts_urls(self) -&gt; None: """Taking the URLs from posts and appending in self.links""" elements = self.driver.find_elements_by_xpath('//a[@href]') for elem in elements: urls = elem.get_attribute('href') if urls not in self.links and 'p' in urls.split('/'): self.links.append(urls) def scroll_down(self) -&gt; None: """Scrolling down the page and taking the URLs""" last_height = self.driver.execute_script('return document.body.scrollHeight') while True: self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight);') time.sleep(1) self.posts_urls() time.sleep(1) new_height = self.driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height self.submit_links() def submit_links(self) -&gt; None: """Gathering Images and Videos and pass to function &lt;fetch_url&gt; Using ThreadPoolExecutor""" self.create_folder() print('[!] Ready for video - images'.title()) print(f'[*] extracting {len(self.links)} posts , please wait...'.title()) with ThreadPoolExecutor(max_workers=self.MAX_WORKERS) as executor: for link in self.links: executor.submit(self.fetch_url, link) def get_fields(self, nodes: Dict, *keys) -&gt; Any: """ :param nodes: The json data from the link using only the first two keys 'graphql' and 'shortcode_media' :param keys: Keys that will be add to the nodes and will have the results of 'type' or 'URL' :return: The value of the key &lt;fields&gt; """ fields = nodes['graphql']['shortcode_media'] for key in keys: fields = fields[key] return fields def fetch_url(self, url: str) -&gt; None: """ This function extracts images and videos :param url: Taking the url :return None """ logging_page_id = self.http_base.get(url, params={'__a': 1}).json() if self.get_fields(logging_page_id, '__typename') == 'GraphImage': image_url = self.get_fields(logging_page_id, 'display_url') self.pictures.append(image_url) elif self.get_fields(logging_page_id, '__typename') == 'GraphVideo': video_url = self.get_fields(logging_page_id, 'video_url') self.videos.append(video_url) elif self.get_fields(logging_page_id, '__typename') == 'GraphSidecar': for sidecar in self.get_fields(logging_page_id, 'edge_sidecar_to_children', 'edges'): if sidecar['node']['__typename'] == 'GraphImage': image_url = sidecar['node']['display_url'] self.pictures.append(image_url) else: video_url = sidecar['node']['video_url'] self.videos.append(video_url) else: print(f'Warning {url}: has unknown type of {self.get_fields(logging_page_id,"__typename")}') def download_video(self, new_videos: Tuple[int, str]) -&gt; None: """ Saving the video content :param new_videos: Tuple[int,str] :return: None """ number, link = new_videos with open(self.folder / f'Video{number}.mp4', 'wb') as f: content_of_video = self.http_base.get(link, stream=True).raw shutil.copyfileobj(content_of_video, f) def images_download(self, new_pictures: Tuple[int, str]) -&gt; None: """ Saving the picture content :param new_pictures: Tuple[int, str] :return: None """ number, link = new_pictures with open(self.folder / f'Image{number}.jpg', 'wb') as f: content_of_picture = self.http_base.get(link, stream=True).raw shutil.copyfileobj(content_of_picture, f) def downloading_video_images(self) -&gt; None: """Using multiprocessing for Saving Images and Videos""" print('[*] ready for saving images and videos!'.title()) picture_data = enumerate(self.pictures) video_data = enumerate(self.videos) pool = Pool(self.N_PROCESSES) pool.map(self.images_download, picture_data) pool.map(self.download_video, video_data) print('[+] Done') def main(): parser = argparse.ArgumentParser() parser.add_argument('-U', '--username', help='Username or your email of your account', action='store', required=True) parser.add_argument('-P', '--password', help='Password of your account', action='store', required=True) parser.add_argument('-F', '--filename', help='Filename for storing data', action='store', required=True) parser.add_argument('-T', '--target', help='Profile name to search', action='store', required=True) args = parser.parse_args() with InstagramPV(args.username, args.password, Path(args.filename), args.target) as pv: pv.login() pv.downloading_video_images() if __name__ == '__main__': main() </code></pre> <p>Usage: <code>myfile.py -U myemail@hotmail.com -P mypassword -F Mynamefile -T stackoverjoke</code></p> <p>My previous comparative review tag:<a href="https://codereview.stackexchange.com/questions/240182/download-pictures-or-videos-from-instagram-using-selenium/240183#240183">Download pictures (or videos) from Instagram using Selenium</a></p>
[]
[ { "body": "<h2>More constants</h2>\n\n<p>This:</p>\n\n<pre><code> self.url: str = 'https://www.instagram.com/{name}/'\n</code></pre>\n\n<p>appears to be a constant, so it can join the others in class scope. While you're doing that, you can also pull the URL from <code>self.driver.get('https://www.instagram.com/accounts/login')</code> into a constant; and also pull the base URL out. In other words:</p>\n\n<pre><code>class InstagramPV:\n MAX_WORKERS: int = 8\n N_PROCESSES: int = 8\n\n BASE_URL = 'https://www.instagram.com/'\n PROFILE_URL_FMT = BASE_URL + '{name}/'\n LOGIN_URL = BASE_URL + 'accounts/login'\n</code></pre>\n\n<h2>Nested <code>get</code></h2>\n\n<p>These:</p>\n\n<pre><code>load_and_check.get('graphql').get('user').get('edge_owner_to_timeline_media').get('count')\n</code></pre>\n\n<p>won't actually do what you want, which is a fail-safe object traversal. For that you need to provide defaults that are empty dictionaries:</p>\n\n<pre><code>self.posts = (\n load_and_check.get('graphql', {})\n .get('user', {})\n .get('edge_owner_to_timeline_media', {})\n .get('count')\n)\n</code></pre>\n\n<p>Also, the first part should be factored out into its own temporary variable, since it's used three times:</p>\n\n<pre><code>user = (\n load_and_check.get('graphql', {})\n .get('user', {})\n)\n</code></pre>\n\n<h2>Methods for reuse</h2>\n\n<pre><code>self.driver.execute_script(\"return document.body.scrollHeight\")\n</code></pre>\n\n<p>should be factored out into a new method for re-use.</p>\n\n<h2>Static function</h2>\n\n<p>This:</p>\n\n<pre><code>def get_fields(self, nodes: Dict, *keys) -&gt; Any:\n \"\"\"\n :param nodes: The json data from the link using only the first two keys 'graphql' and 'shortcode_media'\n :param keys: Keys that will be add to the nodes and will have the results of 'type' or 'URL'\n :return: The value of the key &lt;fields&gt;\n \"\"\"\n fields = nodes['graphql']['shortcode_media']\n for key in keys:\n fields = fields[key]\n return fields\n</code></pre>\n\n<p>doesn't ever use <code>self</code>, which is a big clue that it doesn't belong as an instance method. You should just make it a <code>@staticmethod</code>. The only reason I don't recommend it moving to global scope is that it still has knowledge of the Instagram data format, with its reference to <code>graphql</code>.</p>\n\n<h2>Dictionary traversal</h2>\n\n<p>The loop in <code>get_fields</code> can be replaced with a call to <code>functools.reduce(dict.get, keys, media)</code>. Also, <code>keys</code> - even though it is a variadic argument - can still receive a type hint, and should be <code>Iterable[str]</code>. <code>nodes</code> itself, if you don't know a lot about the structure of the dictionary, can still be narrowed to <code>nodes: Dict[str, Any]</code>.</p>\n\n<h2>Context manager for response</h2>\n\n<p>Now that you're using the streaming interface for Requests (nice!), it's more important that you use the response object as a context manager. For more information read <a href=\"https://github.com/psf/requests/issues/4136\" rel=\"nofollow noreferrer\">https://github.com/psf/requests/issues/4136</a></p>\n\n<p>Basically:</p>\n\n<pre><code>with open(self.folder / f'Video{number}.mp4', 'wb') as f, \\\n self.http_base.get(link, stream=True) as response:\n shutil.copyfileobj(response.raw, f)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:12:26.140", "Id": "471546", "Score": "0", "body": "Questions : 1) _Methods for reuse_ should i put this in a variable for reuse? 2) _Static function_ the field returns 'str' or 'list' , can Any be `Any[str,list]` ? 3) Staticmethods should be in the end of class or doesn't matter ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:13:57.720", "Id": "471548", "Score": "0", "body": "1. If it never changes, then yes, a variable is better than a method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:14:30.347", "Id": "471549", "Score": "0", "body": "2. This is a job for `Union`! If you know it may be `str` or `list`, then `Union[str, list]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T18:55:40.817", "Id": "471557", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/106645/discussion-between-reinderien-and-peilonrayz)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T19:09:20.887", "Id": "471558", "Score": "0", "body": "I believe using `reduce` is bad advice. Around [15 years ago](https://www.artima.com/weblogs/viewpost.jsp?thread=98196) Guido tried to drop `map`, `filter` and `reduce`. For reasons unknown to me they were only relegated to `functools`. However now-a-days the three functions are not in common use with [Google explicitly deprecating them](https://google.github.io/styleguide/pyguide.html#215-deprecated-language-features). I leave this as a notice for future users that the advice to use `reduce` may not be the best advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T19:16:27.087", "Id": "471559", "Score": "1", "body": "To summarize the reason that I will stand by this suggestion: being Pythonic is about simplicity, and this is simple; `functools` should be avoided when there is a simpler tool that does the same job, but there is not. https://stackoverflow.com/a/36584550/313768 remains (in my opinion, rightfully) an acceptable answer. In many, many other cases, `reduce` is a bad idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:34:50.543", "Id": "471571", "Score": "0", "body": "Just to be clear, why are you using the `requests` module if you have Selenium ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T01:23:18.807", "Id": "471585", "Score": "0", "body": "I think it actually makes sense. If there's a large, gruesome, JS-heavy UI for which the easiest interaction is Selenium-style, use Selenium; if there's a decouple-able simple HTTP request necessary, Requests is a better choice. Module installation via pip is cheap, so I think the correct thing is being done here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T12:28:05.260", "Id": "471616", "Score": "0", "body": "Using both `requests` and Selenium makes it 'obvious' to the website this is a scraping job, not just because multiple connections are being made but because the default **user agent** of `requests` is something like: `python-requests/2.23.0`. So there is a greater likelihood that you will be flagged as a **bot** and blocked. I would spoof the user agent in `requests` to make it like Selenium. Also make the request headers more or less the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:40:22.420", "Id": "471630", "Score": "0", "body": "Let's please use the chat link above ^ to discuss this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T13:51:38.503", "Id": "472409", "Score": "0", "body": "@Reinderien my new [question](https://codereview.stackexchange.com/questions/240798/instagram-scraping-using-selenium-download-posts-photos-videos)" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:57:18.390", "Id": "240403", "ParentId": "240401", "Score": "5" } } ]
{ "AcceptedAnswerId": "240403", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T16:27:48.610", "Id": "240401", "Score": "5", "Tags": [ "python", "python-3.x", "web-scraping", "selenium", "instagram" ], "Title": "Scraping Instagram - Download posts, photos - videos" }
240401
<p>My effort to write async methods for copy/move a file in C#</p> <pre><code>public static class FileHelper { private const int _FileStreamDefaultBufferSize = 4096; private static bool HasNetworkDrive(string path) { try { return new DriveInfo(path).DriveType == DriveType.Network; } catch (Exception) { return false; } } private static bool IsUncPath(string path) { try { return new Uri(path).IsUnc; } catch (Exception) { return false; } } private static async Task InternalCopyToAsync(string sourceFilePath, string destFilePath, FileOptions? sourceFileOptions = null, bool overwrite = false) { sourceFilePath.AssertHasText(nameof(sourceFilePath)); destFilePath.AssertHasText(nameof(destFilePath)); var sourceStreamFileOpt = (sourceFileOptions ?? FileOptions.SequentialScan) | FileOptions.Asynchronous; using (FileStream sourceStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, _FileStreamDefaultBufferSize, sourceStreamFileOpt)) using (FileStream destinationStream = new FileStream(destFilePath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.Write, FileShare.None, _FileStreamDefaultBufferSize, true)) { await sourceStream.CopyToAsync(destinationStream, _FileStreamDefaultBufferSize).ConfigureAwait(false); } } public static async Task MoveAsync(string sourceFilePath, string destFilePath) { sourceFilePath.AssertHasText(nameof(sourceFilePath)); destFilePath.AssertHasText(nameof(destFilePath)); if (IsUncPath(sourceFilePath) || HasNetworkDrive(sourceFilePath) || IsUncPath(destFilePath) || HasNetworkDrive(destFilePath)) { await InternalCopyToAsync(sourceFilePath, destFilePath, FileOptions.DeleteOnClose).ConfigureAwait(false); return; } FileInfo sourceFileInfo = new FileInfo(sourceFilePath); string sourceDrive = Path.GetPathRoot(sourceFileInfo.FullName); FileInfo destFileInfo = new FileInfo(destFilePath); string destDrive = Path.GetPathRoot(destFileInfo.FullName); if (sourceDrive == destDrive) { File.Move(sourceFilePath, destFilePath); return; } await Task.Run(() =&gt; File.Move(sourceFilePath, destFilePath)).ConfigureAwait(false); } public static async Task CopyAsync(string sourceFileName, string destFileName) { await InternalCopyToAsync(sourceFileName, destFileName).ConfigureAwait(false); } public static async Task CopyAsync(string sourceFileName, string destFileName, bool overwrite) { await InternalCopyToAsync(sourceFileName, destFileName, overwrite: overwrite).ConfigureAwait(false); } } </code></pre> <p>The extension method <code>AssertHasText</code> is just throwing an <code>ArgumentNullException</code> if <code>!string.IsNullOrWhiteSpace(argument)</code></p> <p>Regarding the implementation of <code>MoveAsync</code> I followed these guidelines</p> <ul> <li>If the source or dest path are a from a network drive, or UNC path, I call the internal async copy method with the flag <code>FileOptions.DeleteOnClose</code></li> <li>If the source drive is the same as the dest drive, I call the standard <code>File.Move</code> method, because it is an almost-instantaneous operation, as the headers are changed but the file contents are not moved</li> <li>In any other case, I use a <code>Task</code> with the standard <code>File.Move</code>. I differentiate the above case to save an unnecessary thread</li> </ul> <p>Question: Regarding the implementation of <code>CopyAsync</code> it will always copy the stream, Can previous claims be applied to the copy as well?</p> <p>EDIT: Adding the implementation of <code>AssertArgumentHasText</code></p> <pre><code>public static void AssertArgumentHasText(this string argument, string name) { if (argument.IsNullOrEmpty()) { throw new ArgumentNullException( name, string.Format( CultureInfo.InvariantCulture, &quot;Argument '{0}' cannot be null or resolve to an empty string : '{1}'.&quot;, name, argument)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T12:44:53.647", "Id": "480918", "Score": "1", "body": "@HenrikHansen as I already stated, it is a wrapper for `string.IsNullOrWhiteSpace` and throws an `ArgumentNullException` taking the name of the var to pass to the exception as an argument." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T12:50:35.127", "Id": "480920", "Score": "1", "body": "@HenrikHansen this is really not the point of the question, however that's an extension method and has actually 2 args, so I'll update the question with the implementation and we can move on to real business" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T05:55:34.847", "Id": "481184", "Score": "1", "body": "From what perspective do you want the code to be reviewed? Or is there any particular question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T07:55:43.047", "Id": "481199", "Score": "1", "body": "@PeterCsala actually yes, my concerns are about the `CopyAsync` method, I updated my question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T10:28:30.093", "Id": "481224", "Score": "1", "body": "Sorry, but I don't get your question. You are calling the `CopyAsync` only in case of Network drive, in other cases you call `File.Move`. So, why do you want to apply the same branching for the Copy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T12:38:05.697", "Id": "481227", "Score": "0", "body": "@PeterCsala actually, they are 2 very separated method. The method `CopyToAsync` is very different from `MoveAsync`, because it will always copy the stream, while the second does some thinking. Should I do the same for `CopyToAsync`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T12:56:46.247", "Id": "481232", "Score": "0", "body": "Because your `CopyAsync` is exposed for external consumers as well, I think it would make sense to do the same branching as you did with the `MoveAsync`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T13:03:00.110", "Id": "481233", "Score": "0", "body": "@PeterCsala please make an answer with some valid reasons for doing as you say, in order to close the question" } ]
[ { "body": "<h2>Errors aren't answers</h2>\n<p>This:</p>\n<pre><code> try\n {\n return new DriveInfo(path).DriveType == DriveType.Network;\n }\n catch (Exception)\n {\n return false;\n }\n</code></pre>\n<p>will harm and not help you. What if a caller passes the integer <code>3</code> for <code>path</code>? The network drive status is certainly not <code>True</code>, but you can't say that it's <code>False</code>, either. It's an error, and should be allowed to fall through, which means you should not be catching <code>Exception</code>. In a different vein: what if (for some weird reason) the <code>DriveType</code> property lookup runs into an <code>OutOfMemoryException</code>? That is also not proof that this is not a network drive.</p>\n<p>If you understand that there are certain (perhaps <code>IOException</code> or derived) exceptions that actually <em>do</em> indicate that this is not a network drive, then catch those specifically.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T12:39:12.447", "Id": "481228", "Score": "0", "body": "Good point, it is a further edit to be done. What about the main question instead?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T14:17:14.940", "Id": "244942", "ParentId": "240407", "Score": "3" } }, { "body": "<blockquote>\n<p>Regarding the implementation of <code>CopyAsync</code> it will always copy the stream.<br />\n<em>Can previous claims be applied to the copy as well?</em></p>\n</blockquote>\n<p>Your current implementation exposes two sort of operations:</p>\n<ol>\n<li>Move</li>\n<li>Copy</li>\n</ol>\n<p>They are sharing the same signature (more or less). The <code>override</code> functionality is not controllable in case of <code>Move</code> from the consumer perspective.</p>\n<p>The <code>Copy</code> operation is optimized to reduce latency (to take advantage of data locality) by branching based on the location of the drive. The same branching could be applied to the <code>Move</code> as well to provide symmetric behaviour. If it branches in the same way then extension in any direction (new driver location (for example Kubernetes virtual drive), new operation (for example Delete), etc.) would be way more convenient.</p>\n<p>From readability and maintainability perspective it is easier to have symmetric functions, because after awhile (without any context / reasoning why <code>Move</code> does not apply the same optimization as Copy do) no one will know who and why did this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T13:29:19.630", "Id": "245079", "ParentId": "240407", "Score": "1" } } ]
{ "AcceptedAnswerId": "245079", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:42:13.957", "Id": "240407", "Score": "3", "Tags": [ "c#", "asynchronous", "io" ], "Title": "Async file copy/move" }
240407
<p>I have created a small library for use by beginner C++ students who are forbidden from using <code>std::vector</code> in their projects. Because of this, I would like you to review my code from the viewpoint of:</p> <h2>Is this code readable, usable, and accessible by beginners in C++?</h2> <p>I see a lot of questions on stackoverflow by students looking for help on their homework questions. Some of these homework questions use manual memory management. Lots of naked pointers to heap allocated memory being passed around. No object owns these pointers. Most of the questions with manual memory management have something like this in the comment section:</p> <blockquote> <p>Why don't you just use <code>std::vector</code>? --totally_rad_programmer_guy</p> <p>We haven't learned that yet. The professor said we can't use <code>vector</code> --OP Student</p> </blockquote> <p>I find these very frustrating. Manual memory management is worth teaching, but if someone is new to a language, let them use the cool toys first! For C++, teach them about encapsulation and RAII and the Rules of 0/3/5. Let them use <code>std::vector</code> out of the gate. &quot;This is a vector. You access it like this. Enjoy.&quot;</p> <p>I created <code>dumb::vector</code> as a class that the student can add to their homework to handle memory management. They still have to read and understand it. They at least have to modify it. But now they can focus on programming and not juggling pointers.</p> <p>I also provide a stripped down <code>dumbestvector</code> class that is super minimal.</p> <p>The point of this code is to use the bare minimum new concepts while introducing memory management. I want to reduce the cognitive load on the student so they're more likely to adopt <code>dumb::vector</code>. So there's no <code>explicit</code>. None of the functions are <code>const</code>. I use <code>unsigned int</code> instead of <code>std::size_t</code>.</p> <p><code>dumbvector.h</code>, <code>dumbestvector.h</code>, and <code>test.cpp</code> are the three main files. Provided below for your reviewing pleasure. The github link is here: <a href="https://github.com/jfilleau/dumbvector" rel="nofollow noreferrer">https://github.com/jfilleau/dumbvector</a></p> <h2>dumbvector.h:</h2> <pre><code>#ifndef DUMB_VECTOR_H #define DUMB_VECTOR_H /* dumb::vector &quot;I'm not allowed to use std::vector!&quot; the student lamented on stackoverflow. The commenters rolled their collective eyes. */ #include &lt;initializer_list&gt; namespace dumb { class vector { private: // using something different than int? Change it here! typedef int value_type; value_type* data_; unsigned int size_; unsigned int capacity_; public: /* YOU MUST KEEP AT LEAST ONE OF THE FOLLOWING FOUR CONSTRUCTORS */ // This one lets you make an empty vector: // dumb::vector v; vector() { data_ = nullptr; size_ = 0; capacity_ = 0; } // This one lets you make a vector of a certain size. // All elements are default constructed: // dumb::vector v(10); vector(unsigned int count) { data_ = new value_type[count]; size_ = count; capacity_ = count; } // This one lets you make a vector of a certain size. // All elements are default constructed, but then assigned value // dumb::vector v(10, 1000); // 10 ints all set to value 1000 vector(unsigned int count, const value_type&amp; value) { data_ = new value_type[count]; size_ = count; capacity_ = count; for (unsigned int i = 0; i &lt; size_; ++i) { data_[i] = value; } } // This one lets you use an initializer_list for creation. // I know this might be confusing. If you don't want to use this one, // remove #include &lt;initializer_list&gt; from the top of this file. // dumb::vector v = {1, 1, 2, 3, 5, 8, 13}; vector(const std::initializer_list&lt;value_type&gt;&amp; init_list) { size_ = init_list.size(); capacity_ = init_list.size(); data_ = new value_type[size_]; auto it = init_list.begin(); for (unsigned int i = 0; i &lt; size_; ++i) { data_[i] = *it; ++it; } } /* YOU MUST KEEP THE FOLLOWING THREE FUNCTIONS OR RULE OF 3 IS VIOLATED */ // copy constructor. Type MUST BE const reference vector(const vector&amp; other) { data_ = new value_type[other.size_]; size_ = other.size_; capacity_ = other.size_; for (unsigned int i = 0; i &lt; size_; ++i) { data_[i] = other.data_[i]; } } // assignment operator. Other doesn't need to be const reference but it is good practice vector&amp; operator=(const vector&amp; other) { delete[] data_; data_ = new value_type[other.size_]; size_ = other.size_; capacity_ = other.size_; for (unsigned int i = 0; i &lt; size_; ++i) { data_[i] = other.data_[i]; } return *this; } // destructor ~vector() { delete[] data_; } /* THE FOLLOWING FUNCTIONS ARE OPTIONAL BUT RECOMMENDED DEPENDING ON YOUR NEEDS */ // allows index operations // dumb::vector v(10, 5); // vector of size 10, all set to 5 // v[0] = 20; // set the first element to 20 instead value_type&amp; operator[](unsigned int pos) { return data_[pos]; } unsigned int size() { return size_; } /* THE FOLLOWING FUNCTIONS ARE OPTIONAL DEPENDING ON YOUR NEEDS */ bool empty() { return size_ == 0; } // increase capacity if required, and copy the element to the end void push_back(const value_type&amp; value) { if (size_ == capacity_) { reserve(size_ + 1); } data_[size_] = value; ++size_; } // removes the last element from the vector. Does not return it. void pop_back() { --size_; // this overwrites what used to be the last element // with a default constructed object of your type // essentially deleting what used to be there data_[size_] = value_type{}; } // increases capacity if required, inserts a copy of the element at the chosen index value_type* insert(unsigned int pos, const value_type&amp; value) { if (size_ == capacity_) { reserve(size_ + 1); } for (unsigned int i = size_; i &gt; pos; --i) { data_[i] = data_[i - 1]; } data_[pos] = value; ++size_; return data_ + pos; } // copies every element above pos down a slot value_type* erase(unsigned int pos) { --size_; unsigned int i; for (i = pos; i &lt; size_; ++i) { data_[i] = data_[i + 1]; } // this overwrites what used to be the last element // with a default constructed object of your type // essentially deleting what used to be there data_[i] = value_type{}; return data_ + pos; } // Copies all the elements in the vector to a larger data allocation. // Accessing that extra space is undefined behavior. // dumb::vector v; // v.reserve(10); // increases capacity to 10 // for (unsigned int i = 0; i &lt; 10; i++) // v.push_back(i); // doesn't keep copying the entire vector on every push_back() void reserve(unsigned int new_cap) { if (new_cap &lt;= capacity_) return; value_type* new_data = new value_type[new_cap]; for (unsigned int i = 0; i &lt; size_; ++i) { new_data[i] = data_[i]; } delete[] data_; data_ = new_data; capacity_ = new_cap; } // returns a raw pointer to the data. Really useful for // functions that take a value_type[] as a parameter value_type* data() { return data_; } // acts as an iterator so you can use iterator loops // and range-based for loops // for (auto i = v.begin(); i != v.end(); i++) // func(*i); // for (auto i : v) // func(i); value_type* begin() { return data_; } // same as above value_type* end() { return data_ + size_; } }; } #endif // DUMB_VECTOR_H </code></pre> <h2>dumbestvector.h:</h2> <pre><code>#ifndef DUMBEST_VECTOR_H #define DUMBEST_VECTOR_H /* dumbestvector For when dumb::vector isn't dumb enough. */ class dumbestvector { private: // using something different than int? Change it here! typedef int value_type; value_type* data_; unsigned int size_; public: /* ONLY ONE CONSTRUCTOR IS AVAILABLE */ // This one lets you make a vector of a certain size. // All elements are default constructed, but then assigned value // dumbestvector v(10, 1000); // 10 ints all set to value 1000 dumbestvector(unsigned int count, const value_type&amp; value) { data_ = new value_type[count]; size_ = count; for (unsigned int i = 0; i &lt; size_; ++i) { data_[i] = value; } } /* YOU MUST KEEP THE FOLLOWING THREE FUNCTIONS OR RULE OF 3 IS VIOLATED */ // copy constructor. Type MUST BE const reference dumbestvector(const dumbestvector&amp; other) { data_ = new value_type[other.size_]; size_ = other.size_; for (unsigned int i = 0; i &lt; size_; ++i) { data_[i] = other.data_[i]; } } // assignment operator. Other doesn't need to be const reference but it is good practice dumbestvector&amp; operator=(const dumbestvector&amp; other) { delete[] data_; data_ = new value_type[other.size_]; size_ = other.size_; for (unsigned int i = 0; i &lt; size_; ++i) { data_[i] = other.data_[i]; } return *this; } // destructor ~dumbestvector() { delete[] data_; } /* THE FOLLOWING FUNCTIONS ARE OPTIONAL BUT RECOMMENDED DEPENDING ON YOUR NEEDS */ value_type&amp; operator[](unsigned int pos) { return data_[pos]; } unsigned int size() { return size_; } // returns a raw pointer to the data. Really useful for // functions that take a value_type[] as a parameter value_type* data() { return data_; } }; #endif // DUMBEST_VECTOR_H </code></pre> <h2>test.cpp:</h2> <pre><code>#include &lt;iostream&gt; #include &quot;dumbvector.h&quot; #include &quot;dumbestvector.h&quot; void print_vec_it(dumb::vector vec); void print_vec_loop(dumb::vector vec); void print_dumbest(dumbestvector vec); void insertion_sort(dumb::vector&amp; vec); void insertion_sort(dumbestvector&amp; vec); int main(int argc, char** argv) { // create an empty dumb::vector and push_back elements into it dumb::vector v1; v1.push_back(0); v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); // we can either use iterators or loops to access the contents std::cout &lt;&lt; &quot;Testing iterator printing:\n&quot;; print_vec_it(v1); std::cout &lt;&lt; &quot;Testing loop printing:\n&quot;; print_vec_loop(v1); // pop pop! v1.pop_back(); std::cout &lt;&lt; &quot;Testing pop_back(). Should be one fewer item then before:\n&quot;; print_vec_it(v1); // testing that insert works v1.insert(0, 10); std::cout &lt;&lt; &quot;Testing insert(0, 10). First element should be 10:\n&quot;; print_vec_it(v1); v1.insert(2, 20); std::cout &lt;&lt; &quot;Testing insert(2, 20). Third element should be 20:\n&quot;; print_vec_it(v1); // testing that operator[] works v1[0] = 6; v1[4] = 12; std::cout &lt;&lt; &quot;Testing operator[]. v[0] = 6; v[4] = 12;\n&quot;; print_vec_it(v1); // testing that copy construction works dumb::vector v2 = v1; std::cout &lt;&lt; &quot;Testing copy construction. Should be same as above:\n&quot;; print_vec_it(v2); // testing that erase works std::cout &lt;&lt; &quot;Testing erase. Fourth element should be erased:\n&quot;; v2.erase(3); print_vec_it(v2); // testing that assignment operator works v1 = v2; std::cout &lt;&lt; &quot;Testing operator=. Should be same as above:\n&quot;; print_vec_it(v1); // testing that initializer lists work dumb::vector v3{ 1, 1, 2, 3, 5, 8, 13 }; dumb::vector v4 = { 21, 34, 55, 89 }; std::cout &lt;&lt; &quot;Testing initializer_list construction. Should be { 1, 1, 2, 3, 5, 8, 13 }:\n&quot;; print_vec_it(v3); std::cout &lt;&lt; &quot;Testing initializer_list construction. Should be { 21, 34, 55, 89 }:\n&quot;; print_vec_it(v4); dumb::vector v5 = { 7, 0, -8, 100, 12345, 2, 22 }; std::cout &lt;&lt; &quot;Testing a common use case, insertion sort. Unsorted dumb::vector:\n&quot;; print_vec_it(v5); insertion_sort(v5); std::cout &lt;&lt; &quot;After sorting:\n&quot;; print_vec_it(v5); // test dumbest vector dumbestvector v6(10, 100); std::cout &lt;&lt; &quot;Testing dumbest vector. Should be 10 elements of value 100:\n&quot;; print_dumbest(v6); v6[5] = 0; std::cout &lt;&lt; &quot;Testing operator[]. v[5] = 0:\n&quot;; print_dumbest(v6); for (unsigned int i = 0; i &lt; v6.size(); i++) { v6[i] = i * -10; } std::cout &lt;&lt; &quot;Testing dumbestvector insertion sort. Unsorted:\n&quot;; print_dumbest(v6); insertion_sort(v6); std::cout &lt;&lt; &quot;After sorting:\n&quot;; print_dumbest(v6); } void print_vec_it(dumb::vector vec) { std::cout &lt;&lt; &quot;[ &quot;; for (const auto&amp; i : vec) { std::cout &lt;&lt; i &lt;&lt; &quot; &quot;; } std::cout &lt;&lt; &quot;]\n&quot;; } void print_vec_loop(dumb::vector vec) { std::cout &lt;&lt; &quot;[ &quot;; for (unsigned int i = 0; i &lt; vec.size(); ++i) { std::cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;; } std::cout &lt;&lt; &quot;]\n&quot;; } void print_dumbest(dumbestvector vec) { std::cout &lt;&lt; &quot;[ &quot;; for (unsigned int i = 0; i &lt; vec.size(); ++i) { std::cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;; } std::cout &lt;&lt; &quot;]\n&quot;; } void insertion_sort(dumb::vector&amp; vec) { unsigned int i = 1; while (i &lt; vec.size()) { unsigned int j = i; while (j &gt; 0 &amp;&amp; vec[j - 1] &gt; vec[j]) { std::swap(vec[j], vec[j - 1]); j -= 1; } i += 1; } } void insertion_sort(dumbestvector&amp; vec) { unsigned int i = 1; while (i &lt; vec.size()) { unsigned int j = i; while (j &gt; 0 &amp;&amp; vec[j - 1] &gt; vec[j]) { std::swap(vec[j], vec[j - 1]); j -= 1; } i += 1; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T10:31:56.500", "Id": "471760", "Score": "1", "body": "It's a bit hard to give a review on this - many good practices may be rejected as \"too advanced\" since they require, well, advanced features. Would it be fine if you receive a review that includes some advanced features (for the benefit of future readers)? You can selectively ignore the suggestions that you find unsuitable for beginners." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T12:32:07.107", "Id": "471772", "Score": "0", "body": "Sure, why not? Go ham." } ]
[ { "body": "<h1>Concept review</h1>\n<p>Bad teachers are, in my opinion, one of the biggest problems plaguing C++. It blows my mind that there are still people teaching C++ in 2021 using techniques used to teach C in the 1970s. The problem is so pervasive the standards committee even put together a working group specifically for the purpose of guiding people on how to properly teach C++.</p>\n<p>So I think you have correctly identified a very real, very serious, and very pervasive problem. What I think you have incorrectly identified is where to go about fixing it. If the problem is shitty teachers, you’re not going to fix it by targeting the students.</p>\n<p>But okay, maybe your goal isn’t to fix the problem, it’s just to help the students in a shitty situation. Unfortunately, on that count I think this kind of idea fails completely, for several reasons:</p>\n<ol>\n<li><p><strong>It doesn’t actually help the student learn C++.</strong></p>\n<p>Handing the student a ready-made class to use is hardly going to help them learn whatever it is they’re supposed to be learning in the assignment they’re struggling with. You may argue that it does, because (like the actual <code>std::vector</code>) it takes away the burden of worrying about all the manual memory management cruft so they can focus on the <em>real</em> thing being taught. That <em>MAY</em> be true… if the point of the teaching exercise wasn’t explicitly to understand what’s going on in memory in the solution. Which, frankly, it often is.</p>\n<p>But the point stands regardless, because <em>if</em> the point of these classes is to provide a <code>vector</code>-lite that the student can understand the inner workings of, then you’re doing them a disservice by writing those inner workings for them, and <em>more</em> so by “dumbing them down”. Let me put that point in point form, to see if that makes it clearer:</p>\n<ul>\n<li>If they <em>should</em> understand C++ well enough to write <code>dumb::vector</code>… then why can’t they write <code>dumb::vector</code> themselves?</li>\n<li>If they’re <em>not</em> supposed to understand C++ well enough to write <code>dumb::vector</code>… then why dumb it down so much? It’s over their head anyway, so why not just do it <em>properly</em>? Why not just re-implement <code>std::vector</code>? Or at least, implement a <code>vector</code>-lite that is still <em>correct</em> (that is, with <code>explicit</code>, <code>const</code>, and the works)?</li>\n</ul>\n</li>\n<li><p><strong>The teacher <em>expects</em> the student to do the manual memory management.</strong></p>\n<p>Putting aside how terrible the teacher’s technique is, they <em>are</em> trying to teach the student something with the assignment. You assume that whatever they’re trying to teach is <em>not</em> manual memory management. That’s a rather specious assumption.</p>\n<p>The teacher has either taught the student everything they need to do the assignment—manual memory management and all—or provided them with the resources they need to figure out it. You are not helping the student by aiding in an end-run around the teacher’s lesson plan. Whatever the student was supposed to learn from the exercise… now they won’t. That’s not helping the student with their course; that’s literally the opposite of that.</p>\n</li>\n<li><p><strong>“Dumbing down” a language is a spectacularly bad way to teach it.</strong></p>\n<p>Have you ever seen a book that teaches, say, French, by teaching the students pidgin “Frenglish” first? No, of course not. Because that would be both ridiculous and actively counter-productive.</p>\n<p>The proper way to teach a language is not to “dumb down” parts of the language that are too complicated to swallow at first. It’s to <em>avoid</em> those complicated parts until the student is ready. When the complexity is unavoidable, you <em>still</em> don’t “dumb it down”, you just present it as is as a matter of fact, and then work with that. For example, in theory just to get the student to introduce themselves in the simplest way, the teacher has to introduce the conjugations of the verb “être”—which is irregular. But of course, that’s not what they actually do; they just tell students that “je suis” is basically “I am”, and that’s that, and from there the student can tack on their name and voilà! They’re actually speaking real, honest-to-goodness French. Granted, all they can say is “I am John/Jane”… but that ain’t nothin’, and from there, the teacher will take the <em>same construct</em> (“je suis ___”) and expand the vocabulary with numbers (that is, age), the idea of linguistic gender (via giving one’s nationality or something else), and so on. Then next, maybe, you show how you can replace “I am/je suis” with “he/she/it is”, while using all the already introduced stuff (age, nationality), and so on, building up from there until <em>eventually</em> the student is ready to be shown the big picture (the full conjugation table).</p>\n<p>To use a C++ example, you wouldn’t just… hide <code>const</code> from students when teaching them about member functions. You would teach them basic member functions that don’t <em>need</em> <code>const</code> first… and then teach them when to use <code>const</code>. For example, you could introduce classes/structs as simple aggregate types (like “struct point { int x; int y; };”), then add a mutating member function (<code>auto mirror_in_y_axis() { x = -x; }</code>), then a non-mutating member function (<code>auto distance_from_origin() const { return std::sqrt((x * x) + (y * y)); }</code>), explaining everything at each step.</p>\n</li>\n<li><p><strong>Playing cute and trying to outsmart the teacher is most likely to backfire.</strong></p>\n<p>I have to wonder exactly what you think will happen if a student turns an assignment with <code>dumb::vector</code> bundled in.</p>\n<ul>\n<li><strong>Teacher:</strong> I thought I said you couldn’t use the standard library.</li>\n<li><strong>Student:</strong> Ah, but that’s not the <em>standard library</em> vector. It’s a dumbed-down variant!</li>\n<li><strong>Teacher:</strong> But you didn’t write it yourself. That’s plagiarism.</li>\n<li><strong>Student:</strong> Ah, but, you see, I <em>understand</em> it because it’s dumbed down! Also, I <em>did</em> sorta <em>type</em> it myself! (Insofar as <code>Ctrl+C &amp;&amp; Ctrl+V</code> counts as “typing”.)</li>\n<li><strong>Teacher:</strong> Well, you’ve completely outwitted me, so I guess I have no option but to give you an A!</li>\n</ul>\n<p>(… and that student’s name… was Albert Einstein!)</p>\n<p>Yeah, no. This is not going to end well for the student stupid enough to actually <em>use</em> <code>dumb::vector</code> in their assignment.</p>\n</li>\n</ol>\n<p>Let me say again that I <em>completely</em> understand your frustration at seeing C++ newbies struggling with bullshit that they really don’t need to be struggling with… both because it’s not necessary to learn the language well (at least not until very advanced stages), and because it’s functionally useless information in practice because who actually <em>does</em> low-level manual memory management like that anymore.</p>\n<p><em>But….</em></p>\n<p>To <em>anyone</em> who comes across a newbie struggling with a C++ problem that they <em><strong>HAVE</strong></em> to solve (because it’s an assignment, for example, rather than just personal amusement)… if you, for <em>whatever reason</em>, don’t want to help them solve <em><strong>THAT PROBLEM</strong></em> (you’d rather show them the “better” way to do it, using modern/advanced techniques or whatever)… then I say, with no personal rancour intended…: STFU.†</p>\n<p>If you lack the patience to get into the weeds and walk the student through their <code>malloc()/free()</code> spaghetti soup, then <em>DO NOT</em> try to offer them a sly trick to get out of it all, and instead just…: STFU.</p>\n<p>You are <em>NOT</em> helping the newbie by distracting them with all the lovely things they cannot have. You are only frustrating and confusing them. It’s fine to offer a glimpse of what lies beyond their shitty C++ course <em>while also helping them in the way they need</em>. But if you’re not willing to really get into the muck and walk <em>WITH</em> the learner through that grody, tedious, poorly conceived and formatted code—<em>NOT</em> simply giving them the answers, but rather guiding them to figure the answers out on their own—then, please…: STFU.</p>\n<p>Let someone who actually wants to help do so, and don’t become distracting noise while they do.</p>\n<p>† (And for those who don’t know that acronym, here’s a link that should clear it up: <a href=\"https://en.wikipedia.org/wiki/STFU\" rel=\"noreferrer\">STFU</a>.)</p>\n<p>(Note that if you’re dealing with a situation where a learner does <em>not</em> <em><strong>HAVE</strong></em> to eschew the standard library—for example, someone just doing some self-directed learning, or “challenging” themselves for some reason—then that’s a very different situation. By all means, with those types, show them the <em>correct</em> way to do it. And if you feel disinclined to help them do it the way <em>they</em> want to do it… meh, then don’t bother; it’s not worth your time.)</p>\n<p>Helping students is not about showing off your mad l33t C++ skillz. Or about showing them how to get away with not doing the work their C++ teacher expects them to do. Helping students is about working <em>WITH</em> the student to understand what <em>THEY</em> need… not what you think they need… and then figuring out how they can achieve that. It is <em>NOT</em> easy to do; not everyone is cut out for it, and even those of us who’ve done it for years do have moments when we look at a teacher’s instructions and go, “WTF is up with <em>this</em> bozo?!” But it’s always about the student, and <em>their</em> needs.</p>\n<p>And I don’t think a student needs a dumb <code>vector</code> replacement.</p>\n<h1>Code review</h1>\n<p>Okay, if you’ve read my view on the concept, you know I think this whole project is fundamentally misguided. That being said, that’s my opinion, and you may disagree. That’s fine. In that case, I’ll review this code under the assumption that you think my philosophy of teaching is wrong, and a dumb <code>vector</code>-lite <em>is</em> a good idea; so I’ll be reviewing the code as-if it’s going to be used for the stated purpose, taking into account all the stated reasoning for it.</p>\n<pre><code>namespace dumb {\n</code></pre>\n<p>Cool, so far. I <em>strongly</em> approve of the use of a namespace, even though that’s something that so many shitty teachers try to avoid talking about (usually by telling students to use <code>using namespace std;</code>, natch). Even if someone wants to try claiming it’s an “advanced” feature, it’s something that can be glossed over trivially by saying “just use <code>dumb::vector</code> instead of <code>vector</code>”.</p>\n<pre><code>class vector\n</code></pre>\n<p>Alright, so I made my position clear in the concept review section, but this isn’t related to that: even assuming that the whole “dumb vector” thing is a good idea, I think you should basically throw <code>dumb::vector</code> out entirely, and just keep <code>dumbestvector</code> (but put <em>that</em> in the namespace and call it <code>dumb::vector</code>).</p>\n<p>Why?</p>\n<p>Well, <code>dumbestvector</code> may be “dumb”… but at least it isn’t <em>wrong</em>.</p>\n<p><em>This</em>…:</p>\n<pre><code>// Copies all the elements in the vector to a larger data allocation.\n// Accessing that extra space is undefined behavior.\n// dumb::vector v;\n// v.reserve(10); // increases capacity to 10\n// for (unsigned int i = 0; i &lt; 10; i++)\n// v.push_back(i); // doesn't keep copying the entire vector on every push_back()\nvoid reserve(unsigned int new_cap)\n{\n if (new_cap &lt;= capacity_)\n return;\n\n value_type* new_data = new value_type[new_cap];\n for (unsigned int i = 0; i &lt; size_; ++i)\n {\n new_data[i] = data_[i];\n }\n\n delete[] data_;\n data_ = new_data;\n capacity_ = new_cap;\n}\n</code></pre>\n<p>… is <em>not</em> how you do capacity.</p>\n<p>The comment is a lie—there is no UB accessing the elements beyond the size but still within the capacity.</p>\n<p>The entire technique is misleading, because you might trick a newbie into thinking that if the size is 10 but the capacity is 20, that there are only 10 elements in the vector. You might confuse a newbie into thinking that <code>new value_type[new_cap]</code> just allocates space, but doesn’t actually initialize the elements in that space… you might deceive them into thinking that initialization doesn’t happen until the <code>new_data[i] = data_[i];</code> line.</p>\n<p>All-in-all, everything about this is just wrong.</p>\n<p>And the worst part is, it’s entirely unnecessary. I mean, if someone isn’t even allowed to use <code>std::vector</code>… if they’re forced to do <em>manual</em> memory management… then they’re hardly in a situation where they’re really in <em>need</em> of extra capacity in their container. So their program will reallocate on every <code>push_back()</code>… so the fuck what? It’ll be slow? </p>\n<p>Hell, most <em>experienced</em> C++ coders don’t even use <code>reserve()</code> as often as they should. I think it’s something a newbie could do without.</p>\n<pre><code>typedef int value_type;\n</code></pre>\n<p>Okay, two things here. First, this should be public, not private.</p>\n<p>Second, you should use the more modern form of type aliasing:</p>\n<pre><code>using value_type = int;\n</code></pre>\n<p>Why? Because it reads more naturally when considered with the rest of the language. One of the first things new C++ programmers have to internalize is that when you see <code>a = b</code>, that means you’re taking what’s on the right, and “assigning it into” what’s on the left. <code>using a = b;</code> fits that pattern beautifully.</p>\n<p>It also works out much more clearly and logically when things start to get more complex. For example, what does <code>typedef a * b;</code> mean? Is a <code>b</code> a pointer to an <code>a</code>, or is a pointer to a <code>b</code> an <code>a</code>? On the other hand: <code>using b = a*;</code> is crystal clear.</p>\n<p>You could include a comment explaining that <code>using value_type = int;</code> is exactly the same thing as <code>typedef int value_type;</code> <em>just in case</em> the shitty teacher introduced <code>typedef</code> but not <code>using</code>. If the teacher introduced just <code>using</code>, or neither <code>typedef</code> or <code>using</code>, this incidental comment shouldn’t do much harm.</p>\n<pre><code>value_type* data_;\nunsigned int size_;\nunsigned int capacity_;\n</code></pre>\n<p>There doesn’t seem to be a good reason not to use member initializers here. Member initializers are one of those things that are <em>really</em> obvious. I mean, if you see:</p>\n<pre><code>struct foo\n{\n int baz = 42;\n int qux = 69;\n};\n</code></pre>\n<p>Even if you don’t know C++ all that well, it’s kinda obvious what those initializers mean.</p>\n<pre><code>unsigned int size_;\nunsigned int capacity_;\n</code></pre>\n<p>You mentioned that you deliberately chose to use <code>unsigned int</code> rather than <code>std::size_t</code>, but never explained why. I assume because you think <code>unsigned int</code> is “dumber” than <code>std::size_t</code>… but I beg to disagree. The moment you do <code>unsigned int</code>, you are going to be peppered with questions like “why <code>unsigned</code>; why not just <code>int</code>? (why not <code>unsigned long</code>, etc. etc.)” which opens a whole can of worms.</p>\n<p>By contrast, <code>std::size_t</code> is just… <em>the</em> type for sizes. Period. It’s what you get when you do <code>sizeof</code>. That doesn’t leave any further questions hanging. It’s a size? Then it’s a <code>std::size_t</code>.</p>\n<pre><code>vector()\n{\n data_ = nullptr;\n size_ = 0;\n capacity_ = 0;\n}\n</code></pre>\n<p>If you use member initializers, this is a good opportunity to do something like this:</p>\n<pre><code>constexpr vector() noexcept = default;\n</code></pre>\n<p>Now, I get that you have an aversion to decorators, but you don’t need to <em>explain</em> them in any great detail:</p>\n<ul>\n<li><strong>Q:</strong> “Why does it say <code>constexpr</code>?”</li>\n<li><strong>A:</strong> “Because you should <em>always</em> use <code>constexpr</code>, unless it won’t compile if you do. It should have been the default, but unfortunately they didn’t think of it until too late.”</li>\n<li><strong>Q:</strong> “What does it do? Do I need it?”</li>\n<li><strong>A:</strong> “It can speed up your program. It’s usually optional, so if you don’t want to use it, that’s fine.”</li>\n</ul>\n<p>And for <code>noexcept</code>:</p>\n<ul>\n<li><strong>A:</strong> “When your function cannot possibly fail, you should mark it <code>noexcept</code>. It’s optional, but it helps both other programmers and the compiler understand that the function is safe to call; it can never fail. Note the constructor that allocates is <em>not</em> marked <code>noexcept</code>, because allocation <em>can</em> fail if you run out of memory.”</li>\n</ul>\n<p>The point I’m getting at is that rather than avoiding complexity, you should use it as a teaching opportunity. Unless the <em>only</em> purpose of <code>dumb::vector</code> is avoiding work, it seems like a good idea to leverage it as an additional teaching tool.</p>\n<p>But even if you don’t want to use the <code>constexpr</code> and the <code>noexcept</code>, the <code>default</code> is still a good idea.</p>\n<pre><code>// This one lets you make a vector of a certain size.\n// All elements are default constructed:\n// dumb::vector v(10);\nvector(unsigned int count)\n{\n data_ = new value_type[count];\n size_ = count;\n capacity_ = count;\n}\n\n// This one lets you make a vector of a certain size.\n// All elements are default constructed, but then assigned value\n// dumb::vector v(10, 1000); // 10 ints all set to value 1000\nvector(unsigned int count, const value_type&amp; value)\n{\n data_ = new value_type[count];\n size_ = count;\n capacity_ = count;\n for (unsigned int i = 0; i &lt; size_; ++i)\n {\n data_[i] = value;\n }\n}\n</code></pre>\n<p>I think you should throw these constructors out. This is getting a bit too clever for a dumb vector.</p>\n<p>Also, you’re opening the door for some <em>MASSIVE</em> confusion when the student discovers that <code>dumb::vector(1, 2)</code> is not the same as <code>dumb::vector{1, 2}</code>.</p>\n<pre><code>vector(const std::initializer_list&lt;value_type&gt;&amp; init_list)\n{\n size_ = init_list.size();\n capacity_ = init_list.size();\n data_ = new value_type[size_];\n auto it = init_list.begin();\n for (unsigned int i = 0; i &lt; size_; ++i)\n {\n data_[i] = *it;\n ++it;\n }\n}\n</code></pre>\n<p>You shouldn’t take <code>std::initializer_list</code> by <code>const&amp;</code>. It’s a view type; it’s meant to be trivial to copy.</p>\n<p>Now, the way you copy the data is a bit of a mess, mixing up iterators and indices, incrementing within the loop and without, using pointers and array-like access. Pick a track and stick to it:</p>\n<pre><code>vector(std::initializer_list&lt;value_type&gt; il)\n{\n // get the size\n size_ = il.size();\n\n // allocate the data\n data_ = new value_type[size_];\n\n // copy the data from the initializer list\n auto p_src = il.begin();\n auto p_end = il.end();\n\n auto p_dest = data_; // p_dest now points to the start of the allocated data space\n\n while (p_src != p_end)\n {\n *p_dest = *p_src;\n\n ++p_src;\n ++p_dest;\n }\n}\n</code></pre>\n<p>The copy constructor is fine, but:</p>\n<pre><code>vector&amp; operator=(const vector&amp; other)\n{\n delete[] data_;\n\n data_ = new value_type[other.size_];\n size_ = other.size_;\n capacity_ = other.size_;\n for (unsigned int i = 0; i &lt; size_; ++i)\n {\n data_[i] = other.data_[i];\n }\n\n return *this;\n}\n</code></pre>\n<p>You don’t check for self-assignment… and it matters here.</p>\n<p>You also don’t illustrate good programming practices. A better solution would be to offer the strong exception guarantee… though of course, you don’t need to explicitly say that’s what you’re doing. Just explain that allocation can fail, so to be safe, you’re not deleting the old data until the new data is ready.</p>\n<pre><code>vector&amp; operator=(const vector&amp; other)\n{\n // allocation can fail, so we allocate to a temporary variable, and make\n // sure everything succeeds before touching this's data members\n auto new_data = new value_type[other.size_];\n\n for (std::size_t i = 0; i &lt; other.size_; ++i)\n new_data[i] = other.data_[i];\n\n // okay, we copied all the data from other into the temporary, so now\n // it's safe to delete the old data from this\n delete[] data_;\n\n // and now we put the new data into this's data members\n data_ = new_data;\n size_ = other.size_;\n\n return *this;\n}\n</code></pre>\n<p>And, for free, you no longer need a self-assignment check.</p>\n<pre><code>// increase capacity if required, and copy the element to the end\nvoid push_back(const value_type&amp; value)\n{\n if (size_ == capacity_)\n {\n reserve(size_ + 1);\n }\n\n data_[size_] = value;\n ++size_;\n}\n\n// removes the last element from the vector. Does not return it.\nvoid pop_back()\n{\n --size_;\n // this overwrites what used to be the last element\n // with a default constructed object of your type\n // essentially deleting what used to be there\n data_[size_] = value_type{};\n}\n</code></pre>\n<p>You’re gonna need a resize function to make these work, but that’s handy in any case, because it’s an easily-understood pattern to resize a vector to a certain size, then fill it with a loop and <code>operator[]</code>.</p>\n<pre><code>auto resize(std::size_t new_size)\n{\n // allocation can fail, so we allocate to a temporary variable, and make\n // sure everything succeeds before touching this's data members\n auto new_data = new value_type[new_size];\n\n // blah blah explain here that we need to handle the case where the new\n // size is larger *and* the case where the new size is smaller\n //\n // if std::min() is verbotten, using a ternary expression is probably too\n // advanced, so you should use an if-else, with one branch for when the\n // new size is smaller - that's repetitive, but, meh, this is a dumb\n // class, after all\n auto num_to_copy = std::min(new_size, size_); // can we use std::min?\n\n for (std::size_t i = 0; i &lt; num_to_copy; ++i)\n new_data[i] = data_[i];\n\n // okay, we copied all the data from this into the temporary, so now\n // it's safe to delete the old data from this\n delete[] data_;\n\n // and now we put the new data into this's data members\n data_ = new_data;\n size_ = new_size;\n}\n\nauto push_back(value_type const&amp; v)\n{\n resize(size_ + 1);\n data_[size_ - 1] = v;\n}\n\nauto pop_back()\n{\n resize(size_ - 1);\n}\n</code></pre>\n<p>You can decide whether it’s worth it to add the complexity of an <code>if</code> to test whether <code>new_size == size_</code>. I wouldn’t bother, considering what this is for.</p>\n<pre><code>// increases capacity if required, inserts a copy of the element at the chosen index\nvalue_type* insert(unsigned int pos, const value_type&amp; value)\n{\n if (size_ == capacity_)\n {\n reserve(size_ + 1);\n }\n\n for (unsigned int i = size_; i &gt; pos; --i)\n {\n data_[i] = data_[i - 1];\n }\n\n data_[pos] = value;\n ++size_;\n\n return data_ + pos;\n}\n\n// copies every element above pos down a slot\nvalue_type* erase(unsigned int pos)\n{\n --size_;\n unsigned int i;\n for (i = pos; i &lt; size_; ++i)\n {\n data_[i] = data_[i + 1];\n }\n // this overwrites what used to be the last element\n // with a default constructed object of your type\n // essentially deleting what used to be there\n data_[i] = value_type{};\n\n return data_ + pos;\n}\n</code></pre>\n<p>These functions aren’t in <code>std::vector</code>’s interface. And they’re not worth the complexity. Dump ’em.</p>\n<pre><code>// Copies all the elements in the vector to a larger data allocation.\n// Accessing that extra space is undefined behavior.\n// dumb::vector v;\n// v.reserve(10); // increases capacity to 10\n// for (unsigned int i = 0; i &lt; 10; i++)\n// v.push_back(i); // doesn't keep copying the entire vector on every push_back()\nvoid reserve(unsigned int new_cap)\n{\n if (new_cap &lt;= capacity_)\n return;\n\n value_type* new_data = new value_type[new_cap];\n for (unsigned int i = 0; i &lt; size_; ++i)\n {\n new_data[i] = data_[i];\n }\n\n delete[] data_;\n data_ = new_data;\n capacity_ = new_cap;\n}\n</code></pre>\n<p>Dump this with prejudice.</p>\n<pre><code>// acts as an iterator so you can use iterator loops\n// and range-based for loops\n// for (auto i = v.begin(); i != v.end(); i++)\n// func(*i);\n// for (auto i : v)\n// func(i);\nvalue_type* begin()\n{\n return data_;\n}\n\n// same as above\nvalue_type* end()\n{\n return data_ + size_;\n}\n</code></pre>\n<p>If you’re going to do this, lean into it. Define aliases for <code>iterator</code> and <code>const_iterator</code>, and define both versions of both functions. Seriously, the amount of complexity that adds is so minimal, and the benefits of the learner making the mental connection between pointers and iterators is so worth it.</p>\n<p>(I also think you should add <code>const</code> versions of <code>data()</code> and <code>operator[]</code>.)</p>\n<p>I would suggest adding three more functions to this interface:</p>\n<ul>\n<li><code>at()</code></li>\n<li><code>clear()</code></li>\n<li><code>operator==</code></li>\n</ul>\n<p><code>at()</code> is useful for bounds-checking… something a newbie is very likely to want to do.</p>\n<p><code>clear()</code> is generally useful because some algorithms require occasionally discarding all data. Plus it allows reusing vectors easily.</p>\n<p><code>operator&lt;=&gt;</code> seems a bit much—it’s generally unnecessary (I don’t often see people wanting to order vectors), and it opens up <em>WAY</em> too many questions. But <code>operator==</code> is a neat demo function:</p>\n<pre><code>constexpr auto operator==(vector const&amp; other) const noexcept -&gt; bool\n{\n // if the sizes are different, the vectors can't possibly be equal\n if (size_ != other.size_)\n return false;\n\n // go through both vectors' data arrays, and if there are any mismatches,\n // then the vectors aren't equal\n for (std::size_t i = 0; i &lt; _size ++i)\n {\n if (data_[i] != other.data_[i])\n return false;\n }\n\n // the sizes are the same, and all the elements match, so these vectors\n // are equal\n return true;\n}\n</code></pre>\n<p>And that’s about it. Everything that applies to <code>dumb::vector</code> also applies to <code>dumbestvector</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-24T14:44:42.937", "Id": "503394", "Score": "0", "body": "Appreciate the review. Very long, so it must be good. I'm just curious how this answer got several upvotes in only two days. Did this question show up on hot network or did you post it to your blog or something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-24T18:14:00.917", "Id": "503408", "Score": "0", "body": " I don’t think I did anything special. I don’t really pay much attention to votes anyway." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-22T03:16:38.267", "Id": "255073", "ParentId": "240409", "Score": "6" } } ]
{ "AcceptedAnswerId": "255073", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T17:57:53.037", "Id": "240409", "Score": "2", "Tags": [ "c++", "memory-management", "vectors" ], "Title": "dumb::vector - a class for students to use when they are expressly forbidden from using std::vector" }
240409
<p>I have been using this quarantine time to learn "Modern C++" (constructs, move semantics, smart pointers, etc, etc) via implementing basic data structures from scratch. As a first step, I've put together a simple (but, hopefully somewhat complete) linked list as one of the foundational pieces.</p> <h2>linked_list.h</h2> <pre><code>#pragma once #include &lt;utility&gt; namespace data_structures { template&lt;typename T&gt; class linked_list { template&lt;typename T&gt; struct list_node { friend linked_list; typedef list_node&lt;T&gt; self_type; typedef list_node&lt;T&gt;&amp; reference; typedef const list_node&lt;T&gt;&amp; const_reference; typedef list_node&lt;T&gt;* pointer; explicit list_node( const T&amp; val ) : data{ std::move( val ) } { } explicit list_node( const T&amp;&amp; val ) : data{ std::move( val ) } { } T data; private: pointer next_ = nullptr, prev_ = nullptr; }; class iterator { public: using node = list_node&lt;T&gt;; typedef iterator self_type; typedef node&amp; reference; typedef node* pointer; explicit iterator( pointer node ) : ptr_( node ) { } self_type operator++() { if( ptr_ ) ptr_ = ptr_-&gt;next_; return *this; } reference operator*() { return *ptr_; } pointer operator-&gt;() { return ptr_; } bool operator==( const self_type&amp; other ) { return ptr_ == other.ptr_; } bool operator!=( const self_type&amp; other ) { return ptr_ != other.ptr_; } private: pointer ptr_; }; typedef linked_list&lt;T&gt; self_type; typedef linked_list&lt;T&gt;&amp; reference; typedef const linked_list&lt;T&gt;&amp; const_reference; typedef linked_list&lt;T&gt;* pointer; typedef size_t size_type; typedef list_node&lt;T&gt; node_type; using node = typename node_type::pointer; using node_reference = typename node_type::reference; using const_node_reference = typename node_type::const_reference; using node_pointer = std::unique_ptr&lt;node_type&gt;; node_pointer head_, tail_; size_t length_{}; public: linked_list(); explicit linked_list( std::initializer_list&lt;T&gt; init_list ); linked_list( const self_type&amp; other ); linked_list( self_type&amp;&amp; other ) noexcept; ~linked_list(); void swap( reference other ) noexcept; void push_back( T item ) { insert( length_, item ); } void push_front( T item ) { insert( 0, item ); } void append( const_reference other ); T pop_front(); T pop_back(); const_node_reference at( size_type position ); void remove( T value ); void remove_at( size_type position ); iterator begin() { return iterator( head_-&gt;next_ ); } iterator end() { return iterator( tail_.get() ); } [[nodiscard]] const_node_reference front() const { return *head_-&gt;next_; } [[nodiscard]] const_node_reference back() const { return *tail_-&gt;prev_; } [[nodiscard]] bool empty() const { return head_-&gt;next == tail_.get(); } [[nodiscard]] size_type size() const { return length_; } reference operator=( const self_type&amp; other ); // NOLINT(cppcoreguidelines-c-copy-assignment-signature, misc-unconventional-assign-operator) reference operator=( self_type&amp;&amp; other ) noexcept; // NOLINT(cppcoreguidelines-c-copy-assignment-signature, misc-unconventional-assign-operator) reference operator+( const self_type&amp; other ) { append( other ); return *this; } void operator+=( const self_type&amp; other ) { append( other ); } void operator+=( const T&amp; value ) { push_back( value ); } protected: void insert( size_type position, T value ); node get( size_type position ); }; template &lt;typename T&gt; linked_list&lt;T&gt;::linked_list() { head_ = std::make_unique&lt;node_type&gt;( T() ); tail_ = std::make_unique&lt;node_type&gt;( T() ); head_-&gt;next_ = tail_.get(); head_-&gt;prev_ = tail_.get(); tail_-&gt;next_ = head_.get(); tail_-&gt;prev_ = head_.get(); } template &lt;typename T&gt; linked_list&lt;T&gt;::linked_list( const std::initializer_list&lt;T&gt; init_list ) : linked_list() { for( auto&amp; item : init_list ) { push_back( item ); } } template &lt;typename T&gt; linked_list&lt;T&gt;::linked_list( const self_type&amp; other ) : linked_list() { append( other ); } template &lt;typename T&gt; linked_list&lt;T&gt;::linked_list( self_type&amp;&amp; other ) noexcept : linked_list() { swap( other ); } template &lt;typename T&gt; linked_list&lt;T&gt;::~linked_list() { if( !head_ ) return; // destroyed from move for( node current = head_-&gt;next_; current != tail_.get(); ) { node temp = current; current = current-&gt;next_; delete temp; } } template &lt;typename T&gt; // NOLINT(cppcoreguidelines-c-copy-assignment-signature typename linked_list&lt;T&gt;::reference linked_list&lt;T&gt;::operator=( const self_type&amp; other ) // NOLINT(cppcoreguidelines-c-copy-assignment-signature, misc-unconventional-assign-operator) { if( this == &amp;other ) return *this; auto temp( other ); temp.swap( *this ); return *this; } template &lt;typename T&gt; // NOLINT(cppcoreguidelines-c-copy-assignment-signature typename linked_list&lt;T&gt;::reference linked_list&lt;T&gt;::operator=( self_type&amp;&amp; other ) noexcept // NOLINT(cppcoreguidelines-c-copy-assignment-signature, misc-unconventional-assign-operator) { if( this == &amp;other ) return *this; // clean up this for( node current = head_-&gt;next_; current != tail_.get(); ) { node temp = current; current = current-&gt;next_; delete temp; length_--; } // this &lt;- other head_ = std::move( other.head_ ); tail_ = std::move( other.tail_ ); length_ = other.length_; other.length_ = 0; return *this; } template &lt;typename T&gt; void linked_list&lt;T&gt;::swap( reference other ) noexcept { std::swap( head_, other.head_ ); std::swap( tail_, other.tail_ ); std::swap( length_, other.length_ ); } template &lt;typename T&gt; void linked_list&lt;T&gt;::append( const_reference other ) { node dest = tail_-&gt;prev_; for( node source = other.head_-&gt;next_; source != other.tail_.get(); source = source-&gt;next_ ) { node new_node{ new node_type( source-&gt;data ) }; if( new_node == nullptr ) throw std::bad_alloc(); new_node-&gt;prev_ = dest; dest-&gt;next_ = new_node; dest = new_node; length_++; } dest-&gt;next_ = tail_.get(); tail_-&gt;prev_ = dest; } template &lt;typename T&gt; T linked_list&lt;T&gt;::pop_front() { if( length_ &lt;= 0 ) throw std::runtime_error( "ATTEMPT_POP_EMPTY_LIST" ); const auto value = front().data; remove_at( 0 ); return value; } template &lt;typename T&gt; T linked_list&lt;T&gt;::pop_back() { if( length_ &lt;= 0 ) throw std::runtime_error( "ATTEMPT_POP_EMPTY_LIST" ); const auto value = back().data; remove_at( length_ - 1 ); return value; } template &lt;typename T&gt; typename linked_list&lt;T&gt;::const_node_reference linked_list&lt;T&gt;::at( size_type position ) { if( position &gt;= length_ ) throw std::runtime_error( "INVALID_LIST_POSITION" ); return *get( position ); } template &lt;typename T&gt; void linked_list&lt;T&gt;::insert( const size_type position, T value ) { if( position &gt; length_ + 1) throw std::runtime_error( "INVALID_LIST_POSITION" ); node next = get( position ); node new_node{ new node_type( value ) }; if( new_node == nullptr ) throw std::bad_alloc(); node prev = next-&gt;prev_; new_node-&gt;next_ = next; new_node-&gt;prev_ = prev; prev-&gt;next_ = new_node; next-&gt;prev_ = new_node; length_++; } template &lt;typename T&gt; typename linked_list&lt;T&gt;::node linked_list&lt;T&gt;::get( const size_type position ) { const auto mid = ceil( length_ / 2 ); node node; if( position &lt;= mid ) { node = head_-&gt;next_; for( size_type index = 0; index &lt; position; index++ ) node = node-&gt;next_; } else { node = tail_.get(); for( size_type index = length_; index &gt; position; index-- ) node = node-&gt;prev_; } return node; } template &lt;typename T&gt; void linked_list&lt;T&gt;::remove( T value ) { for( node node = head_-&gt;next_; node != tail_.get(); node = node-&gt;next_ ) { if( node-&gt;data == value ) { node-&gt;prev_-&gt;next_ = node-&gt;next_; node-&gt;next_-&gt;prev_ = node-&gt;prev_; delete node; length_--; break; } } } template &lt;typename T&gt; void linked_list&lt;T&gt;::remove_at( const size_type position ) { if( position &gt;= length_ ) throw std::runtime_error( "REMOVE_PAST_END_ATTEMPT" ); node node = get( position ); node-&gt;prev_-&gt;next_ = node-&gt;next_; node-&gt;next_-&gt;prev_ = node-&gt;prev_; delete node; length_--; } } </code></pre> <p>A few notes:</p> <p>The use of smart pointers for the sentinel nodes and not the actual list contents seemed to be the best trade-off in terms of code readability &amp; design. I have refactored this a few times (from a singly using all <code>unique_ptr</code>'s, to a double using a <code>unique_ptr</code> for the head/next node and standard references to the tail/prev node, to this current version). Happy to hear any suggestions here.</p> <p>The move semantics for the list itself I am not completely in love with. For example, when initializing a new list from an existing one using <code>std::move</code> the old list will no longer have valid sentinel nodes as they have been 'reclaimed' by the new list, so the old one is now 'invalid' and the deconstructor has a fail-safe check to not clean itself up if this is the case. From reading how this <em>should</em> be implemented (the move'd object should still valid post-move, just in an 'invalid' state), I believe what I have is correct although it just seems suboptimal.</p> <p>The iterator implementation I have doesn't include a <code>const</code> version as from what I have been reading (or, at least my interpretation I should say) is that is no longer 'best practice' to implement a const version of the iterator &amp; <code>cbegin</code>/<code>cend</code>, and instead the consumer should use const correct iterators? (i.e., '<code>for(const auto&amp; i : list )</code>' in C++ 17+. Is my interpretation correct here?</p> <p>Any and all other suggestions for improvement/functionality/readability/etc welcomed.</p> <p>There is also a set of unit tests (<code>GTest</code>) if anyone is interested.</p> <h2>linkedlist_test.cpp</h2> <pre><code>#include "pch.h" #include &lt;gtest/gtest.h&gt; #include "../data-structures/linked_list.h" namespace data_structure_tests::integer_linked_list_tests { typedef data_structures::linked_list&lt;int&gt; int_list; /// &lt;summary&gt; /// Testing class for singly linked list. /// &lt;/summary&gt; class linked_list_tests : public ::testing::Test { protected: void SetUp() override { } void TearDown() override { } }; // // Linked List Tests // TEST_F( linked_list_tests, at_head ) { auto list = int_list{ 1, 2, 3 }; EXPECT_EQ( list.size(), 3 ); auto actual = list.at( 0 ); EXPECT_EQ( actual.data, 1 ); } TEST_F( linked_list_tests, at_tail ) { auto list = int_list{ 1, 2, 3 }; EXPECT_EQ( list.size(), 3 ); auto actual = list.at( 2 ); EXPECT_EQ( actual.data, 3 ); } TEST_F( linked_list_tests, get_head ) { auto list = int_list{ 1, 2, 3 }; EXPECT_EQ( list.size(), 3 ); auto actual = list.at( 0 ); EXPECT_EQ( actual.data, 1 ); } TEST_F( linked_list_tests, push_front_empty ) { auto list = int_list{ }; EXPECT_EQ( list.size(), 0 ); list.push_back( 1 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 1 ); } TEST_F( linked_list_tests, push_back ) { auto list = int_list{ }; EXPECT_EQ( list.size(), 0 ); list.push_back( 3 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.front().data, 3 ); EXPECT_EQ( list.back().data, 3 ); list.push_back( 2 ); EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.front().data, 3 ); EXPECT_EQ( list.back().data, 2 ); list.push_back( 1 ); EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.front().data, 3 ); EXPECT_EQ( list.back().data, 1 ); } TEST_F( linked_list_tests, push_front ) { auto list = int_list{ }; EXPECT_EQ( list.size(), 0 ); list.push_front( 3 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.front().data, 3 ); EXPECT_EQ( list.back().data, 3 ); list.push_front( 2 ); EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.front().data, 2 ); EXPECT_EQ( list.back().data, 3 ); list.push_front( 1 ); EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 3 ); } TEST_F( linked_list_tests, init_list ) { auto list = int_list{ 5, 4, 3, 2, 1 }; EXPECT_EQ( list.size(), 5 ); EXPECT_EQ( list.front().data, 5 ); EXPECT_EQ( list.back().data, 1 ); EXPECT_EQ( list.at( 4 ).data, 1 ); EXPECT_EQ( list.at( 3 ).data, 2 ); EXPECT_EQ( list.at( 2 ).data, 3 ); EXPECT_EQ( list.at( 1 ).data, 4 ); EXPECT_EQ( list.at( 0 ).data, 5 ); } TEST_F( linked_list_tests, out_of_bounds ) { auto list = int_list{ 1, 2, 3, 4 }; try { auto no_exist = list.at( 4 ); FAIL() &lt;&lt; "This should throw an error."; } catch( std::runtime_error&amp; e ) { EXPECT_EQ( std::string( e.what() ), "INVALID_LIST_POSITION" ); } } TEST_F( linked_list_tests, iterator ) { auto list = int_list{ 0, 1, 2, 3, 4, 5 }; auto expected = 0; for( const auto&amp; node : list ) { auto actual = node.data; EXPECT_EQ( actual, expected ); expected++; } } TEST_F( linked_list_tests, add_lists ) { auto list1 = int_list{ 0, 1, 2, 3, 4 }; const auto list2 = int_list{ 5, 6, 7, 8, 9 }; list1 = list1 + list2; auto expected = 0; for( const auto&amp; node : list1 ) { auto actual = node.data; EXPECT_EQ( actual, expected ); expected++; } } TEST_F( linked_list_tests, append_value ) { auto list = int_list{ 0, 1, 2 }; EXPECT_EQ( list.size(), 3 ); list += 3; EXPECT_EQ( list.size(), 4 ); EXPECT_EQ( list.back().data, 3 ); EXPECT_EQ( list.at( 0 ).data, 0 ); EXPECT_EQ( list.at( 1 ).data, 1 ); EXPECT_EQ( list.at( 2 ).data, 2 ); EXPECT_EQ( list.at( 3 ).data, 3 ); } TEST_F( linked_list_tests, swap ) { auto list1 = int_list{ 1, 2, 3 }; auto list2 = int_list{ 4, 5, 6 }; EXPECT_EQ( list1.size(), 3 ); EXPECT_EQ( list2.size(), 3 ); list1.swap( list2 ); EXPECT_EQ( list1.size(), 3 ); EXPECT_EQ( list2.size(), 3 ); EXPECT_EQ( list1.at( 0 ).data, 4 ); EXPECT_EQ( list1.at( 1 ).data, 5 ); EXPECT_EQ( list1.at( 2 ).data, 6 ); EXPECT_EQ( list2.at( 0 ).data, 1 ); EXPECT_EQ( list2.at( 1 ).data, 2 ); EXPECT_EQ( list2.at( 2 ).data, 3 ); } TEST_F( linked_list_tests, copy_constructor ) { auto list = int_list{ 0, 1, 2 }; EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.at( 0 ).data, 0 ); EXPECT_EQ( list.at( 1 ).data, 1 ); EXPECT_EQ( list.at( 2 ).data, 2 ); auto list_copy( list ); EXPECT_EQ( list_copy.size(), 3 ); EXPECT_EQ( list_copy.at( 0 ).data, 0 ); EXPECT_EQ( list_copy.at( 1 ).data, 1 ); EXPECT_EQ( list_copy.at( 2 ).data, 2 ); list_copy.push_back( 4 ); EXPECT_EQ( list_copy.back().data, 4 ); EXPECT_NE( list.back().data, list_copy.back().data ); } TEST_F( linked_list_tests, copy_assignment_equal ) { auto list1 = int_list{ 0, 1, 2 }; EXPECT_EQ( list1.size(), 3 ); EXPECT_EQ( list1.at( 0 ).data, 0 ); EXPECT_EQ( list1.at( 1 ).data, 1 ); EXPECT_EQ( list1.at( 2 ).data, 2 ); auto list2 = int_list{ 3, 4, 5 }; EXPECT_EQ( list2.size(), 3 ); list2 = list1; EXPECT_EQ( list1.size(), 3 ); EXPECT_EQ( list1.at( 0 ).data, 0 ); EXPECT_EQ( list1.at( 1 ).data, 1 ); EXPECT_EQ( list1.at( 2 ).data, 2 ); EXPECT_EQ( list2.size(), 3 ); EXPECT_EQ( list2.at( 0 ).data, 0 ); EXPECT_EQ( list2.at( 1 ).data, 1 ); EXPECT_EQ( list2.at( 2 ).data, 2 ); } TEST_F( linked_list_tests, self_copy ) { auto list1 = int_list{ 0, 1, 2 }; EXPECT_EQ( list1.size(), 3 ); EXPECT_EQ( list1.at( 0 ).data, 0 ); EXPECT_EQ( list1.at( 1 ).data, 1 ); EXPECT_EQ( list1.at( 2 ).data, 2 ); list1 = list1; EXPECT_EQ( list1.size(), 3 ); EXPECT_EQ( list1.at( 0 ).data, 0 ); EXPECT_EQ( list1.at( 1 ).data, 1 ); EXPECT_EQ( list1.at( 2 ).data, 2 ); } TEST_F( linked_list_tests, move_assignment_operator ) { auto list1 = int_list{ 1, 2, 3 }; EXPECT_EQ( list1.size(), 3 ); EXPECT_EQ( list1.at( 0 ).data, 1 ); EXPECT_EQ( list1.at( 1 ).data, 2 ); EXPECT_EQ( list1.at( 2 ).data, 3 ); auto list2 = int_list{ 4, 5, 6 }; EXPECT_EQ( list2.size(), 3 ); EXPECT_EQ( list2.at( 0 ).data, 4 ); EXPECT_EQ( list2.at( 1 ).data, 5 ); EXPECT_EQ( list2.at( 2 ).data, 6 ); list2 = std::move( list1 ); // list1 = invalid state EXPECT_EQ( list1.size(), 0 ); // NOLINT(bugprone-use-after-move, hicpp-invalid-access-moved) EXPECT_EQ( list2.size(), 3 ); EXPECT_EQ( list2.at( 0 ).data, 1 ); EXPECT_EQ( list2.at( 1 ).data, 2 ); EXPECT_EQ( list2.at( 2 ).data, 3 ); } TEST_F( linked_list_tests, move_constructor ) { auto list1 = int_list{ 1, 2, 3, 4, 5 }; EXPECT_EQ( list1.size(), 5 ); EXPECT_EQ( list1.at( 0 ).data, 1 ); EXPECT_EQ( list1.at( 1 ).data, 2 ); EXPECT_EQ( list1.at( 2 ).data, 3 ); EXPECT_EQ( list1.at( 3 ).data, 4 ); EXPECT_EQ( list1.at( 4 ).data, 5 ); auto list2 = std::move( list1 ); // list1 = invalid state EXPECT_EQ( list1.size(), 0 ); // NOLINT(bugprone-use-after-move, hicpp-invalid-access-moved) EXPECT_EQ( list2.size(), 5 ); EXPECT_EQ( list2.at( 0 ).data, 1 ); EXPECT_EQ( list2.at( 1 ).data, 2 ); EXPECT_EQ( list2.at( 2 ).data, 3 ); EXPECT_EQ( list2.at( 3 ).data, 4 ); EXPECT_EQ( list2.at( 4 ).data, 5 ); } TEST_F( linked_list_tests, move_constructor_copy ) { auto outer = int_list(); { auto inner = int_list{ 1, 2, 3, 4, 5 }; EXPECT_EQ( inner.size(), 5 ); EXPECT_EQ( inner.at( 0 ).data, 1 ); EXPECT_EQ( inner.at( 1 ).data, 2 ); EXPECT_EQ( inner.at( 2 ).data, 3 ); EXPECT_EQ( inner.at( 3 ).data, 4 ); EXPECT_EQ( inner.at( 4 ).data, 5 ); outer = std::move( inner ); } EXPECT_EQ( outer.size(), 5 ); EXPECT_EQ( outer.at( 0 ).data, 1 ); EXPECT_EQ( outer.at( 1 ).data, 2 ); EXPECT_EQ( outer.at( 2 ).data, 3 ); EXPECT_EQ( outer.at( 3 ).data, 4 ); EXPECT_EQ( outer.at( 4 ).data, 5 ); } TEST_F( linked_list_tests, empty_insert_delete ) { auto list = int_list{ }; EXPECT_EQ( list.size(), 0 ); list.push_back( 1 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 1 ); list.remove_at( 0 ); EXPECT_EQ( list.size(), 0 ); } TEST_F( linked_list_tests, remove_single ) { auto list = int_list{ 1 }; EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 1 ); list.remove( 1 ); EXPECT_EQ( list.size(), 0 ); } TEST_F( linked_list_tests, remove_head_double ) { auto list = int_list{ 1, 2 }; EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 2 ); list.remove( 1 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.front().data, 2 ); EXPECT_EQ( list.back().data, 2 ); } TEST_F( linked_list_tests, remove_tail_double ) { auto list = int_list{ 1, 2 }; EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 2 ); list.remove( 2 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 1 ); } TEST_F( linked_list_tests, remove_head_triple ) { auto list = int_list{ 1, 2, 3 }; EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.at( 0 ).data, 1 ); EXPECT_EQ( list.at( 1 ).data, 2 ); EXPECT_EQ( list.at( 2 ).data, 3 ); list.remove_at( 0 ); EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.at( 0 ).data, 2 ); EXPECT_EQ( list.at( 1 ).data, 3 ); } TEST_F( linked_list_tests, remove_past_end ) { auto list = int_list{ 1, 2, 3 }; EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.at( 0 ).data, 1 ); EXPECT_EQ( list.at( 1 ).data, 2 ); EXPECT_EQ( list.at( 2 ).data, 3 ); try { list.remove_at( 3 ); FAIL() &lt;&lt; "This should throw an error."; } catch( std::runtime_error&amp; e ) { EXPECT_EQ( std::string( e.what() ), "REMOVE_PAST_END_ATTEMPT" ); } EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.at( 0 ).data, 1 ); EXPECT_EQ( list.at( 1 ).data, 2 ); EXPECT_EQ( list.at( 2 ).data, 3 ); } TEST_F( linked_list_tests, remove_tail_triple ) { auto list = int_list{ 1, 2, 3 }; EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.at( 0 ).data, 1 ); EXPECT_EQ( list.at( 1 ).data, 2 ); EXPECT_EQ( list.at( 2 ).data, 3 ); list.remove_at( 2 ); EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.at( 0 ).data, 1 ); EXPECT_EQ( list.at( 1 ).data, 2 ); EXPECT_EQ( list.back().data, 2 ); } TEST_F( linked_list_tests, remove_middle ) { auto list = int_list{ 1, 2, 3, 4, 5, 6 }; EXPECT_EQ( list.size(), 6 ); EXPECT_EQ( list.at( 0 ).data, 1 ); EXPECT_EQ( list.at( 1 ).data, 2 ); EXPECT_EQ( list.at( 2 ).data, 3 ); EXPECT_EQ( list.at( 3 ).data, 4 ); EXPECT_EQ( list.at( 4 ).data, 5 ); EXPECT_EQ( list.at( 5 ).data, 6 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 6 ); list.remove_at( 4 ); EXPECT_EQ( list.size(), 5 ); EXPECT_EQ( list.at( 0 ).data, 1 ); EXPECT_EQ( list.at( 1 ).data, 2 ); EXPECT_EQ( list.at( 2 ).data, 3 ); EXPECT_EQ( list.at( 3 ).data, 4 ); EXPECT_EQ( list.at( 4 ).data, 6 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 6 ); list.remove_at( 3 ); EXPECT_EQ( list.size(), 4 ); EXPECT_EQ( list.at( 0 ).data, 1 ); EXPECT_EQ( list.at( 1 ).data, 2 ); EXPECT_EQ( list.at( 2 ).data, 3 ); EXPECT_EQ( list.at( 3 ).data, 6 ); EXPECT_EQ( list.front().data, 1 ); EXPECT_EQ( list.back().data, 6 ); list.remove_at( 0 ); EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.at( 0 ).data, 2 ); EXPECT_EQ( list.at( 1 ).data, 3 ); EXPECT_EQ( list.at( 2 ).data, 6 ); EXPECT_EQ( list.front().data, 2 ); EXPECT_EQ( list.back().data, 6 ); list.remove_at( 2 ); EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.at( 0 ).data, 2 ); EXPECT_EQ( list.at( 1 ).data, 3 ); EXPECT_EQ( list.front().data, 2 ); EXPECT_EQ( list.back().data, 3 ); list.remove_at( 1 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.at( 0 ).data, 2 ); EXPECT_EQ( list.front().data, 2 ); EXPECT_EQ( list.back().data, 2 ); list.remove_at( 0 ); EXPECT_EQ( list.size(), 0 ); EXPECT_EQ( list.front().data, 0 ); EXPECT_EQ( list.back().data, 0 ); } TEST_F( linked_list_tests, pop_front_empty ) { auto list = int_list{}; try { list.pop_back(); FAIL() &lt;&lt; "This should throw an error."; } catch( std::runtime_error&amp; e ) { EXPECT_EQ( std::string( e.what() ), "ATTEMPT_POP_EMPTY_LIST" ); } } TEST_F( linked_list_tests, pop_back_empty ) { auto list = int_list{}; try { list.pop_back(); FAIL() &lt;&lt; "This should throw an error."; } catch( std::runtime_error&amp; e ) { EXPECT_EQ( std::string( e.what() ), "ATTEMPT_POP_EMPTY_LIST" ); } } TEST_F( linked_list_tests, pop_front ) { auto list = int_list{ 1, 2, 3 }; EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.pop_front(), 1 ); EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.pop_front(), 2 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.pop_front(), 3 ); EXPECT_EQ( list.size(), 0 ); } TEST_F( linked_list_tests, pop_back ) { auto list = int_list{ 1, 2, 3 }; EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.pop_back(), 3 ); EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.pop_back(), 2 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.pop_back(), 1 ); EXPECT_EQ( list.size(), 0 ); } TEST_F( linked_list_tests, pop_alt ) { auto list = int_list{ 1, 2, 3, 4, 5 }; EXPECT_EQ( list.size(), 5 ); EXPECT_EQ( list.pop_front(), 1 ); EXPECT_EQ( list.size(), 4 ); EXPECT_EQ( list.pop_back(), 5 ); EXPECT_EQ( list.size(), 3 ); EXPECT_EQ( list.pop_front(), 2 ); EXPECT_EQ( list.size(), 2 ); EXPECT_EQ( list.pop_back(), 4 ); EXPECT_EQ( list.size(), 1 ); EXPECT_EQ( list.pop_front(), 3 ); EXPECT_EQ( list.size(), 0 ); } TEST_F( linked_list_tests, find_element ) { auto list = int_list{ 1, 2, 3, 4, 5 }; const auto to_find = 3; auto actual = std::find_if(list.begin(), list.end(), [&amp;]( const auto&amp; node ) { return node.data == to_find; }); EXPECT_TRUE( actual != std::end( list ) ); EXPECT_EQ( actual-&gt;data, to_find ); } TEST_F( linked_list_tests, no_find_element ) { auto list = int_list{ 1, 2, 3, 4, 5 }; const auto to_find = 6; auto actual = std::find_if( list.begin(), list.end(), [&amp;]( const auto&amp; node ) { return node.data == to_find; } ); EXPECT_TRUE( actual == std::end( list ) ); } } </code></pre>
[]
[ { "body": "<p>The code is pretty good, but there are some parts of it that aren't intuitive enough to be readed cleverly.</p>\n<p>Don't misunderstand me, your design is good, but it is quite complex to be seen through properly. Have in account:</p>\n<blockquote>\n<p>Our main goal is to be meaningful building the simplest.</p>\n</blockquote>\n<p>Think of it as a martial artist, be efficient with the minimum movement. Emphatically, this allow us to make better systems and extend them.</p>\n<h3>The Good:</h3>\n<ul>\n<li>Modern features added to the implementation, which brings optimization.</li>\n<li>Non use of macros (it is better to avoid them)</li>\n<li>Non use of <code>using namespace</code></li>\n<li>Use of exceptions when needed (essential when working with data structures)</li>\n</ul>\n<h3>Code Review:</h3>\n<ul>\n<li>If you are writing a data structures project, you will find that dynamic data structures needs common linking components. In example a queue or a stack will use a Singly Linked Node or if you want a Doubly Linked Node. So, you could define list_node in other file. Commonly you will want to have classes and structures separated in distinct files.</li>\n<li>Struct properties are public by default you really don't need to make your <code>linked_list</code> a friend class of <code>list_node</code></li>\n<li>Do not use typedef so frecuently, it makes the code quite messy. when you do this you hide the type and if the new typedef isn't descriptive enough it will cause trouble both reading and debuggin the code.</li>\n<li>Be consistent with naming, I saw a field called ptr_ so you should use the _ suffix.</li>\n<li>The best of a struct is to easily handle its members because they are public think of it, the implementation normally hide the nodes (should).</li>\n<li>Your implementations of data structures should not return node objects.</li>\n</ul>\n<h3>Some comments:</h3>\n<p>It is interesting the way you are reinventing the wheel, normally some people says things like &quot;we do not need to reinvent the wheel, since it is done why...&quot; and so, but think of it, what tire manufacturers are doing in this moment. Well passing the discussion, the answer is simple, <em>you always need something better.</em></p>\n<p>I recommend you the following <a href=\"https://google.github.io/styleguide/cppguide.html\" rel=\"nofollow noreferrer\">Google C++ Style Guide</a> which is something good to familiarize with. This is an standard for coding C++ elaborated by Google (if you don't have a standard you already follow)</p>\n<p>Finally. Hope that my answer were of you like and helped you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:57:51.993", "Id": "471577", "Score": "0", "body": "As mentioned before, provide specific observations about the code, and provide specific references. The good bullet points are fine, what are possible issues in the code, they should be bullet points, not rewriting the posters code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:26:29.927", "Id": "471625", "Score": "1", "body": "I see your point, you mean simplify the answer so that it be easy and fast to read ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:53:05.040", "Id": "471636", "Score": "1", "body": "Much better, you can include code as examples of your points, but don't rewrite the entire solution." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T21:34:59.813", "Id": "240418", "ParentId": "240412", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T19:13:01.077", "Id": "240412", "Score": "2", "Tags": [ "c++", "linked-list", "reinventing-the-wheel", "c++17" ], "Title": "Modern C++ Linked List" }
240412
<p>Today I learnt the basics of OOP. I have tried to apply them to this coffee machine project. However I'm still a <em>beginner</em>, and so I feel my code can be improved. Are there any tips, trick or other other advice I can follow to improve the look, runtime, readability or take full advantage of OOP?</p> <p>This code is simulating a coffee machine which asks for 4 different actions; buy, fill, remaining, and exit.</p> <p>When you enter buy, the program asks you which type of coffee you want. Here you can enter 1, 2, 3 or back - if you change your mind about getting coffee. Each coffee has different requirements for the supplies it needs to make a coffee. If there are not enough supplies available, in the coffee machine, then no coffee is made and a prompt appears. If there are enough supplies, the requirements for your selected coffee get deducted from the supplies available and a prompt showing it was successful appears.</p> <p>The function fill allows you to add to the supplies in the <code>CoffeeMachine</code> class.</p> <p>Remaining display the current quantities of supplies for each of the materials in the coffee machine. Such as water, milk, coffee beans, cups, and money.</p> <p>Exit allows the user to stop the program.</p> <pre class="lang-py prettyprint-override"><code>#First OOP Project class CoffeeMachine: running = False def __init__(self, water, milk, coffee_beans, cups, money): # quantities of items the coffee machine already had self.water = water self.milk = milk self.coffee_beans = coffee_beans self.cups = cups self.money = money #if the machine isnt running then start running if not CoffeeMachine.running: self.start() def start(self): self.running = True self.action = input("Write action (buy, fill, take, remaining, exit):\n") print() #possible choices to perform in the coffee machine if self.action == "buy": self.buy() elif self.action == "fill": self.fill() elif self.action == "take": self.take() elif self.action == "exit": exit() elif self.action == "remaining": self.status() def return_to_menu(self): # returns to the menu after an action print() self.start() def available_check(self): # checks if it can afford making that type of coffee at the moment self.not_available = "" # by checking whether the supplies goes below 0 after it is deducted if self.water - self.reduced[0] &lt; 0: self.not_available = "water" elif self.milk - self.reduced[1] &lt; 0: self.not_available = "milk" elif self.coffee_beans - self.reduced[2] &lt; 0: self.not_available = "coffee beans" elif self.cups - self.reduced[3] &lt; 0: self.not_available = "disposable cups" if self.not_available != "": # if something was detected to be below zero after deduction print(f"Sorry, not enough {self.not_available}!") return False else: # if everything is enough to make the coffee print("I have enough resources, making you a coffee!") return True def deduct_supplies(self): # performs operation from the reduced list, based on the coffee chosen self.water -= self.reduced[0] self.milk -= self.reduced[1] self.coffee_beans -= self.reduced[2] self.cups -= self.reduced[3] self.money += self.reduced[4] def buy(self): self.choice = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:\n") if self.choice == '1': self.reduced = [250, 0, 16, 1, 4] # water, milk, coffee beans, cups, money if self.available_check(): # checks if supplies are available self.deduct_supplies() # if it is, then it deducts elif self.choice == '2': self.reduced = [350, 75, 20, 1, 7] if self.available_check(): self.deduct_supplies() elif self.choice == "3": self.reduced = [200, 100, 12, 1, 6] if self.available_check(): self.deduct_supplies() elif self.choice == "back": # if the user changed his mind self.return_to_menu() self.return_to_menu() def fill(self): # for adding supplies to the machine self.water += int(input("Write how many ml of water do you want to add:\n")) self.milk += int(input("Write how many ml of milk do you want to add:\n")) self.coffee_beans += int(input("Write how many grams of coffee beans do you want to add:\n")) self.cups += int(input("Write how many disposable cups of coffee do you want to add:\n")) self.return_to_menu() def take(self): # for taking the money from the machine print(f"I gave you ${self.money}") self.money -= self.money self.return_to_menu() def status(self): # to display the quantities of supplies in the machine at the moment print(f"The coffee machine has:") print(f"{self.water} of water") print(f"{self.milk} of milk") print(f"{self.coffee_beans} of coffee beans") print(f"{self.cups} of disposable cups") print(f"${self.money} of money") self.return_to_menu() CoffeeMachine(400, 540, 120, 9, 550) # specify the quantities of supplies at the beginning # water, milk, coffee beans, disposable cups, money </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T19:51:33.037", "Id": "471564", "Score": "0", "body": "alright i did add comments to the program to make it easier" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T20:16:44.567", "Id": "471565", "Score": "1", "body": "Thank you for the added description. I hope you get a good answer now :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:37:34.460", "Id": "471717", "Score": "0", "body": "FYI what you are building here is called a *state machine*. That is, the machine has a particular internal state, it takes in a sequence of *actions* as inputs, each action might or might not cause a state change, and might or might not cause an *output* that is based on action and state. There is a huge literature on the study of state machines and how to efficiently implement them; you might want to do some reading." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T14:32:43.923", "Id": "471884", "Score": "1", "body": "Please don't fix the code in the question based on the answers you've been given, it makes it impossible for other readers to understand what the actual review was supposed to be." } ]
[ { "body": "<p>When you have multiple <code>if</code> statements, like your code does, it can be an indication that you can use a <a href=\"https://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">visitor pattern</a> to your code. I will use a dict in my example.</p>\n\n<p>Your code:</p>\n\n<pre><code>def start(self):\n self.running = True\n self.action = input(\"Write action (buy, fill, take, remaining, exit):\\n\")\n print()\n #possible choices to perform in the coffee machine\n if self.action == \"buy\":\n self.buy()\n elif self.action == \"fill\":\n self.fill()\n elif self.action == \"take\":\n self.take()\n elif self.action == \"exit\":\n exit()\n elif self.action == \"remaining\":\n self.status()\n</code></pre>\n\n<p>Re-written, using the visitor pattern:</p>\n\n<pre><code>def action_buy(self):\n self.buy()\n\naction_choices = { \"buy\" : action_buy,\n \"fill\" : action_fill, ...\n\ndef start(self):\n self.running = True\n self.action = input(\"Write action (buy, fill, take, remaining, exit):\\n\")\n print()\n #possible choices to perform in the coffee machine\n if self.action in action_choices:\n action_choices[self.action](self)\n</code></pre>\n\n<p>You can use the same principle on the function buy. I didn't verify the code so probably there are some errors, but hope you got the idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T20:45:01.403", "Id": "471566", "Score": "0", "body": "that is really useful, thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:11:31.067", "Id": "471666", "Score": "2", "body": "Even better, you can use the keys of the dict to generate your prompt text: `input(\"Write action ({actions}):\\n\".format(actions=action_choices.keys())`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T20:26:31.267", "Id": "240415", "ParentId": "240413", "Score": "13" } }, { "body": "<p>You should split business logic and user interface.</p>\n\n<p>Whilst it's common to get coffee machines that are hella advanced and can talk to humans.\nWhen programming you should build in layers.</p>\n\n<p>I always build the core of the logic to be a generic as possible. This allows for easier tests, re-usability and segregation of the project.</p>\n\n<p>This would means changing the <code>CoffeeMachine</code> to only contain <code>available</code> and <code>deduct</code> as methods.</p>\n\n<p>I would also add a class <code>CoffeeInterface</code> that can be a <a href=\"https://docs.python.org/3/library/cmd.html\" rel=\"noreferrer\"><code>cmd.Cmd</code></a>.\nThis will help cut out some of the code that you have right now.</p>\n\n<ul>\n<li><p>Only use <code>self.foo</code> for attributes defined in the <code>__init__</code>. Everything else should be passed via arguments.</p>\n\n<p>I also wouldn't change any of the attributes defined in the <code>__init__</code> as only things directly related to the class should be defined there.</p></li>\n<li><p>Please don't do things like <code>if not CoffeeMachine.running: self.start()</code> in <code>__init__</code>. You should let the user call <code>.start()</code>.</p></li>\n<li><p><code>exit()</code> is not intended to be used in actual live programs. Instead you should structure your code so that it is not needed.</p>\n\n<p>There are times when <code>exit(1)</code> or <code>raise SystemExit(1)</code> are useful. But unless you're doing Unix programming it's unlikely you'll need these.</p></li>\n</ul>\n\n<p>All this together can get the following code. Not much has changed as I mostly just split the two classes.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class CoffeeMachine:\n def __init__(self, water, milk, coffee_beans, cups, money):\n self.water = water\n self.milk = milk\n self.coffee_beans = coffee_beans\n self.cups = cups\n self.money = money\n\n def available(self, water, milk, coffee_beans, cups, _):\n not_available = \"\"\n if self.water - water &lt; 0:\n not_available = \"water\"\n elif self.milk - milk &lt; 0:\n not_available = \"milk\"\n elif self.coffee_beans - coffee_beans &lt; 0:\n not_available = \"coffee beans\"\n elif self.cups - cups &lt; 0:\n not_available = \"disposable cups\"\n\n if not_available != \"\":\n print(f\"Sorry, not enough {not_available}!\")\n return False\n else:\n print(\"I have enough resources, making you a coffee!\")\n return True\n\n def deduct(self, water, milk, coffee_beans, cups, money):\n self.water -= water\n self.milk -= milk\n self.coffee_beans -= coffee_beans\n self.cups -= cups\n self.money += money\n\n\nclass CoffeeInterface(cmd.Cmd):\n def __init__(self, coffee_machine, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.coffee_machine = coffee_machine\n\n def do_buy(self, _):\n choice = input(\"What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:\\n\")\n if choice == '1':\n requirements = [250, 0, 16, 1, 4]\n if self.coffee_machine.available(*requirements):\n self.coffee_machine.deduct(*requirements)\n\n elif choice == '2':\n requirements = [350, 75, 20, 1, 7]\n if self.coffee_machine.available(*requirements):\n self.coffee_machine.deduct(*requirements)\n\n elif choice == \"3\":\n requirements = [200, 100, 12, 1, 6]\n if self.coffee_machine.available(*requirements):\n self.coffee_machine.deduct(*requirements)\n\n elif choice == \"back\": # if the user changed his mind\n pass\n\n def do_fill(self, _):\n \"\"\"Add supplies to the machine.\"\"\"\n self.coffee_machine.water += int(input(\"Write how many ml of water do you want to add:\\n\"))\n self.coffee_machine.milk += int(input(\"Write how many ml of milk do you want to add:\\n\"))\n self.coffee_machine.coffee_beans += int(input(\"Write how many grams of coffee beans do you want to add:\\n\"))\n self.coffee_machine.cups += int(input(\"Write how many disposable cups of coffee do you want to add:\\n\"))\n\n def do_take(self, _):\n \"\"\"Take money from the machine.\"\"\"\n print(f\"I gave you ${self.coffee_machine.money}\")\n self.coffee_machine.money -= self.coffee_machine.money\n\n def do_status(self):\n \"\"\"Display the quantities of supplies in the machine at the moment.\"\"\"\n print(f\"The coffee machine has:\")\n print(f\"{self.coffee_machine.water} of water\")\n print(f\"{self.coffee_machine.milk} of milk\")\n print(f\"{self.coffee_machine.coffee_beans} of coffee beans\")\n print(f\"{self.coffee_machine.cups} of disposable cups\")\n print(f\"${self.coffee_machine.money} of money\")\n\n\nCoffeeInterface(CoffeeMachine(400, 540, 120, 9, 550)).cmdloop()\n</code></pre>\n\n<p>Now that the two separate things have been split apart we can focus on reviewing the code.</p>\n\n<ul>\n<li><p>I would move supplies into yet another class.<br>\nI would make this class a named tuple as it has a couple of benefits:</p>\n\n<ol>\n<li>It's immutable, meaning that it's hard to mess up <code>CoffeeMachine.available</code>.</li>\n<li>Getting specific values from it is clean, <code>reduced.water</code> rather than <code>reduced[0]</code>.</li>\n<li>We can pass around one object rather than using nasty <code>*requirements</code>.</li>\n</ol>\n\n<p>I have elected to use <a href=\"https://docs.python.org/3/library/typing.html#typing.NamedTuple\" rel=\"noreferrer\"><code>typing.NamedTuple</code></a> however <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"noreferrer\"><code>collections.namedtuple</code></a> may be simpler to understand as it doesn't use type hints.</p></li>\n<li><p>I would define the <code>__sub__</code> dunder method on the <code>Supplies</code> class.<br>\nThis means when we are subtracting supplies, the core of your code, it's nicer to the eyes.</p>\n\n<p>To get this working correctly you have the option to make <code>money</code> work differently to the rest. Or you can make money negative when you're supplying the cost of a drink. I think a negative cost to make a drink is the most intuitive.</p></li>\n<li><p>The code for <code>available</code> can be reduced to less lines, however this would make the code more confusing at the moment.</p></li>\n<li><p>I would move the <code>print</code> out of the <code>available</code> function, it is better located in <code>do_buy</code>.<br>\nTo allow printing the missing item you can change its name to <code>unavailable</code> and return the unavailable item.\nThis would have the benefit of still making sense.</p></li>\n<li><p>You should move the available drinks out of <code>do_buy</code>.<br>\nIf you move them into a dictionary then you can significantly reduce the amount of code in <code>do_buy</code>.</p>\n\n<p>To do this we can build a dictionary with each key being the value 1, 2 or 3. And the value as the <code>Supplies</code> for that drink.\nFrom here we can use <code>dict.get(choice, None)</code>, which will return the <code>Supplies</code> for the selected drink or <code>None</code> if the user didn't enter a valid choice.</p>\n\n<p>From here we can just return if it's not a valid choice, and interact with the <code>CoffeeMachine</code> otherwise.</p></li>\n<li><p>To simplify <code>do_fill</code> and <code>take</code> we can add the <code>__add__</code> dunder method.<br>\nThis means we only need one <code>+</code> rather than four.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import cmd\nfrom typing import NamedTuple\n\n\nclass Supplies(NamedTuple):\n water: int\n milk: int\n coffee_beans: int\n cups: int\n money: int\n\n def __sub__(self, other):\n return Supplies(\n self.water - other.water,\n self.milk - other.milk,\n self.coffee_beans - other.coffee_beans,\n self.cups - other.cups,\n self.money - other.money,\n )\n\n def __add__(self, other):\n return Supplies(\n self.water + other.water,\n self.milk + other.milk,\n self.coffee_beans + other.coffee_beans,\n self.cups + other.cups,\n self.money + other.money,\n )\n\n\nDRINKS = {\n '1': Supplies(250, 0, 16, 1, -4),\n '2': Supplies(350, 75, 20, 1, -7),\n '3': Supplies(200, 100, 12, 1, -6),\n}\n\n\nclass CoffeeMachine:\n def __init__(self, supplies):\n self.supplies = supplies\n\n def unavailable(self, drink):\n remaining = self.supplies - drink\n not_available = \"\"\n if remaining.water &lt; 0:\n not_available = \"water\"\n elif remaining.milk &lt; 0:\n not_available = \"milk\"\n elif remaining.coffee_beans &lt; 0:\n not_available = \"coffee beans\"\n elif remaining.cups &lt; 0:\n not_available = \"disposable cups\"\n return not_available if not_available else None\n\n def deduct(self, drink):\n self.supplies -= drink\n\n\nclass CoffeeInterface(cmd.Cmd):\n def __init__(self, coffee_machine, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.coffee_machine = coffee_machine\n\n def do_buy(self, _):\n choice = input(\"What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:\\n\")\n drink = DRINKS.get(choice, None)\n if drink is None:\n return\n\n unavailable = self.coffee_machine.available(drink)\n if unavailable:\n print(f\"Sorry, not enough {unavailable}!\")\n else:\n print(\"I have enough resources, making you a coffee!\")\n self.coffee_machine.deduct(drink)\n\n def do_fill(self, _):\n \"\"\"Add supplies to the machine.\"\"\"\n self.coffee_machine.supplies += Supplies(\n int(input(\"Write how many ml of water do you want to add:\\n\")),\n int(input(\"Write how many ml of milk do you want to add:\\n\")),\n int(input(\"Write how many grams of coffee beans do you want to add:\\n\")),\n int(input(\"Write how many disposable cups of coffee do you want to add:\\n\")),\n 0,\n )\n\n def do_take(self, _):\n \"\"\"Take money from the machine.\"\"\"\n money = self.coffee_machine.supplies.money\n print(f\"I gave you ${money}\")\n self.coffee_machine.supplies -= Supplies(0, 0, 0, 0, money)\n\n def do_status(self):\n \"\"\"Display the quantities of supplies in the machine at the moment.\"\"\"\n supplies = self.coffee_machine.supplies\n print(f\"The coffee machine has:\")\n print(f\"{supplies.water} of water\")\n print(f\"{supplies.milk} of milk\")\n print(f\"{supplies.coffee_beans} of coffee beans\")\n print(f\"{supplies.cups} of disposable cups\")\n print(f\"${supplies.money} of money\")\n\n\nCoffeeInterface(CoffeeMachine(Supplies(400, 540, 120, 9, 550))).cmdloop()\n</code></pre>\n\n<ul>\n<li><p>Given the amount of <code>self.coffee_machine.supplies.{x}</code> it should be blindingly apparent that <code>CoffeeMachine</code> is now more of a hindrance than a help.</p>\n\n<ul>\n<li>Having to read and write <code>self.coffee_machine.supplies</code> is rather annoying.</li>\n<li>We can easily change <code>deduct</code> to just <code>self.coffee_machine.supplies -= drink</code>.</li>\n<li>The function <code>unavailable</code> can be moved onto either <code>Supplies</code> or <code>CoffeeInterface</code>.</li>\n</ul></li>\n<li><p>One of the benefits to using <code>NamedTuple</code> is that it defines a means to iterate over it without us having to write it.<br>\nThis means that we can simplify the <code>__sub__</code>, <code>__add__</code> and <code>unavailable</code> methods.</p>\n\n<p>To do so we can use <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"noreferrer\"><code>zip</code></a> which lets us iterate over two things at the same time.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>foos = 'abcdef'\nbars = 'ghijkl'\n\n# non-zip\nfor i in range(len(foos)):\n print(foos[i], bars[i])\n\n# zip\nfor foo, bar in zip(foos, bars):\n print(foo, bar)\n</code></pre>\n\n<p>We can also use a list comprehension or generator expression to build the new <code>Supplies</code> on one line.</p></li>\n<li><p>With <code>cmd</code> you can pass a string when entering a command.\nThis means it is possible to enter <code>buy espresso</code>.</p>\n\n<p>It would be cool if you used this to buy by an item's name rather than an odd number.</p>\n\n<p>To allow this you can have a menu option that shows a list of items that you can buy.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import cmd\nfrom typing import NamedTuple\n\n\nclass Supplies(NamedTuple):\n water: int\n milk: int\n coffee_beans: int\n cups: int\n money: int\n\n def __sub__(self, other):\n return Supplies(*[s - o for s, o in zip(self, other)])\n\n def __add__(self, other):\n return Supplies(*[s + o for s, o in zip(self, other)])\n\n def unavailable(self):\n return [\n field\n for field, value in zip(self._fields, self)\n if value &lt; 0\n ]\n\n\nDRINKS = {\n 'espresso': Supplies(250, 0, 16, 1, -4),\n 'latte': Supplies(350, 75, 20, 1, -7),\n 'cappuccino': Supplies(200, 100, 12, 1, -6),\n}\n\n\nclass CoffeeInterface(cmd.Cmd):\n def __init__(self, supplies, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.supplies = supplies\n\n def do_menu(self, _):\n print('\\n'.join(DRINKS))\n\n def do_buy(self, choice):\n drink = DRINKS.get(choice.lower(), None)\n if drink is None:\n return\n\n remaining = self.supplies - drink\n unavailable = remaining.unavailable()\n if unavailable:\n print(f\"Sorry, not enough {', '.join(unavailable)}!\")\n else:\n print(\"I have enough resources, making you a coffee!\")\n self.supplies = remaining\n\n def do_fill(self, _):\n \"\"\"Add supplies to the machine.\"\"\"\n self.supplies += Supplies(\n int(input(\"Write how many ml of water do you want to add:\\n\")),\n int(input(\"Write how many ml of milk do you want to add:\\n\")),\n int(input(\"Write how many grams of coffee beans do you want to add:\\n\")),\n int(input(\"Write how many disposable cups of coffee do you want to add:\\n\")),\n 0,\n )\n\n def do_take(self, _):\n \"\"\"Take money from the machine.\"\"\"\n print(f\"I gave you ${self.supplies.money}\")\n self.supplies -= Supplies(0, 0, 0, 0, self.supplies.money)\n\n def do_status(self):\n \"\"\"Display the quantities of supplies in the machine at the moment.\"\"\"\n print(f\"The coffee machine has:\")\n print(f\"{self.supplies.water} of water\")\n print(f\"{self.supplies.milk} of milk\")\n print(f\"{self.supplies.coffee_beans} of coffee beans\")\n print(f\"{self.supplies.cups} of disposable cups\")\n print(f\"${self.supplies.money} of money\")\n\n\nCoffeeInterface(Supplies(400, 540, 120, 9, 550)).cmdloop()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T21:44:40.180", "Id": "240419", "ParentId": "240413", "Score": "8" } }, { "body": "<p>First some basic observations:</p>\n\n<ol>\n<li><p>Your <code>running</code> variable is shared across all <code>CoffeeMachine</code> objects -- as soon as you create one <code>CoffeeMachine</code>, it starts itself, and then any subsequent <code>CoffeeMachine</code> you create anywhere in the universe is also \"running\" and so it doesn't start itself! Unless this is a property you intended it to have (it would certainly not match the behavior of real-world coffee machines), you should make <code>running</code> an instance variable (i.e. put it in the <code>__init__</code>), or better yet, not have it at all (since you immediately initialize it anyway and never use it for anything else thereafter -- if a machine is always \"running\" as soon as it's created, no point in having a bool to indicate that state).</p></li>\n<li><p>Some of your instance variables are created after <code>__init__</code>. Python lets you do this, but it's considered bad practice because it's very easy to have bugs where you access a variable before it's initialized. In general, all instance variables should be declared in <code>__init__</code>.</p></li>\n<li><p>Your <code>self.reduced</code> variable is only used for <code>available_check</code> and <code>deduct_supplies</code>, which are called immediately after <code>reduced</code> is set -- <code>reduced</code> should simply be a parameter. If it's a parameter, then you know that its value doesn't matter after those functions return (which is the case) and you don't need to worry about what other parts of your code setting <code>self.reduced</code> might affect. The general rule here is that state should be as \"short-lived\" and/or \"narrowly scoped\" as possible. (edit: as I go through the rest of the code, I see that there's a common pattern of assigning values to <code>self</code> where a locally-scoped value would suffice. Never make data more persistent than it needs to be!)</p></li>\n</ol>\n\n<p>Now, some more \"big picture\" notes on the structure of the methods:</p>\n\n<ol>\n<li><p>All of your actions call back to <code>return_to_menu</code> which calls back to <code>start</code>. Maybe <code>start</code> should just loop? That way <code>return_to_menu</code> doesn't need to get called at the end of every action method, and it's also obvious to someone reading your <code>start</code> method that it's actually a loop (you want the way your code works to be obvious to everyone who reads it).</p></li>\n<li><p>Specifying the different types of objects as <code>Enum</code>s makes it a little easier to keep track of the possible values and keep different parts of your code from having different versions of them.</p></li>\n<li><p>When you have associations between different pieces of data (like \"type of ingredient\" and \"quantity\"), a natural way to store that is in a dictionary. Again, this makes it easier to keep track of things, and it also makes it easier to say \"do this for every ingredient\" without having to copy and paste.</p></li>\n</ol>\n\n<p>I took a few passes over this code seeing if I could convert everything into enums and dictionaries, with the general goal of never having to copy+paste the same word in multiple places, and turning all those <code>if</code>...<code>elif</code> chains into iterations or lookups. The general pattern I've followed is to have the \"name\" of the enumeration be the way you refer to it in your code and the \"value\" be the user-visible rendering (which is usually but not always the same); in real life you'd probably have a slightly more complex (and extensible) mapping that would allow for localization, etc, but as a general demonstration of the concept I think this is good enough. </p>\n\n<p>Here's what I came up with; there's a lot more data declared up front that defines how the coffee machine operates, and a lot less actual code in the methods.</p>\n\n<pre><code>from enum import Enum, auto\nfrom typing import Dict, List\n\nclass Inventory(Enum):\n \"\"\"Inventory items.\"\"\"\n water = \"water\"\n milk = \"milk\"\n coffee_beans = \"coffee beans\"\n cups = \"disposable cups\"\n money = \"money\"\n\n# The unit description of each inventory item.\nUNITS = { \n Inventory.water: \"ml of\",\n Inventory.milk: \"ml of\",\n Inventory.coffee_beans: \"grams of\",\n Inventory.cups: \"of\",\n Inventory.money: \"of\",\n}\n\nclass Action(Enum):\n \"\"\"Menu actions.\"\"\"\n buy = \"buy\"\n fill = \"fill\"\n take = \"take\"\n status = \"remaining\"\n\nclass Product(Enum):\n \"\"\"Products for sale.\"\"\"\n espresso = \"1\"\n latte = \"2\"\n cappuccino = \"3\"\n\n# The cost of each product.\nCOSTS = { \n Product.espresso: {\n Inventory.water: 250,\n Inventory.milk: 0,\n Inventory.coffee_beans: 16,\n Inventory.cups: 1,\n Inventory.money: 4,\n },\n Product.latte: {\n Inventory.water: 350,\n Inventory.milk: 75,\n Inventory.coffee_beans: 20,\n Inventory.cups: 1,\n Inventory.money: 7,\n },\n Product.cappuccino: {\n Inventory.water: 200,\n Inventory.milk: 100,\n Inventory.coffee_beans: 12,\n Inventory.cups: 1,\n Inventory.money: 6,\n },\n}\n\nclass CoffeeMachine:\n\n def __init__(\n self, \n water: int, \n milk: int, \n coffee_beans: int, \n cups: int, \n money: int\n ):\n self.quantities = {\n Inventory.water: water,\n Inventory.milk: milk,\n Inventory.coffee_beans: coffee_beans,\n Inventory.cups: cups,\n Inventory.money: money,\n }\n\n self.run()\n\n def run(self) -&gt; None:\n do_action = {\n Action.buy: self.buy,\n Action.fill: self.fill,\n Action.take: self.take,\n Action.status: self.status,\n }\n actions = ', '.join(action.value for action in Action)\n\n while True:\n action = input(f\"Write action ({actions}, exit):\\n\")\n print()\n if action == \"exit\":\n break\n do_action[Action(action)]()\n print()\n\n def available_check(self, cost: Dict[Inventory, int]) -&gt; bool:\n \"\"\"checks if it can afford making that type of coffee at the moment\"\"\"\n for item in Inventory:\n if self.quantities[item] &lt; cost[item]:\n print(f\"Sorry, not enough {item.value}!\")\n return False\n else:\n print(\"I have enough resources, making you a coffee!\")\n return True\n\n def deduct_supplies(self, cost: Dict[Inventory, int]) -&gt; None:\n \"\"\"performs operation from the cost list, based on the coffee chosen\"\"\"\n for item in Inventory:\n self.quantities[item] -= cost[item]\n\n def buy(self) -&gt; None:\n products = \", \".join(\n f\"{product.value} - {product.name}\" for product in Product\n )\n choice = input(\n f\"What do you want to buy? {products}, back - to main menu:\\n\"\n )\n if choice == \"back\":\n return\n cost = COSTS[Product(choice)]\n if self.available_check(cost):\n self.deduct_supplies(cost)\n\n def fill(self) -&gt; None: \n \"\"\"for adding supplies to the machine\"\"\"\n for item in Inventory:\n if item == Inventory.money:\n continue\n self.quantities[item] += int(input(\n \"Write how many \"\n f\"{UNITS[item]} {item.value}\"\n \" do you want to add:\\n\"\n ))\n\n def take(self) -&gt; None:\n \"\"\"for taking the money from the machine\"\"\"\n print(f\"I gave you ${self.quantities[Inventory.money]}\")\n self.quantities[Inventory.money] = 0\n\n def status(self) -&gt; None: \n \"\"\"display the quantities of supplies in the machine at the moment\"\"\"\n print(f\"The coffee machine has:\")\n for item in Inventory:\n print(f\"{self.quantities[item]} {UNITS[item]} {item.value}\")\n\n# specify the quantities of supplies at the beginning\n# water, milk, coffee beans, disposable cups, money\nCoffeeMachine(400, 540, 120, 9, 550) \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T00:23:48.130", "Id": "471584", "Score": "0", "body": "Wow, that's a lot of stuff I doubt the user will ever need. You may want to post this as a separate question as from a 2 second glance I'm not sure it's that great. Lots of PEP 8, PEP 257 and Enum violations here too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T23:29:30.250", "Id": "240424", "ParentId": "240413", "Score": "5" } }, { "body": "<p>Instead of </p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def start(self):\n self.running = True\n self.action = input(\"Write action (buy, fill, take, remaining, exit):\\n\")\n print()\n #possible choices to perform in the coffee machine\n if self.action == \"buy\":\n self.buy()\n elif self.action == \"fill\":\n self.fill()\n elif self.action == \"take\":\n self.take()\n elif self.action == \"exit\":\n exit()\n elif self.action == \"remaining\":\n self.status()\n</code></pre>\n\n<p>I would suggest</p>\n\n<pre><code> def start(self):\n self.running = True\n\n action = input(\"Write action (buy, fill, take, remaining, exit):\\n\")\n print()\n\n try:\n getattr(self, self.action)()\n except AttributeError:\n print(\"Invalid action\") \n</code></pre>\n\n<p>but you then have to add methods <code>exit(self)</code> and <code>remaining(self)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T11:38:30.447", "Id": "240442", "ParentId": "240413", "Score": "4" } }, { "body": "<h2>class/instance variables</h2>\n\n<p>In your code, you use class variables instead of instance variables.</p>\n\n<p>You have to know that class variables are shared in all instance, for example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class CoffeeMachine:\n water = 400\n\n\nmy_machine = CoffeeMachine()\nyour_machine = CoffeeMachine()\n\nCoffeeMachine.water = 0\nprint(my_machine.water)\nprint(your_machine.water)\n</code></pre>\n\n<p>You get 0 in both machines!</p>\n\n<p>The right way is to used instance variable. Instance variables determine the state of your object:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class CoffeeMachine:\n def __init__(self):\n self.water = 400\n\n\nmy_machine = CoffeeMachine()\nyour_machine = CoffeeMachine()\n\nmy_machine.water = 0\nprint(my_machine.water)\nprint(your_machine.water)\n</code></pre>\n\n<p>So, in your code, you can replace <code>CoffeeMachine.sothing</code> by <code>self.sothing</code>.</p>\n\n<p>See the chapter <a href=\"https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables\" rel=\"noreferrer\">Class and Instance Variables</a> in the Python documentation.</p>\n\n<p>Your constructor become:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class CoffeeMachine:\n def __init__(self):\n self.water = 400\n self.milk = 540\n self.coffee_beans = 120\n self.cups = 9\n self.money = 550\n self.running = False\n</code></pre>\n\n<h2>infinite recursion</h2>\n\n<p>I have detected a potential infinite recursion:</p>\n\n<ul>\n<li>The <code>__init__</code> function calls `start``,</li>\n<li>The <code>start</code> function calls on of the actions,</li>\n<li>Each action calls <code>return_to_menu</code>,</li>\n<li>And the <code>return_to_menu</code> function calls <code>start</code> again…</li>\n</ul>\n\n<p>To avoid that, you can use an infinite loop, which will be controlled by the <em>running</em> attribute.\nHere is the scenario:</p>\n\n<p>The machine is initialised: <em>running</em> is <code>True</code>,</p>\n\n<p>While <em>running</em> is <code>True</code>:</p>\n\n<ul>\n<li>The user enter the action he wants to do</li>\n<li>The machine execute the action</li>\n</ul>\n\n<p>You can easily translate into a <code>main</code> function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n machine = CoffeeMachine()\n while machine.running:\n action = ask_action()\n machine.execute_action(action)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Of course, we need to change the implementation slightly:</p>\n\n<ul>\n<li><p>the initialisation must set <em>running</em> to <code>True</code>,</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def __init__(self):\n ...\n self.running = False\n</code></pre></li>\n<li><p>the old <code>start</code> method is divided into 2 functions with a single role: prompting the user and running an action.</p></li>\n<li><p>The <code>return_to_menu</code> is removed.</p></li>\n</ul>\n\n<h2>Prompting the user</h2>\n\n<p>When you ask something to the user you generally need to check the input to make sure it matches what we need. If not, we loop forever.</p>\n\n<p>For the <code>ask_action</code> function, we have a set of acceptable answers: \"buy\", \"fill\", \"take\", \"exit\", \"remaining\". So, we can loop forever until the user enter an acceptable answer.</p>\n\n<p>In Python, we can use an enumeration for that:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import enum\n\nclass Action(enum.Enum):\n BUY = \"buy\"\n FILL = \"fill\"\n TAKE = \"take\"\n EXIT = \"exit\"\n REMAINING = \"remaining\"\n</code></pre>\n\n<p>Here is a small demo of the possibilities:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; possible_values = [action.value for action in Action]\n&gt;&gt;&gt; possible_values\n['buy', 'fill', 'take', 'exit', 'remaining']\n\n&gt;&gt;&gt; action = Action(\"fill\")\n&gt;&gt;&gt; action\n&lt;Action.FILL: 'fill'&gt;\n\n&gt;&gt;&gt; action = Action(\"quit\")\nTraceback (most recent call last):\n ...\nValueError: 'quit' is not a valid Action\n</code></pre>\n\n<p>Here is how you can define the <code>ask_action</code> function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import enum\n\nclass Action(enum.Enum):\n BUY = \"buy\"\n FILL = \"fill\"\n TAKE = \"take\"\n EXIT = \"exit\"\n REMAINING = \"remaining\"\n\ndef ask_action():\n possible_values = \", \".join([action.value for action in Action])\n while True:\n answer = input(f\"Write action ({possible_values}):\\n\")\n try:\n return Action(answer)\n except ValueError:\n print(f\"This answer is not valid: {answer}\")\n</code></pre>\n\n<p>Note: <code>ask_action</code> is a function here, there no need to turn it into a method since it doesn't access the class variables or methods.</p>\n\n<h2>executing an action</h2>\n\n<p>It easy to change the old <code>start</code> method into a <code>execute_action</code> method. This method has the parameter <em>action</em>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def execute_action(self, action):\n if action == Action.BUY:\n self.buy()\n elif action == Action.FILL:\n self.fill()\n elif action == Action.TAKE:\n self.take()\n elif action == Action.EXIT:\n self.running = False\n elif action == Action.REMAINING:\n self.show_remaining()\n else:\n raise NotImplementedError(action)\n</code></pre>\n\n<p>The implementation is slightly changed:</p>\n\n<ul>\n<li>The <strong>exit</strong> action is changed to set <em>running</em> to <code>False</code>.</li>\n<li><code>NotImplementedError</code> is raised if the action is unknown: this prevent unwanted behavior if your <code>Action</code> enumaration changes in the future but you forget to update <code>execute_action</code>.</li>\n<li><code>status</code> (which is renamed <code>show_remaining</code>) is fixed: no need to take the class in parameter.</li>\n</ul>\n\n<p>As you can see, it is very simple.</p>\n\n<h2>Show remaining</h2>\n\n<p>The <code>status</code> function was renamed <code>show_remaining</code> to use a verb and match the term used in <code>Action</code>.\nBut you can also change the Action into \"status\" if you prefer.</p>\n\n<p>The status don't need to have any parameter because you only want to display the instance variable values.\nSo, you can write:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def show_remaining(self):\n \"\"\"\n Display the quantities of supplies in the machine at the moment\n \"\"\"\n print(f\"The coffee machine has:\")\n print(f\"{self.water} of water\")\n print(f\"{self.milk} of milk\")\n print(f\"{self.coffee_beans} of coffee beans\")\n print(f\"{self.cups} of disposable cups\")\n print(f\"${self.money} of money\")\n</code></pre>\n\n<p>Instead of using a comment you can use a docstring. This is that way we document function and classes in Python.</p>\n\n<p>You can read <a href=\"https://docs.python-guide.org/writing/documentation/\" rel=\"noreferrer\">The Hitchhiker Guide to Python</a> about docstring and API documentation in general. Very good book.</p>\n\n<h2>Ask for a drink</h2>\n\n<p>The \"buy\" action is similar to the \"ask_action/execute_action\".\nIf you use the same logic, you'll see that you can drop or reimplement the <code>deduct_supplies</code> function too.</p>\n\n<p>The difference is that you want the user to enter a number instead of a text.\nYou have: 1 - \"espresso\", 2 - \"latte\", 3 - \"cappuccino\", for \"back to main menu\", you can choose 9.\nAll that can be stored in a class Python <code>dict</code> to do the mapping between numbers and labels.</p>\n\n<p>Note that <code>ask_drink</code> is a good name for this function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def ask_drink():\n choices = {1: \"espresso\", 2: \"latte\", 3: \"cappuccino\", 9: \"back to main menu\"}\n possible_values = \", \".join(f\"{value} - {name}\" for value, name in sorted(choices.items()))\n while True:\n answer = input(f\"What do you want to buy? ({possible_values}):\\n\")\n try:\n value = int(answer)\n if value in choices:\n return value\n print(f\"This answer is not valid: {answer}\")\n except ValueError:\n print(f\"This is not a number: {answer}\")\n</code></pre>\n\n<p>Remarks:</p>\n\n<ul>\n<li><code>sorted</code> is required because <code>dict</code> keys are unordered (well, actually, recent versions of Python keep keys order),</li>\n<li>Using <code>value in choices</code> is a good way to check if a key is in a dictionary.</li>\n</ul>\n\n<h2>Consumption (deduced supplies)</h2>\n\n<p>In your coffee machine, deduced supplies is represented as a list of 5 elements.\nFor instance, we have <code>[250, 0, 16, 1, 4]</code> for water, milk, coffee beans, cups and money.\nIf you have a list, you need to access the items by index. But I would be easier to access the items by name. To do that, you can use a <a href=\"https://docs.python.org/3.9/library/collections.html#collections.namedtuple\" rel=\"noreferrer\"><code>collections.namedtuple</code></a>. A <code>namedtuple</code> is a factory function which creates a class (a subclass of <code>tuple</code>).</p>\n\n<p>First, you can define a new tuple class, we call it <code>Consumption</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import collections\n\nConsumption = collections.namedtuple(\"Consumption\", \"water, milk, coffee_beans, cups, money\")\n</code></pre>\n\n<p>You can instanciate the <code>Consumption</code> like a classic <code>tuple</code> or with key/value pairs:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>espresso_cons = Consumption(250, 0, 16, 1, 4)\nlatte_cons = Consumption(water=350, milk=75, coffee_beans=20, cups=1, money=7)\ncappuccino_cons = Consumption(water=200, milk=100, coffee_beans=12, cups=1, money=6)\n</code></pre>\n\n<p><em>note:</em> the second form is really more readable.</p>\n\n<h2>Checking availability</h2>\n\n<p>When you need to \"check\" something, you can think about exceptions. The idea behind this is: I do some tests and if something is wrong I raise an exception. The exception type and/or the exception message can detail the problem. Then I can use an exception handler to display the message.</p>\n\n<p>To define an exception, a good practice is to inherit the <code>Exception</code> class like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class NotEnoughSupplyError(Exception):\n def __init__(self, supply):\n msg = f\"Sorry, not enough {supply}\"\n super(NotEnoughSupplyError, self).__init__(msg)\n</code></pre>\n\n<p>This exception take a <em>supply</em> parameter which is the name of the missing supply.</p>\n\n<p>You can then implement the <code>available_check</code> method as below:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def available_check(self, consumption):\n \"\"\"\n Checks if it can afford making that type of coffee at the moment\n\n :param consumption: the Consumption\n :raise NotEnoughSupplyError: if at least one supply is missing.\n \"\"\"\n if self.water - consumption.water &lt; 0:\n raise NotEnoughSupplyError(\"water\")\n elif self.milk - consumption.milk &lt; 0:\n raise NotEnoughSupplyError(\"milk\")\n elif self.coffee_beans - consumption.coffee_beans &lt; 0:\n raise NotEnoughSupplyError(\"coffee beans\")\n elif self.cups - consumption.cups &lt; 0:\n raise NotEnoughSupplyError(\"cups\")\n</code></pre>\n\n<p>Really simple, isn't it?</p>\n\n<h2>The <code>buy</code> method</h2>\n\n<p>You know have all the elements in hand to implement the <code>buy</code> method:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def buy(self):\n drink = ask_drink()\n if drink == 9:\n return\n espresso_cons = Consumption(250, 0, 16, 1, 4)\n latte_cons = Consumption(water=350, milk=75, coffee_beans=20, cups=1, money=7)\n cappuccino_cons = Consumption(water=200, milk=100, coffee_beans=12, cups=1, money=6)\n consumption = {1: espresso_cons, 2: latte_cons, 3: cappuccino_cons}[drink]\n try:\n self.available_check(consumption)\n except NotEnoughSupplyError as exc:\n print(exc)\n else:\n print(\"I have enough resources, making you a coffee!\")\n self.water -= consumption.water\n self.milk -= consumption.milk\n self.coffee_beans -= consumption.coffee_beans\n self.cups -= consumption.cups\n self.money += consumption.money\n</code></pre>\n\n<p>To get the <code>consumption</code> we introduce a small mapping between each drink value and each <code>Consumption</code> instances.</p>\n\n<p>Of course, instead of an exception handler you can use a classic <code>if</code>. But I wanted to show you something powerful.</p>\n\n<h2>The <code>fill</code> method</h2>\n\n<p>Again, to implement the <code>fill</code> method, you can introduce a function <code>ask_quantity</code> which ask for a quantity of a given supply. This function take a message in parameter:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def ask_quantity(msg):\n while True:\n answer = input(msg + \"\\n\")\n try:\n value = int(answer)\n if value &gt;= 0:\n return value\n print(f\"This answer is not valid: {answer}\")\n except ValueError:\n print(f\"This is not a number: {answer}\")\n</code></pre>\n\n<p>The <code>fill</code> method can be implemented as follow:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def fill(self):\n \"\"\"\n Add supplies to the machine\n \"\"\"\n self.water += ask_quantity(\"Write how many ml of water do you want to add:\")\n self.milk += ask_quantity(\"Write how many ml of milk do you want to add:\")\n self.coffee_beans += ask_quantity(\"Write how many grams of coffee beans do you want to add:\")\n self.cups += ask_quantity(\"Write how many disposable cups of coffee do you want to add:\")\n</code></pre>\n\n<h2>The <code>take</code> method.</h2>\n\n<p>Not sure to understand what the <code>take</code> method do: <em>money</em> is always reset to 0!?</p>\n\n<h2>Putting everything together</h2>\n\n<p>As you can see, I have done a lot of improvements. You can certainly go further, but write something simple and easy to read.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import collections\nimport enum\n\n\nclass Action(enum.Enum):\n BUY = \"buy\"\n FILL = \"fill\"\n TAKE = \"take\"\n EXIT = \"exit\"\n REMAINING = \"remaining\"\n\n\ndef ask_action():\n possible_values = \", \".join([action.value for action in Action])\n while True:\n answer = input(f\"Write action ({possible_values}):\\n\")\n try:\n return Action(answer)\n except ValueError:\n print(f\"This answer is not valid: {answer}\")\n\n\ndef ask_drink():\n choices = {1: \"espresso\", 2: \"latte\", 3: \"cappuccino\", 9: \"back to main menu\"}\n possible_values = \", \".join(f\"{value} - {name}\" for value, name in sorted(choices.items()))\n while True:\n answer = input(f\"What do you want to buy? ({possible_values}):\\n\")\n try:\n value = int(answer)\n if value in choices:\n return value\n print(f\"This answer is not valid: {answer}\")\n except ValueError:\n print(f\"This is not a number: {answer}\")\n\n\ndef ask_quantity(msg):\n while True:\n answer = input(msg + \"\\n\")\n try:\n value = int(answer)\n if value &gt;= 0:\n return value\n print(f\"This answer is not valid: {answer}\")\n except ValueError:\n print(f\"This is not a number: {answer}\")\n\n\nConsumption = collections.namedtuple(\"Consumption\", \"water, milk, coffee_beans, cups, money\")\n\n\nclass NotEnoughSupplyError(Exception):\n def __init__(self, supply):\n msg = f\"Sorry, not enough {supply}\"\n super(NotEnoughSupplyError, self).__init__(msg)\n\n\nclass CoffeeMachine:\n def __init__(self):\n # quantities of items the coffee machine already had\n self.water = 400\n self.milk = 540\n self.coffee_beans = 120\n self.cups = 9\n self.money = 550\n self.running = True\n\n def execute_action(self, action):\n if action == Action.BUY:\n self.buy()\n elif action == Action.FILL:\n self.fill()\n elif action == Action.TAKE:\n self.take()\n elif action == Action.EXIT:\n self.running = False\n elif action == Action.REMAINING:\n self.show_remaining()\n else:\n raise NotImplementedError(action)\n\n def available_check(self, consumption):\n \"\"\"\n Checks if it can afford making that type of coffee at the moment\n\n :param consumption: the Consumption\n :raise NotEnoughSupplyError: if at least one supply is missing.\n \"\"\"\n if self.water - consumption.water &lt; 0:\n raise NotEnoughSupplyError(\"water\")\n elif self.milk - consumption.milk &lt; 0:\n raise NotEnoughSupplyError(\"milk\")\n elif self.coffee_beans - consumption.coffee_beans &lt; 0:\n raise NotEnoughSupplyError(\"coffee beans\")\n elif self.cups - consumption.cups &lt; 0:\n raise NotEnoughSupplyError(\"cups\")\n\n def buy(self):\n drink = ask_drink()\n if drink == 9:\n return\n espresso_cons = Consumption(250, 0, 16, 1, 4)\n latte_cons = Consumption(water=350, milk=75, coffee_beans=20, cups=1, money=7)\n cappuccino_cons = Consumption(water=200, milk=100, coffee_beans=12, cups=1, money=6)\n consumption = {1: espresso_cons, 2: latte_cons, 3: cappuccino_cons}[drink]\n try:\n self.available_check(consumption)\n except NotEnoughSupplyError as exc:\n print(exc)\n else:\n print(\"I have enough resources, making you a coffee!\")\n self.water -= consumption.water\n self.milk -= consumption.milk\n self.coffee_beans -= consumption.coffee_beans\n self.cups -= consumption.cups\n self.money += consumption.money\n\n def fill(self):\n \"\"\"\n Add supplies to the machine\n \"\"\"\n self.water += ask_quantity(\"Write how many ml of water do you want to add:\")\n self.milk += ask_quantity(\"Write how many ml of milk do you want to add:\")\n self.coffee_beans += ask_quantity(\"Write how many grams of coffee beans do you want to add:\")\n self.cups += ask_quantity(\"Write how many disposable cups of coffee do you want to add:\")\n\n def take(self):\n \"\"\"\n Take the money from the machine\n \"\"\"\n print(f\"I gave you ${self.money}\")\n self.money = 0\n\n def show_remaining(self):\n \"\"\"\n Display the quantities of supplies in the machine at the moment\n \"\"\"\n print(f\"The coffee machine has:\")\n print(f\"{self.water} of water\")\n print(f\"{self.milk} of milk\")\n print(f\"{self.coffee_beans} of coffee beans\")\n print(f\"{self.cups} of disposable cups\")\n print(f\"${self.money} of money\")\n\n\ndef main():\n machine = CoffeeMachine()\n while machine.running:\n action = ask_action()\n machine.execute_action(action)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>IMO, the <em>money</em> should not be a supply like <em>water</em>...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T11:38:57.640", "Id": "471769", "Score": "1", "body": "You might want to add in your first section that `if not CoffeeMachine.running` should become `if not self.running`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:48:49.943", "Id": "471892", "Score": "2", "body": "Regarding your section on \"infinite recursion\", I'd like to point out that one state tail calling the next state is a widely-used pattern to implement state machines. And, as this question here, and many other questions on [so] show, it also seems to be a very *natural* way of modeling them, for beginners like the OP. Also, as explained by Guy L. Steele and others, tail calls are *fundamental* to OOP. So, there is nothing inherently wrong with how the OP modeled the state machine, in fact, it is *the* standard OOP way to model a state machine. It's only a limitation of Python that prevents …" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:50:31.717", "Id": "471894", "Score": "0", "body": "… the solution from working. (Some people would argue it's not so much a limitation of Python but rather a limitation of Guido van Rossum, since there are plenty of Pythonistas and Python implementors who would like Proper Tail Calls in Python, but Guido van Rossum has explicitly forbidden any Python implementation from providing them.)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T14:08:04.033", "Id": "240447", "ParentId": "240413", "Score": "27" } }, { "body": "<p>You might gain more OOP points by using more objects. </p>\n\n<p>Start by defining an exception:</p>\n\n<pre><code>class NotAvailable(Exception):\n pass\n</code></pre>\n\n<p>When something runs out, you can raise the exception and have the program return cleanly to the menu. This simplifies the flow control.</p>\n\n<p>Next, define a worker which will actually make the coffee etc:</p>\n\n<pre><code>class Worker(object):\n def __init__(self):\n pass\n\n def list_actions(self):\n return ['buy', 'fill', 'take', 'remaining']\n\n def set_state(self,water,milk,coffee_beans,cups,money ):\n # quantities of items the coffee machine already had\n self.water = water\n self.milk = milk\n self.coffee_beans = coffee_beans\n self.cups = cups\n self.money = money\n\n def available_check(self): # checks if it can afford making that type of coffee at the moment\n self.not_available = \"\" # by checking whether the supplies goes below 0 after it is deducted\n if self.water - self.reduced[0] &lt; 0:\n self.not_available = \"water\"\n elif self.milk - self.reduced[1] &lt; 0:\n self.not_available = \"milk\"\n elif self.coffee_beans - self.reduced[2] &lt; 0:\n self.not_available = \"coffee beans\"\n elif self.cups - self.reduced[3] &lt; 0:\n self.not_available = \"disposable cups\"\n\n if self.not_available != \"\": # if something was detected to be below zero after deduction\n print(f\"Sorry, not enough {self.not_available}!\")\n raise NotAvailable\n\n else: # if everything is enough to make the coffee\n print(\"I have enough resources, making you a coffee!\")\n return True\n\n def deduct_supplies(self):\n# performs operation from the reduced list, based on the coffee chosen\n self.water -= self.reduced[0]\n self.milk -= self.reduced[1]\n self.coffee_beans -= self.reduced[2]\n self.cups -= self.reduced[3]\n self.money += self.reduced[4]\n\n def buy(self):\n self.choice = input(\"What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:\\n\")\n if self.choice == '1':\n self.reduced = [250, 0, 16, 1, 4] # water, milk, coffee beans, cups, money\n self.available_check() # checks if supplies are available\n self.deduct_supplies() # if it is, then it deducts\n\n elif self.choice == '2':\n self.reduced = [350, 75, 20, 1, 7]\n self.available_check()\n self.deduct_supplies()\n\n elif self.choice == \"3\":\n self.reduced = [200, 100, 12, 1, 6]\n self.available_check() \n self.deduct_supplies() \n\n elif self.choice != 'back':\n print (\"Choice not recognised\")\n\n\n def fill(self): # for adding supplies to the machine\n self.water += int(input(\"Write how many ml of water do you want to add:\\n\"))\n self.milk += int(input(\"Write how many ml of milk do you want to add:\\n\"))\n self.coffee_beans += int(input(\"Write how many grams of coffee beans do you want to add:\\n\"))\n self.cups += int(input(\"Write how many disposable cups of coffee do you want to add:\\n\"))\n\n def take(self): # for taking the money from the machine\n print(f\"I gave you ${self.money}\")\n self.money -= self.money\n\n def remaining(self): # to display the quantities of supplies in the machine at the moment\n print(f\"The coffee machine has:\")\n print(f\"{self.water} of water\")\n print(f\"{self.milk} of milk\")\n print(f\"{self.coffee_beans} of coffee beans\")\n print(f\"{self.cups} of disposable cups\")\n print(f\"${self.money} of money\")\n</code></pre>\n\n<p>This is mainly your code, but I have change <code>available_check()</code> to raise the exception defined above, and removed the <code>return_to_menu()</code> method because the worker will simply finish working when it is finished.</p>\n\n<p>Finally, the machine itself:</p>\n\n<pre><code>class CoffeeMachine(object):\n def __init__(self, water,milk,coffee_beans,cups,money ):\n \"\"\"The coffee machine starts itself on initialisation.\n When running, it asks the user to select a task, and then passes the task to the worker.\n \"\"\"\n\n self.worker = Worker()\n self.worker.set_state(water,milk,coffee_beans,cups,money)\n self.start()\n\n def start(self):\n \"\"\"Start the machine running.\n Continue running until exit is requested\n \"\"\"\n\n self.running = True\n while self.running:\n action = input(\"Write action (%s) or exit:\\n\" % ', '.join( self.worker.list_actions() ) )\n if action == 'exit':\n self.running = False\n elif action in self.worker.list_actions():\n self.execute_task(action)\n else:\n print (\"INVALID OPTION -- PLEASE TRY AGAIN\")\n\n def execute_task(self,action):\n \"\"\"Execute a task, calling the worker method named in the action variable.\n The NotAvailable exception is caught\n \"\"\"\n\n try:\n return getattr( self.worker, action)()\n except NotAvailable:\n print (\"Please make another choice (%s not available)\" % self.worker.not_available)\n\ncm = CoffeeMachine(400, 540, 120, 9, 550)\n</code></pre>\n\n<p>Defining the worker as a separate object gives a clearer separation between the different tasks in your programming challenge.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T23:33:29.143", "Id": "240762", "ParentId": "240413", "Score": "1" } } ]
{ "AcceptedAnswerId": "240447", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T19:25:04.430", "Id": "240413", "Score": "24", "Tags": [ "python", "python-3.x", "object-oriented" ], "Title": "Simulating an OOP Coffee Machine" }
240413
<p>It's been a while I program in ANSI C, and helping my brother with a school project I ended up revising my C gift (or lack of) :)</p> <p>the idea was to create an inverted V process using <code>fork()</code> and I ended up with the code that <a href="https://github.com/balexandre/invert-tree-c" rel="nofollow noreferrer">you can find in GitHub</a></p> <p>I was wondering if there's an easy way of accomplish it, as I see that I might be able to refactor it as there's code that is equal in some lines, but I could never got it to have the same output</p> <p>This is only for curiosity as the work is already presented in school but I always thrive to learn better and I keep wonder if we can refactor the block below</p> <pre class="lang-c prettyprint-override"><code>pid = fork(); switch (pid) { case -1: printf("fork failed\n"); break; case 0: printf("Process %s%d %d, from %d\n", colLetter, currentRow, getpid(), getppid()); currentRow += 1; // process 1 fork and his child process_single_tree(colLetter, maxInteractions, currentRow); break; default: break; } </code></pre> <p>to only have one iteration and not having to similar blocks in the code</p> <hr> <p><strong>Added</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/wait.h&gt; #define MIN 0 #define MAX 32 /** * Validates if the interaction number is between the acceptable range * @param int lines to process * @return nothing */ void validateInteractions(int interactions) { if (interactions &lt; MIN || interactions &gt; MAX) { printf("Level must be between %d and %d", MIN, MAX); exit(1); } } /** * Validates if there are enough arguments * @param int number of arguments (argc) * @return nothing */ void validateArguments(int arguments) { if (arguments &lt; 2) { printf("A decimal argument must be declared"); exit(1); } } /** * Processes a single fork() and his child * @param char the column Letter that the column belongs * @param int the max interactions to process * @param int the current row id * @return nothing */ void process_single_tree(char *colLetter, int maxInteractions, int currentRow) { int pid; int status; if (currentRow &gt; maxInteractions) { exit(0); } pid = fork(); switch (pid) { case -1: printf("fork failed\n"); break; case 0: printf("Process %s%d %d, from %d\n", colLetter, currentRow, (int)getpid(), (int)getppid()); currentRow += 1; // process 1 fork and his child process_single_tree(colLetter, maxInteractions, currentRow); break; default: break; } wait(&amp;status); } /** * Processes double fork() and their childs * @param int the max interactions to process * @param int the current row id * @return nothing */ void process_double_tree(int maxInteractions, int currentRow) { int i; int index = 2; // process twice int pid; int status; char *colLetter; // column letter for (i = 1; i &lt;= index; i++) { colLetter = i == 1 ? "A" : "B"; if (currentRow &gt; 1) exit(0); pid = fork(); switch (pid) { case -1: printf("fork failed\n"); break; case 0: printf("Process %s%d %d, from %d\n", colLetter, currentRow, (int)getpid(), (int)getppid()); currentRow += 1; // process 1 fork and his child process_single_tree(colLetter, maxInteractions, currentRow); break; default: break; } } for (i = 0; i &lt; index; i++) { wait(&amp;status); } } int main(int argc, char *argv[]) { int interactions; int currentRow = 1; // check if "argv[1]" is valid validateArguments(argc); interactions = atoi(argv[1]); // check if level is between MIN and MAX validateInteractions(interactions); printf("Inverted V process tree with n=%d\n", interactions); printf("Process AB has PID=%d\n", (int)getpid()); // there are levels to process if (interactions &gt; 0) { // create 2 forks and process each child process_double_tree(interactions, currentRow); } } </code></pre> <p><em>edited</em> added as suggested, as pid's should be cast</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:29:07.090", "Id": "471568", "Score": "1", "body": "Welcome to code review where we review working code from projects to provide suggestions on how that code can be improved. This question is off-topic because it doesn't provide enough code to review. We would need to see at least the entire function this snippet is a part of, but preferably we would like to see the entire code of the project. For instance the code references a function called `process_single_tree()` but that function is not included for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T22:53:34.387", "Id": "471576", "Score": "0", "body": "@pacmaninbw isn't that the point of the GitHub url, it's only [one `.c` file](https://github.com/balexandre/invert-tree-c/tree/master/src) :) - should I be more explicit on the file in question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T23:02:42.327", "Id": "471578", "Score": "1", "body": "The code to be reviewed must be included in the question, a link is fine for a full project. Snippets might be okay on stackoverflow, but they are not okay on code review. Please take a look at https://codereview.stackexchange.com/help/how-to-ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T23:12:25.167", "Id": "471579", "Score": "2", "body": "Unless you post your code here in your question then for legal reasons we cannot touch your code. Your code is not available under any copyright meaning that any review of your code we perform is potentially copyright infringement. For this reason we have the \"authorship\" close reason, so we can protect users that could be subjected to copyright trolling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T23:19:28.143", "Id": "471580", "Score": "3", "body": "so, very diff from StackOverflow... thank you to point out the rules for me! I've added the code to the question :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T23:19:46.583", "Id": "471581", "Score": "2", "body": "Note: `getpid()` does not certainly return an `int` and so `\"%d\"` is not certainly the correct specifier. Suggest [What is the correct printf specifier for printing pid_t](https://stackoverflow.com/q/20533606/2410359)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T23:23:17.837", "Id": "471582", "Score": "1", "body": "Thank you for adding the code to the question. I have retracted my close vote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T23:25:40.337", "Id": "471583", "Score": "1", "body": "Close vote retracted." } ]
[ { "body": "<h2>stderr</h2>\n\n<p>Consider printing your errors to <code>stderr</code>; for example:</p>\n\n<pre><code> printf(\"Level must be between %d and %d\", MIN, MAX);\n</code></pre>\n\n<p>can be</p>\n\n<pre><code> fprintf(stderr, \"Level must be between %d and %d\", MIN, MAX);\n</code></pre>\n\n<h2>colLetter</h2>\n\n<p>If this is actually a letter, is there any reason you can't pass it around as a <code>char</code> instead of a <code>char*</code> string?</p>\n\n<h2>perror</h2>\n\n<pre><code>printf(\"fork failed\\n\");\n</code></pre>\n\n<p>Based on <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html\" rel=\"nofollow noreferrer\">the spec</a>, this modifies <code>errno</code>, so you are best to use <code>perror</code> here instead of <code>printf</code>.</p>\n\n<h2>Casting prior to printf</h2>\n\n<p><code>getpid</code> actually returns a <code>pid_t</code>, which might not be guaranteed to fit in an <code>int</code>. In fact, <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_types.h.html\" rel=\"nofollow noreferrer\">the spec</a> says that</p>\n\n<blockquote>\n <p>The implementation shall support one or more programming environments in which the widths of <code>pid_t</code> [...] are no greater than the width of type long. </p>\n</blockquote>\n\n<p>So to avoid overflow, you're safer to cast this to a <code>long</code> and print with <code>%l</code>.</p>\n\n<h2>No-op default</h2>\n\n<p>This:</p>\n\n<pre><code>default:\n break;\n</code></pre>\n\n<p>can be omitted.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T01:04:52.087", "Id": "240476", "ParentId": "240416", "Score": "1" } }, { "body": "<p>regarding:</p>\n\n<pre><code>printf(\"fork failed\\n\");\n</code></pre>\n\n<p>error messages should be output to <code>stderr</code> and when the error is from a C library function, should also output the text reason the system thinks the error occurred. Suggest:</p>\n\n<pre><code>perror( \"fork failed\" );\n</code></pre>\n\n<p>which handles both output activities</p>\n\n<p>regarding: </p>\n\n<pre><code>interactions = atoi(argv[1]); \n</code></pre>\n\n<p>Always check <code>argc</code> to assure the user actually entered the expected command line parameter (if not, then output to <code>stderr</code> a USAGE message) before accessing anything beyond <code>argv[0]</code>. Other wise, when the expected command line parameter has not been entered by the user, accessing beyond <code>argv[0]</code> will result in a seg fault event. without the user having any idea as to why</p>\n\n<p>regarding:</p>\n\n<pre><code>printf(\"A decimal argument must be declared\");\n</code></pre>\n\n<p>This outputs an error message to <code>stdout</code> rather than to <code>stderr</code>. Suggest:</p>\n\n<pre><code>fprintf( stderr, \"USAGE: %s decimal argument\\n\", argv[0] );\n</code></pre>\n\n<p>regarding:</p>\n\n<pre><code>case 0:\n printf(\"Process %s%d %d, from %d\\n\", colLetter, currentRow, (int)getpid(), (int)getppid());\n currentRow += 1;\n // process 1 fork and his child\n process_single_tree(colLetter, maxInteractions, currentRow);\n break;\n\ndefault:\n break;\n}\n\nwait(&amp;status);\n</code></pre>\n\n<p>This will have the child process (along with the parent process) calling <code>wait()</code> Suggest:</p>\n\n<pre><code>case 0:\n printf(\"Process %s%d %d, from %d\\n\", colLetter, currentRow, (int)getpid(), (int)getppid());\n currentRow += 1;\n // process 1 fork and his child\n process_single_tree(colLetter, maxInteractions, currentRow);\n exit( EXIT_SUCCESS ); &lt;&lt;-- added statement\n break;\n\ndefault:\n wait(&amp;status);\n break;\n}\n</code></pre>\n\n<p>regarding:</p>\n\n<pre><code>interactions = atoi(argv[1]);\n</code></pre>\n\n<p>The function: <code>atoi()</code> can fail and it will not notify you of this event. Suggest using the function: <code>strtol()</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T01:45:10.493", "Id": "240478", "ParentId": "240416", "Score": "1" } } ]
{ "AcceptedAnswerId": "240478", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T21:07:35.647", "Id": "240416", "Score": "2", "Tags": [ "c" ], "Title": "Inverted V process tree" }
240416
<p>I am trying to prove the famous <a href="https://www.statisticshowto.com/probability-and-statistics/monty-hall-problem/" rel="nofollow noreferrer">"Monty Hall Paradox"</a>: </p> <blockquote> <p>The Monty Hall problem is a probability puzzle named after <strong>Monty Hall</strong>, the original host of the TV show <strong><em>Let’s Make a Deal</em></strong>. It’s a famous paradox that has a solution that is so absurd, most people refuse to believe it’s true.</p> </blockquote> <pre><code>private static void suffle(ulong numberOfTries) { int correctHits = 0; int wrongHits = 0; var prizeIndex = new Random(); for (ulong i = 1; i &lt;= numberOfTries; i++) { int[] doors = { 1, 2, 3 }; var prizeDoor = doors[prizeIndex.Next(0, doors.Length)] ; var selectedDoor = doors[prizeIndex.Next(0, doors.Length)]; int discardedDoor = doors[prizeIndex.Next(0, doors.Length)]; while (discardedDoor == prizeDoor || discardedDoor == selectedDoor) { discardedDoor = doors[prizeIndex.Next(0, doors.Length)]; } var correctGuess = selectedDoor == prizeDoor; if (correctGuess) correctHits++; else wrongHits++; Console.WriteLine($"Prize Door: {prizeDoor}\nSelected Door: {selectedDoor}\nDiscarded Door: {discardedDoor}\nRight Guess? {correctGuess}\n\n"); } Console.WriteLine($"Right Guesses: {correctHits} / {numberOfTries}\nWrong Guesses: {wrongHits} / {numberOfTries}"); } </code></pre>
[]
[ { "body": "<p>your code is pretty neat and readable. Shuffling algorithm looks reliable to me, however I have a few comments to your C# code.</p>\n\n<ol>\n<li>You pass the argument <code>numberOfTries</code> as <code>ulong</code> type, but <code>correctHits</code> and <code>wrongHits</code> are <code>int</code>. It could lead to wrong output if the <code>numberOfTries</code> is large enough to overflow <code>int.MaxValue</code>.</li>\n<li>Variable doors are initialized in each loop. It could be initialized once in higher scope, e.g. before the <code>for</code> loop.</li>\n<li><p>I can see repetetive code <code>doors[prizeIndex.Next(0, doors.Length)]</code>. This piece of code could be refactored to isolated method. For example:</p>\n\n<p>private static int GetDoorNumber() => _doors[_prizeIndex.Next(0, _doors.Length)];</p></li>\n<li><p>You can save couple of code lines introducing ternary operator. Then you do not need variable correctGuess.</p>\n\n<p>correctHits += (selectedDoor == prizeDoor) ? 1 : 0;</p></li>\n</ol>\n\n<p>You can calculate <code>wrongHits</code> as a difference of numberOfTries and correctHits. But your solution works too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T21:41:20.313", "Id": "240595", "ParentId": "240422", "Score": "2" } } ]
{ "AcceptedAnswerId": "240595", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-12T23:14:01.993", "Id": "240422", "Score": "2", "Tags": [ "c#", "random" ], "Title": "Could anyone say if this is a reliable shuffling code?" }
240422
<p>Below is my honest attempt to write thread safe queue using C++11 features. Please review it and provide your comments. </p> <pre><code>#include &lt;queue&gt; #include &lt;condition_variable&gt; #include &lt;atomic&gt; #include &lt;iostream&gt; template &lt;typename T&gt; class ThreadSafeQueue { std::queue&lt;T&gt; m_queue; std::mutex m_mutex; public : void Push(const T&amp; data) { std::lock_guard&lt;std::mutex&gt; lock(m_mutex); m_queue.push(data); } // Universal reference template &lt;typename ...Args&gt; void Emplace(Args&amp;&amp;... args) { std::lock_guard&lt;std::mutex&gt; lock(m_mutex); m_queue.emplace(std::forward&lt;Args&gt;(args)...); } void PopFront(T&amp; data) { std::lock_guard&lt;std::mutex&gt; lock(m_mutex); data = m_queue.front(); m_queue.pop(); } void PopFrontNoLock(T&amp; data) { data = m_queue.front(); m_queue.pop(); } size_t Size() { std::lock_guard&lt;std::mutex&gt; lock(m_mutex); return m_queue.size(); } bool Empty() { std::lock_guard&lt;std::mutex&gt; lock(m_mutex); return m_queue.empty(); } bool EmptyNoLock() { return m_queue.empty(); } std::mutex&amp; GetMutex() { return m_mutex; } }; template &lt;typename T&gt; class ReaderWriterQueue { ThreadSafeQueue&lt;T&gt; m_safeQueue{}; std::condition_variable m_condVar{}; std::atomic&lt;bool&gt; m_writeCompleted{}; public : void Push(const T&amp; data) { m_safeQueue.Push(data); m_condVar.notify_one(); } // Universal reference template &lt;typename ...Args&gt; void Emplace(Args&amp;&amp;... args) { m_safeQueue.Emplace(std::forward&lt;Args&gt;(args)...); m_condVar.notify_one(); } void PopFront(T&amp; data) { std::unique_lock&lt;std::mutex&gt; lock(m_safeQueue.GetMutex()); m_condVar.wait(lock, [this] {return (!m_safeQueue.EmptyNoLock() || m_writeCompleted); }); m_safeQueue.PopFrontNoLock(data); } void NotifyWriteEnd() { m_writeCompleted = true; } bool IsWriteFinished() const { return m_writeCompleted; } bool Empty() { return m_safeQueue.Empty(); } }; </code></pre> <p>Driver code to test thread safe queue:</p> <pre><code>void ProduceData(ReaderWriterQueue&lt;int&gt;&amp; queue) { int i = 0; while (i &lt; 10) { queue.Emplace(i); i++; } queue.NotifyWriteEnd(); std::cout &lt;&lt; "Finished Writing" &lt;&lt; std::endl; } void ReadData(ReaderWriterQueue&lt;int&gt;&amp; queue) { while (!queue.IsWriteFinished() || !queue.Empty()) { int waitTime; queue.PopFront(waitTime); std::cout &lt;&lt; "popped " &lt;&lt; waitTime &lt;&lt; "\n"; std::this_thread::sleep_for(std::chrono::seconds(waitTime)); } std::cout &lt;&lt; "Finished Reading" &lt;&lt; std::endl; } int main() { ReaderWriterQueue&lt;int&gt; rwQueue; std::thread writer(ProduceData, std::ref(rwQueue)); const int readerThreadCount = 2; std::thread readers[readerThreadCount]; for (int count=0; count &lt; readerThreadCount; count++) { std::thread reader(ReadData, std::ref(rwQueue)); readers[count] = std::move(reader); } if (writer.joinable()) { writer.join(); } for (int count = 0; count &lt; readerThreadCount; count++) { if (readers[count].joinable()) { readers[count].join(); } } return 0; } </code></pre>
[]
[ { "body": "<p>There's no way to notify locked consumers of the write end. You might want to modify <code>PopFront</code> and <code>NotifyWriteEnd</code> to return a special null value to every awaiting consumer (or otherwise wake up all the awaiting consumers and notify them the queue is exhausted) when <code>NotifyWriteEnd()</code> is called. Otherwise you'll need a rather serious contract inherent in your application design, that every consumer should know <em>in advance</em> that it <em>would be able</em> to get a matching producer before starting awaiting on the queue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T06:12:57.957", "Id": "240432", "ParentId": "240431", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T05:45:29.130", "Id": "240431", "Score": "3", "Tags": [ "c++", "c++11", "multithreading", "queue" ], "Title": "Thread safe reader-writer queue with C++11" }
240431
<p>I've always found the boilerplate needed to use <a href="https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html#index-getopts" rel="nofollow noreferrer"><code>getopts</code></a> correctly fairly fiddly and verbose, and was motivated to try to abstract it away. I wanted to try dynamically writing the parsed arguments into <code>local</code> variables accessible to the calling function, and I came up with this:</p> <pre><code>main() { local _usage='foo [-a] [-b] [-f val] [-v val] [args ...]' eval &quot;$(parse_opts 'f:v:ab')&quot; echo &quot;f=$f v=$v a=$a b=$b -- $#: $*&quot; } main &quot;$@&quot; </code></pre> <p>Yes, it uses <code>eval</code>, but given the alternative (a crufty <code>while</code> loop and <code>case</code> statement), I think it's still an improvement.</p> <p>I'm looking for any general feedback about this approach and implementation. Can I reduce the amount of code being <code>eval</code>ed? Anything I can simplify or improve? Any edge cases or bugs I've missed?</p> <p>Relevant code/docs:</p> <pre><code># Helper utility to simplify using Bash's getopts utility, and make it # usable with functions. # # Example usage: # foo() { # local _usage=... # optional usage string # eval &quot;$(parse_opts 'f:v:ab')&quot; # provide a standard getopts string # echo &quot;f is $f&quot; # opts are now local variables # if (( a )); then # check boolean flags with (( ... )) # echo &quot;Saw -a&quot; # fi # } # # This script eliminates the gruntwork and verbosity of using getopts, # allowing you to focus on actual behavior rather than argument parsing. # It handles looping over getopts, parsing each result, and reporting # errors. Each parsed option is set as a local variable in the calling # function, enabling easy and safe access to all values. # # No-arg options are set to 0 by default and 1 if passed as an # argument, allowing concise testing with (( ... )). # # Options that accept an argument are set to the empty string by # default, and otherwise set to the value passed as an argument. # To check if a (non-empty) argument was passed use [[ -n &quot;$...&quot; ]]. # # All parsed arguments are shift-ed out of $@, leaving any # subsequent positional arguments in-place. A -- argument can be # used to halt option parsing early, e.g. `-a -- -b` will only # parse -a and leave -b as an argument. # # Parsing errors cause the calling function to return with exit # code 2. If a _usage variable is set before argument parsing # its contents will be included in the error message. # # Actual parser implementation; assumes all variables it sets # are local, which parse_opts sets up. Do not call directly. _parse_opts_helper() { local OPTARG opt optstring=${1:?optstring}; shift # ensure string _is_ prefixed with : while getopts &quot;:${optstring#:}&quot; opt; do case &quot;${opt}&quot; in [?:]) case &quot;${opt}&quot; in :) echo &quot;Option '-${OPTARG}' requires an argument&quot; &gt;&amp;2 ;; [?]) echo &quot;Unknown option '-${OPTARG}'&quot; &gt;&amp;2 ;; esac if [[ -n &quot;$_usage&quot; ]]; then echo &quot;Usage: $_usage&quot; &gt;&amp;2 fi return 2 ;; *) if [[ &quot;$optstring&quot; != *&quot;${opt}:&quot;* ]]; then OPTARG=1 fi printf -v &quot;$opt&quot; '%s' &quot;$OPTARG&quot; ;; esac done } # The output of this function is intended to be passed to eval, # therefore we try to minimize what it prints and delegate most # of the heavy lifting to a separate function. # Expected output: # local OPTIND=1 a b c=0 # vars are dynamically parsed # _parse_opts_helper a:b:c &quot;$@&quot; || return # shift $((OPTIND - 1)) # OPTIND=1 parse_opts() { local i char last_char vars=() optstring=${1:?optstring} optstring=&quot;${optstring#:}&quot; # ensure string is not prefixed with : if ! [[ &quot;$optstring&quot; =~ ^[a-zA-Z:]*$ ]] || [[ &quot;$optstring&quot; == *::* ]]; then echo &quot;Invalid optstring: $optstring&quot; &gt;&amp;2 return 2 fi for (( i=${#optstring}-1 ; i &gt;= 0 ; i-- )); do char=${optstring:i:1} if [[ &quot;$char&quot; != &quot;:&quot; ]]; then if [[ &quot;$last_char&quot; == &quot;:&quot; ]]; then vars+=(&quot;$char&quot;) else vars+=(&quot;${char}=0&quot;) fi fi last_char=$char done echo &quot;local OPTIND=1 ${vars[*]}&quot; printf '_parse_opts_helper %q &quot;$@&quot; || return\n' &quot;$optstring&quot; echo 'shift $((OPTIND - 1))' echo 'OPTIND=1' } </code></pre> <p>Pulled from <a href="https://gist.github.com/dimo414/93776b78a38791ed1bd1bad082d08009" rel="nofollow noreferrer">this gist</a> which will likely be kept more up-to-date than the code pasted here.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T09:57:49.553", "Id": "240436", "Score": "1", "Tags": [ "bash", "console", "meta-programming" ], "Title": "Simplified Bash getopts flow" }
240436
<p>What do you think of using <code>struct Board(Vec&lt;Vec&lt;Cell&gt;&gt;)</code>? It's nice that I can attach the <code>Display</code> trait, and just print the board.</p> <p>But on the flip-side, we have things that seem wrong, like:</p> <pre class="lang-rust prettyprint-override"><code>fn next_step(b: Board) -&gt; Board { let Board(mut board) = b; // ... Board(board) } </code></pre> <p>And I couldn't find a way to pass a <code>Board</code> (or a reference to one) to <code>nr_of_neighbors</code>. Moving the <code>Vec</code> out in <code>next_step</code> (or similarly when using a mutable reference there), prevented me from doing that. Or am I missing something?</p> <p>Any additional feedback welcome as well!</p> <ul> <li>Note: it's a <code>Vec</code> instead of an <code>array</code> in case I add the feature that the player can choose the board size interactively.</li> <li>I know the <code>as i64</code> isn't that great. Not sure though what's a nice, practical and concise way of dealing with that though.</li> </ul> <h3>Complete working code</h3> <p>Should run in any ANSI-compatible terminal.</p> <pre class="lang-rust prettyprint-override"><code>use itertools::join; use std::fmt; use std::{thread, time}; #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Cell { Aliv, Dead } impl fmt::Display for Cell { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { match *self { Cell::Aliv =&gt; write!(f, "x"), Cell::Dead =&gt; write!(f, " "), } } } struct Board(Vec&lt;Vec&lt;Cell&gt;&gt;); impl fmt::Display for Board { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { let Board(vec) = self; let str = join(vec.into_iter().map(|row| join(row, "|")), "\n"); write!(f, "{}", str) } } fn main() { let mut board = Board(vec![ vec![Cell::Aliv, Cell::Aliv, Cell::Aliv, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], vec![Cell::Aliv, Cell::Dead, Cell::Aliv, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], vec![Cell::Aliv, Cell::Aliv, Cell::Aliv, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], vec![Cell::Dead, Cell::Aliv, Cell::Aliv, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead], ]); loop { print!("{esc}[2J{esc}[1;1H", esc = 27 as char); // clear ANSI-compatible terminal println!("{}", board); board = next_step(board); thread::sleep(time::Duration::from_secs(1)); } } fn next_step(b: Board) -&gt; Board { let Board(mut board) = b; for x in 0..board.len() { for y in 0..board[x].len() { let n = nr_of_neighbors(&amp;board, x, y); let cell = board[x][y]; if cell == Cell::Aliv &amp;&amp; (n == 2 || n == 3) { // survives } else if cell == Cell::Dead &amp;&amp; n == 3 { board[x][y] = Cell::Aliv; } else { board[x][y] = Cell::Dead; } } } Board(board) } fn nr_of_neighbors(board: &amp;Vec&lt;Vec&lt;Cell&gt;&gt;, current_x: usize, current_y: usize) -&gt; u32 { let cur_x = current_x as i64; let cur_y = current_y as i64; let mut count: u32 = 0; for x in cur_x-1..cur_x+2 { for y in cur_y-1..cur_y+2 { if x &gt;=0 &amp;&amp; y &gt;= 0 &amp;&amp; x &lt; board.len() as i64 &amp;&amp; y &lt; board[x as usize].len() as i64 &amp;&amp; !(x == cur_x &amp;&amp; y == cur_y) &amp;&amp; board[x as usize][y as usize] == Cell::Aliv { count = count + 1; } } } count } </code></pre>
[]
[ { "body": "<h2>On your notes:</h2>\n\n<ul>\n<li><p>Problems with <code>u64</code>/<code>u32</code> got fixed once I started using <code>usize</code> everywhere. </p></li>\n<li><p>Board shouldn't be copied every time in <code>next_step</code>, <code>&amp;mut Board</code> could be used instead.</p></li>\n<li><p><code>next_step</code>, as well as <code>nr_of_neighbors</code> could be a methods.</p></li>\n</ul>\n\n<h2>Bugs:</h2>\n\n<ul>\n<li><p>There is a bug in calculating number of neighbors: your condition <code>!(x == cur_x &amp;&amp; y == cur_y)</code> is equivalent to <code>x != cur_x || y != cur_y</code>, which is not intended.</p></li>\n<li><p>There is a problem with your algorithm: it depends on the order of the iteration, when you should really apply changes to the new board.</p></li>\n</ul>\n\n<h2>Notes about the code below</h2>\n\n<ul>\n<li>You are using <code>newtype</code> pattern to implement traits that you need on the type that doesn't do it itself. I advise you to look into <code>derive_more</code> crate. Basically, I derived a <code>Deref</code> implementation in order not to write it myself. That way, everywhere where &amp;Board is used, it can be coerced to &amp;Vec> so you don't have to write <code>self.0[x]</code> to access a row.</li>\n</ul>\n\n<h2>Resulting code</h2>\n\n<pre><code>use std::fmt;\nuse std::{thread, time};\n\nuse itertools::join;\nuse itertools::Itertools;\n\nuse derive_more::Deref;\n\n#[repr(u8)]\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\nenum Cell {\n Alive,\n Dead,\n}\n\nimpl fmt::Display for Cell {\n fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {\n match *self {\n Cell::Alive =&gt; write!(f, \"x\"),\n Cell::Dead =&gt; write!(f, \" \"),\n }\n }\n}\n\n#[derive(Deref)]\nstruct Board(Vec&lt;Vec&lt;Cell&gt;&gt;);\n\nimpl Board {\n fn nr_of_neighbors(&amp;self, cur_x: usize, cur_y: usize) -&gt; usize {\n let x_min = cur_x.saturating_sub(1);\n let y_min = cur_y.saturating_sub(1);\n\n let x_max = (cur_x + 2).min(self.len() - 1);\n let y_max = (cur_y + 2).min(self.len() - 1);\n\n (x_min..x_max)\n .cartesian_product(y_min..y_max)\n .filter(|&amp;(x, y)| x != cur_x &amp;&amp; y != cur_y &amp;&amp; self[x][y] == Cell::Alive)\n .count()\n }\n\n fn next_step(&amp;mut self) {\n let mut new_board = self.clone();\n\n for x in 0..self.len() {\n for y in 0..self[x].len() {\n let n = self.nr_of_neighbors(x, y);\n let cell = self[x][y];\n\n if cell == Cell::Alive &amp;&amp; (n == 2 || n == 3) {\n // survives\n } else if cell == Cell::Dead &amp;&amp; n == 3 {\n new_board[x][y] = Cell::Alive;\n } else {\n new_board[x][y] = Cell::Dead;\n }\n }\n }\n\n self.0 = new_board;\n }\n}\n\nimpl fmt::Display for Board {\n fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {\n write!(f, \"{}\", join(self.iter().map(|row| join(row, \"|\")), \"\\n\"))\n }\n}\n\nfn main() {\n #[rustfmt::skip]\n let mut board = Board(vec![\n vec![Cell::Alive, Cell::Alive, Cell::Alive, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n vec![Cell::Alive, Cell::Dead, Cell::Alive, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n vec![Cell::Alive, Cell::Alive, Cell::Alive, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n vec![Cell::Dead, Cell::Alive, Cell::Alive, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n vec![Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead, Cell::Dead],\n ]);\n\n loop {\n print!(\"{esc}[2J{esc}[1;1H\", esc = 27 as char); // clear ANSI-compatible terminal\n println!(\"{}\\n\", board);\n board.next_step();\n thread::sleep(time::Duration::from_secs(1));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:45:47.310", "Id": "471798", "Score": "0", "body": "very cool thanks! I didn't know about `saturating_sub` and `derive_more` of course... hm.. but you still have to copy the whole board `new_board = self.clone();` which doesn't seem very efficient? or is it some lazy cloning? couldn't find what clone does for Vec in the docs..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:18:04.600", "Id": "471811", "Score": "0", "body": "@mb21, that's not about efficiency, but correctness of algorithm - you can't mutate the board you are currently working on. I believe there is a dynamic programming solution, but I'm not sure. There could be 2 Vecs inside the Board, so that you don't reallocate every iteration and at the end of `next_step` you just make a swap. Or a cell can contain two states - current and future, which will improve data locality. If you care about efficiency I recommend using Vec<Cell> instead of Vec<Vec<Cell>>, so that there's no extra indirection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T07:01:20.703", "Id": "471850", "Score": "0", "body": "Ah, of course. Can't believe I missed that... have been working too much with immutable structures (in other langs). One last question: is using methods instead of functions generally favoured in Rust? or is it more of a stylistic choice, where OOP people use methods and functional people use functions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T14:27:37.807", "Id": "471882", "Score": "0", "body": "@mb21 I think it's a choice, but I'm learning rust just like you." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:09:03.210", "Id": "240505", "ParentId": "240437", "Score": "3" } }, { "body": "<p>Generally, you should only put a <code>Vec</code> inside of a <code>Vec</code> if the inner <code>Vec</code> will have a dynamic size. Otherwise, you lose a lot of performance due to indirection (you have a pointer to an array of pointers, which points to each row), which screws with the CPU cache. Instead, you should use a single <code>Vec</code> which has a size of <code>width * height</code>. This pattern is so common that there's a crate to do just that—<a href=\"https://docs.rs/ndarray/0.13.0/ndarray/macro.array.html\" rel=\"nofollow noreferrer\">ndarray</a> (see also <a href=\"https://docs.rs/ndarray/0.13.0/ndarray/struct.ArrayBase.html#indexing-and-dimension\" rel=\"nofollow noreferrer\">this</a>). However, you could also write your own wrapper functions that multiply the column by the width and add the height.</p>\n\n<blockquote>\n <p>is using methods instead of functions generally favoured in Rust? or is it more of a stylistic choice, where OOP people use methods and functional people use functions?</p>\n</blockquote>\n\n<p>It really depends. When using the newtype pattern (which you are), absolutely use methods—it's the most ergonomic option. However, using free functions is a great idea when working with other types where it doesn't make sense to have a struct. You should think of structs as data, not logic. Using a struct to hold data and using functions to operate on that data is great. However, using a struct to hold logic generally means that you should rethink your layout. That's not always the case, but is a good start.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T22:34:46.540", "Id": "240653", "ParentId": "240437", "Score": "3" } } ]
{ "AcceptedAnswerId": "240505", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T10:16:49.823", "Id": "240437", "Score": "4", "Tags": [ "rust", "game-of-life" ], "Title": "Rust Conway's Game of Life: struct Board(Vec<Vec<Cell>>)" }
240437
<p>The script calls the sunrise-sunset API to get one of the possible values, then converts it to 24-Hour format and MET time (as the times from the API are 12-hour and UTC). At the end, it joins the list to a string and prints it. I know this isn't commented very well, but are there any significant flaws in this code? I neither have any experience with Python nor with programming in general, this is just for a personal project and Python seemed to be the best way to do this, so I'm open for any advice and help.</p> <pre><code>import json import urllib.request as request def apiGetList(key): """ Function twilightApiGetList(key): Calls the sunrise-sunset api to return the value of a given key Possible keys: sunrise, sunset, solar_noon, day_length, civil_twilight_begin, civil_twilight_end, nautical_twilight_begin, nautical_twilight_end, astronomical_twilight_begin, astronomical_twilight_end All times returned are a list in 12-hour format, UTC time """ with request.urlopen('https://api.sunrise-sunset.org/json?lat=44.244622&amp;lng=-7.768863&amp;date=today') as response: if response.getcode() == 200: source = response.read() data = json.loads(source) out = list(f"{data['results'][key]}") if len(out) == 10: out.insert(0, '0') else: pass return(out) else: print("Not successful") return def convert12To24(lst): """ Function convert12To24(lst): Converts from 12-hour format to 24-hour format, input and output types are lists """ if lst[9] == "A" and "".join(lst[0:2]) == "12": del lst[8:12] lst[0:2] = '00' elif lst[9] == "A": del lst[8:12] elif lst[9] == "P" and "".join(lst[0:2]) == "12": del lst[8:12] else: del lst[8:12] lst[0:2] = str(int("".join(lst[0:2])) + 12) return(lst) def convertUtcToMet(time): """ Function convertUtcToMet(time): Converts from UTC time to MET time by adding two hours. Input and output time is in 24-hour format, type is a list """ if int("".join(time[0:2])) &lt; 8: time[0:2] = str(int("".join(time[0:2])) + 2) time.insert(0, '0') elif "".join(time[0:2]) == '22': time[0:2] = '00' elif "".join(time[0:2]) == '23': time[0:2] = '01' else: time[0:2] = str(int("".join(time[0:2])) + 2) return(time) if __name__ == "__main__": ctb = apiGetList("civil_twilight_begin") cte = apiGetList("civil_twilight_end") print("".join(convertUtcToMet(convert12To24(ctb)))) print("".join(convertUtcToMet(convert12To24(cte)))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T15:18:42.723", "Id": "471649", "Score": "0", "body": "Is MET Middle-European Time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T15:22:43.577", "Id": "471650", "Score": "0", "body": "If so, MET only has a one-hour offset from UTC, not 2...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T16:05:03.717", "Id": "471654", "Score": "0", "body": "Also, are you on a boat? Those coordinates are in the Atlantic Ocean north of Portugal - which is not in MET." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T16:16:31.650", "Id": "471657", "Score": "0", "body": "I'm guessing now, but it might be that you have an accidental negative sign in your longitude - the positive longitude would put you in Italy south of Turin, which is probably (?) in the timezone that you indicate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T08:12:10.820", "Id": "471742", "Score": "0", "body": "@Reinderien Don't worry about these coordinates, I changed the real location for random numbers so that I wouldn't reveal my location! I'm actually located in Germany. Also, you are right, I didn't look up the time difference between UTC and MET because I thought I remembered it correctly, thanks for clarifying! I will work through your answer and try to understand it correctly before accepting it, but already thanks a lot for the help!" } ]
[ { "body": "<p>Welcome to CodeReview! This is a great first question.</p>\n\n<h2>Do not do your own time math</h2>\n\n<p>...nor your own formatting when possible. Tell Python to do it for you. Some example code:</p>\n\n<pre><code>from dataclasses import dataclass\nfrom datetime import timedelta, datetime, timezone\nimport requests, pytz\n\n\n@dataclass(frozen=True)\nclass DayInfo:\n day_length: timedelta\n sunrise: datetime\n sunset: datetime\n solar_noon: datetime\n civil_twilight_begin: datetime\n civil_twilight_end: datetime\n nautical_twilight_begin: datetime\n nautical_twilight_end: datetime\n astronomical_twilight_begin: datetime\n astronomical_twilight_end: datetime\n\n @classmethod\n def get(cls, lat: float, long: float, tz: timezone) -&gt; 'DayInfo':\n \"\"\" Function twilightApiGetList(key):\n Calls the sunrise-sunset api to return the value of a given key\n All times returned are in the provided timezone.\n \"\"\"\n with requests.get(\n 'https://api.sunrise-sunset.org/json',\n params={\n 'lat': lat,\n 'lng': long,\n 'date': 'today', # technically this can be omitted\n 'formatted': 0, # we want ISO8601 (\"machine-readable\")\n },\n ) as response:\n response.raise_for_status()\n data = response.json()\n\n if data['status'] != 'OK':\n raise requests.HTTPError(data['status'], response=response)\n results = data['results']\n\n return cls(\n day_length=timedelta(seconds=int(results['day_length'])),\n **{\n k: datetime.fromisoformat(results[k]).astimezone(tz)\n for k in (\n 'sunrise',\n 'sunset',\n 'solar_noon',\n 'civil_twilight_begin',\n 'civil_twilight_end',\n 'nautical_twilight_begin',\n 'nautical_twilight_end',\n 'astronomical_twilight_begin',\n 'astronomical_twilight_end',\n )\n },\n )\n\n\nif __name__ == \"__main__\":\n day_info = DayInfo.get(44.244622, -7.768863, pytz.timezone('MET'))\n print(f'{day_info.civil_twilight_begin:%H:%m}')\n print(f'{day_info.civil_twilight_end:%H:%m}')\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>You didn't parameterize the right things. Parameters should be coordinates and timezone.</li>\n<li>Ask the API for machine-readable (ISO) dates.</li>\n<li>Might as well parse everything from the API.</li>\n<li>Do not use string manipulation to get your desired format. What is shown is string interpolation with standard Python time fields.</li>\n<li>Use <code>requests</code> - it has a lot of niceties that make this easier.</li>\n<li>Only issue one call to the API, returning an object that has both of the keys you care about. If you're never, ever going to use the other keys, you can delete them from this class, but they're inexpensive to generate - compared to a second HTTP call, which is much more expensive.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T15:28:34.393", "Id": "240451", "ParentId": "240438", "Score": "3" } } ]
{ "AcceptedAnswerId": "240451", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T10:22:54.790", "Id": "240438", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "API request, conversion from 12-hour to 24-hour format and conversion from UTC to MET time" }
240438
<p>I am writing a custom allocator for my educational game engine project where I need to iterate through a collection of components(similar to Unity3D) every frame. There are game objects and every game object is composed of these components. Components are classes like Transform, Camera, Light, Mesh Renderer and so on which need to be updated every frame. </p> <p>I also needed my own shared_ptr implementation, ptr_ref, as these components need to be destroyed even before the reference count reaches zero and this was not possible with std::shared_ptr. ptr_ref works very similar to std::shared_ptr on the outside, with the exception that all instances pointing to the same memory can be invalidated(their underlying data set to <em>nullptr</em>). </p> <p><strong>ptr_ref.h</strong></p> <pre><code>#pragma once #include &lt;functional&gt; template &lt;typename T&gt; class ptr_ref { using Deleter = std::function&lt;void( ptr_ref&lt;T&gt;&amp; )&gt;; public: ptr_ref( ) : refCount_( nullptr ), data_( nullptr ), deleter_( nullptr ) { } ptr_ref( T* ptr, const Deleter&amp; deleter = nullptr ) : refCount_( new size_t( 1 ) ), data_( new T* ( ptr ) ), deleter_( deleter ) { } ptr_ref( const ptr_ref&amp; other ) : refCount_( other.refCount_ ), data_( other.data_ ), deleter_( other.deleter_ ) { ++( *refCount_ ); } ptr_ref( ptr_ref&amp;&amp; other ) noexcept : refCount_( other.refCount_ ), data_( other.data_ ), deleter_( other.deleter_ ) { other.data_ = nullptr; other.refCount_ = nullptr; other.deleter_ = nullptr; } ptr_ref&amp; operator=( const ptr_ref&amp; other ) { this-&gt;refCount_ = other.refCount_; this-&gt;data_ = other.data_; this-&gt;deleter_ = other.deleter_; ++( *refCount_ ); return *this; } ptr_ref&amp; operator=( ptr_ref&amp;&amp; other ) noexcept { this-&gt;refCount_ = other.refCount_; this-&gt;data_ = other.data_; this-&gt;deleter_ = other.deleter_; other.data_ = nullptr; other.refCount_ = nullptr; other.deleter_ = nullptr; return *this; } ~ptr_ref( ) { if (data_) { --( *refCount_ ); if (*refCount_ &lt;= 0) { if (*data_) { if (deleter_) deleter_( *this ); else delete ( *data_ ); } delete refCount_; delete data_; data_ = nullptr; refCount_ = nullptr; } } } //decreases the refcount by 1 void reset( ) { if (data_) { --( *refCount_ ); if (*refCount_ &lt;= 0) { if (*data_) { if (deleter_) deleter_( *this ); else delete ( *data_ ); } delete refCount_; delete data_; } data_ = nullptr; refCount_ = nullptr; } } T* operator-&gt;( ) const { return ( *data_ ); } T operator*( ) const { return *( *data_ ); } bool operator==( const ptr_ref&amp; other ) const { return ( *data_ ) == *( other.data_ ); } bool operator!=( const ptr_ref&amp; other ) const { return ( *data_ ) != *( other.data_ ); } template &lt;typename... params &gt; static ptr_ref&lt;T&gt; make( params&amp;&amp; ...args ) { ptr_ref&lt;T&gt; ref; ref.refCount_ = new size_t( 1 ); ref.data_ = new T * ( new T( std::forward&lt;params&gt;( args )... ) ); return ref; } inline T* get( ) const { return ( *data_ ); } inline T** get_address( ) const { return data_; } inline size_t ref_count( ) const { return ( *refCount_ ); } void set( T* ptr ) { *data_ = ptr; } protected: size_t* refCount_; T** data_; Deleter deleter_; }; </code></pre> <p><strong>GrowingListAllocator.h</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;unordered_map&gt; #include &lt;set&gt; #include "../utils/ptr_ref.h" template &lt;typename T, size_t BLOCK_SIZE&gt; struct Chunk { public: explicit Chunk( size_t priority ) : priority_( priority ), buffer_( nullptr ), size_( 0 ) { buffer_ = reinterpret_cast&lt;T*&gt;( malloc( BLOCK_SIZE * sizeof( T ) ) ); addresses_.resize( BLOCK_SIZE, nullptr ); } ~Chunk( ) { for (size_t i = 0; i &lt; size_; ++i) { ( buffer_ + i )-&gt;~T( ); } addresses_.clear( ); free( buffer_ ); buffer_ = nullptr; } inline bool is_full( ) const { return size_ == BLOCK_SIZE; } inline bool size( ) const { return size_; } inline size_t priority( ) const { return priority_; } T* allocate( ) { T* ptr = ( buffer_ + size_ ); ++size_; return ptr; } T* get_pointer_at( size_t index ) { return ( buffer_ + index ); } void set_address( T** ptr ) { addresses_[ size_ - 1 ] = ptr; } void release( T* ptr, Chunk&lt;T, BLOCK_SIZE&gt;* lastChunk, const std::function&lt;void( T** )&gt;&amp; OnSwap ) { ptr-&gt;~T( ); void* src = reinterpret_cast&lt;void*&gt;( lastChunk-&gt;buffer_ + ( lastChunk-&gt;size_ - 1 ) ); void* current = reinterpret_cast&lt;void*&gt;( ptr ); if (src != current) { memcpy( current, src, sizeof( T ) ); *( lastChunk-&gt;addresses_[ lastChunk-&gt;size_ - 1 ] ) = reinterpret_cast&lt;T*&gt;( current ); OnSwap( lastChunk-&gt;addresses_[ lastChunk-&gt;size_ - 1 ] ); } --lastChunk-&gt;size_; } private: T* buffer_; std::vector&lt;T**&gt; addresses_; size_t size_, priority_; }; template &lt;typename T, size_t BLOCK_SIZE&gt; class GrowingBlockAllocator { using TChunk = Chunk&lt;T, BLOCK_SIZE&gt;; public: GrowingBlockAllocator( ) :size_( 0 ) { } ~GrowingBlockAllocator( ) { freeChunks_.clear( ); for (TChunk* chunk : chunks_) { delete chunk; } chunks_.clear( ); memoryMap_.clear( ); } template &lt;typename... params&gt; ptr_ref&lt;T&gt; instantiate( params&amp;&amp; ...args ) { if (freeChunks_.empty( )) { TChunk* chunk = new TChunk( chunks_.size( ) ); chunks_.push_back( chunk ); freeChunks_.insert( chunk ); } TChunk* chunk = *( freeChunks_.begin( ) ); T* ptr = chunk-&gt;allocate( ); //If there is no more memory in the chunk, remove it from the free list if (chunk-&gt;is_full( )) { freeChunks_.erase( chunk ); } ptr_ref&lt;T&gt; ref( new( ptr ) T( std::forward&lt;params&gt;( args )... ), [ this ] ( ptr_ref&lt;T&gt;&amp; ref ) { this-&gt;release( ref ); } ); chunk-&gt;set_address( ref.get_address( ) ); memoryMap_[ ref.get_address( ) ] = chunk; ++size_; return ref; } void release( ptr_ref&lt;T&gt;&amp; ref ) { TChunk* chunk = memoryMap_[ ref.get_address( ) ]; TChunk* lastChunk = nullptr; for (auto rit = chunks_.rbegin( ); rit != chunks_.rend( ); ++rit) { lastChunk = *( rit ); size_t size = lastChunk-&gt;size( ); if (size &gt; 0) { break; } } chunk-&gt;release( ref.get( ), lastChunk, [ &amp; ] ( T** ptr ) { this-&gt;memoryMap_[ ptr ] = chunk; } ); if (!lastChunk-&gt;is_full( )) { freeChunks_.insert( lastChunk ); } if (chunk-&gt;is_full( )) { freeChunks_.erase( chunk ); } ref.set( nullptr ); --size_; } inline size_t size( ) const { return size_; } T* operator[]( size_t i ) { size_t ptr_index = i % BLOCK_SIZE; size_t chunk_index = ( i - ptr_index ) / BLOCK_SIZE; return chunks_[ chunk_index ]-&gt;get_pointer_at( ptr_index ); } private: std::vector&lt;TChunk*&gt; chunks_; std::unordered_map&lt;T**, TChunk*&gt; memoryMap_; struct Comparator { public: inline bool operator()( TChunk* lhs, TChunk* rhs ) const { return lhs-&gt;priority( ) &lt; rhs-&gt;priority( ); } }; std::set&lt;TChunk*, Comparator&gt; freeChunks_; size_t size_; }; </code></pre> <p><strong>Usage(main.cpp)</strong></p> <pre><code>#include &lt;iostream&gt; #include "allocators/GrowingBlockAllocator.h" struct Data { public: int32_t* Marks; int32_t id; Data( int32_t id_ ) :id( id_ ) { Marks = new int32_t[ 5 ]; std::cout &lt;&lt; "Data_" &lt;&lt; id &lt;&lt; "is constructed" &lt;&lt; std::endl; } ~Data( ) { delete[ ] Marks; std::cout &lt;&lt; "Data_" &lt;&lt; id &lt;&lt; "is destroyed" &lt;&lt; std::endl; } }; struct Pack { public: Pack( int32_t v ) :value( v ) { std::cout &lt;&lt; "Pack_" &lt;&lt; value &lt;&lt; "is constructed at " &lt;&lt; (void*) this &lt;&lt; std::endl; data = new Data( value ); } ~Pack( ) { delete data; std::cout &lt;&lt; "Pack_" &lt;&lt; value &lt;&lt; "is destroyed at " &lt;&lt; (void*) this &lt;&lt; std::endl; } Data* data; int32_t value; }; int main( ) { GrowingBlockAllocator&lt;Pack, 3&gt; allocator; std::vector&lt; ptr_ref&lt;Pack&gt;&gt; packs; std::cout &lt;&lt; '\n' &lt;&lt; "**************************" &lt;&lt; '\n' &lt;&lt; std::endl; for (size_t i = 0; i &lt; 7; i++) { packs.push_back( allocator.instantiate( static_cast&lt;int32_t&gt;( 1 + i ) ) ); } std::cout &lt;&lt; '\n' &lt;&lt; "**************************" &lt;&lt; '\n' &lt;&lt; std::endl; allocator.release( packs[ 1 ] ); allocator.release( packs[ 4 ] ); std::cout &lt;&lt; "Is packs[4] null? " &lt;&lt; ( packs[ 4 ] == nullptr ) &lt;&lt; std::endl; packs[ 4 ] = allocator.instantiate( 8 ); std::cout &lt;&lt; "Is packs[4] null? " &lt;&lt; ( packs[ 4 ] == nullptr ) &lt;&lt; std::endl; std::cout &lt;&lt; '\n' &lt;&lt; "**************************" &lt;&lt; '\n' &lt;&lt; std::endl; std::cout &lt;&lt; "Elements in Memery Pool :" &lt;&lt; std::endl; for (size_t i = 0; i &lt; allocator.size( ); i++) { std::cout &lt;&lt; "Data_" &lt;&lt; allocator[ i ]-&gt;value &lt;&lt; std::endl; } std::cout &lt;&lt; '\n' &lt;&lt; "**************************" &lt;&lt; '\n' &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T01:22:04.553", "Id": "473554", "Score": "0", "body": "\"these components need to be destroyed even before the reference count reaches zero\" can you explain why? Does `std::weak_ptr` solve the problem? Why not follow the interface of `std::allocator`?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T11:07:08.613", "Id": "240439", "Score": "3", "Tags": [ "c++", "performance", "game", "memory-management", "memory-optimization" ], "Title": "Custom allocator for improved cache locality and fast iteration in C++" }
240439
<p>I am currently reading Uncle Bob's <em>Clean Code</em> and wonder what would be the "cleaner" implementation of the following:</p> <p>Let's say I want to implement a <code>HTTPRequest</code> class which handles the execution of (well, obviously) http requests. </p> <p>This was my initial implementation:</p> <pre><code>class HTTPRequest(object): def __init__(self, url, method, **kwds): self.logger = logging.getLogger(__name__) self.url = url self.method = method self.request_kwds = kwds self.execution_time_seconds = 0.0 self.response = None self.logger.debug("Created instance %s" % self) def execute(self): self.logger.debug("%s starting request" % self) start_time = time.time() self.response = HTTPResponse( request=self, request_response=requests.request(url=self.url, method=self.method, **self.request_kwds) ) self.execution_time_seconds = time.time() - start_time self.logger.debug( "%s received response %s after %.4f seconds" % (self, self.response, self.execution_time_seconds) ) self.response.raise_for_status() return self.response </code></pre> <p>The <code>execute</code> method currently does two things: issuing the request and capturing the response, and measuring the execution time. So first of all, this would be a violation of the <em>Single Responsibility Principle</em>.<br> Furthermore, it is very detailed and on a low level of abstraction. </p> <p>Now, I could split this up in different sub methods, like this:</p> <pre><code>class HTTPRequest(object): def __init__(self, url, method, **kwds): self.logger = logging.getLogger(__name__) self.url = url self.method = method self.request_kwds = kwds self._start_time = 0 self.execution_time_seconds = 0.0 self.response = None self.logger.debug("Created instance %s" % self) def execute(self): self.logger.debug("%s starting request" % self) self._start_time_measurement() self._execute_request() self._stop_time_measurement() self.logger.debug( "%s received response %s after %.4f seconds" % (self, self.response, self.execution_time_seconds) ) return self.response def _start_time_measurement(self): self._start_time = time.time() def _execute_request(self): self.response = HTTPResponse( request=self, request_response=requests.request(url=self.url, method=self.method, **self.request_kwds) ) self.response.raise_for_status() def _stop_time_measurement(self): self.execution_time_seconds = time.time() - self._start_time </code></pre> <p>Besides having separated the logic of time measurement and request execution, from what I've read so far this version should be considered "cleaner". </p> <p>But I have two concerns about it:</p> <ul> <li><p>This class is still extremely simple. This refactoring made it significantly longer (replacing two single line statements with a call to a function which takes up two lines (+1 for spacing). Doing this kind of refactoring to a "real" class with a lot of business logic could blow it up indefinitely (which is then again considered "unclean")</p></li> <li><p>The original version was - in my eyes - already readable enough, as it used intention-revealing names for the variables, making it clear that there is some kind of time measurement going on during the request.</p></li> </ul> <p>So the question is:<br> which version do you prefer, and why? How much extraction of logic into sub methods is too much?</p> <hr> <p>For the sake of completeness, here is a (stripped down version of) the HTTPResponse class and necessary imports to make the code executable:</p> <pre><code>import time import logging import requests class HTTPResponse(object): def __init__(self, request, request_response): self.request = request self._response = request_response def raise_for_status(self): self._response.raise_for_status() class HTTPRequest(object): # one of the two versions from above </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T11:30:56.377", "Id": "471614", "Score": "0", "body": "The current code does not run because of HTTPResponse missing, if this is your own class, can you add it to the question please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:08:48.297", "Id": "471619", "Score": "2", "body": "@EugeneProut People are allowed to post snippets of their code. I have a question in the works that requires ~1600 LOC to work. But I only want a review of a section of it that's ~100 LOC. Are you implying I'd have to post all 1600 LOC? We don't have to be able to run the code. Heck I almost never run code in questions or answers." } ]
[ { "body": "<p>Whether it makes sense to break this up is somewhat contextually dependent on whether you anticipate reusing this pattern elsewhere, IMO. If it's a one-off it might be cleaner to simply do it in-place as in your first example; I don't think the second example is particularly easier to follow, since your <code>execute</code> method still contains a lot of logging-related code either way, and it has the undesirable side effect of adding more state to your object that could otherwise be locally scoped.</p>\n\n<p>However, if you do plan on reusing this logging logic, a neat way to separate its implementation details from the function that you're trying to log is putting it in a decorator:</p>\n\n<pre><code>import functools\n\n\ndef logged(logger_name):\n logger = logging.getLogger(logger_name)\n\n def decorator(func):\n @functools.wraps(func)\n def wrapped_func(self, *args, **kwargs):\n start_time = time.time()\n logger.debug(\"%s starting execution\" % self)\n ret = func(self, *args, **kwargs)\n exec_time = time.time() - start_time\n logger.debug(\n \"%s returned %s after %.4f seconds\" % (self, ret, exec_time)\n )\n return ret\n return wrapped_func\n return decorator\n\n\nclass HTTPRequest(object):\n def __init__(self, url, method, **kwds):\n self.logger = logging.getLogger(__name__)\n self.url = url\n self.method = method\n self.request_kwds = kwds\n self.logger.debug(\"Created instance %s\" % self)\n\n @logged(__name__)\n def execute(self):\n response = HTTPResponse(\n request=self,\n request_response=requests.request(\n url=self.url,\n method=self.method,\n **self.request_kwds\n )\n )\n response.raise_for_status()\n return response\n</code></pre>\n\n<p>Now all of the logging logic is completely removed from the body of <code>execute</code>, and it lives in that one little <code>@logged</code> decoration, which you can reuse with any other method on any other object (note that the decorator is written to assume it's being applied to an instance method, because it uses a <code>self</code> parameter in its logging). Note that it always measures the overall execution time of the decorated function starting before it's called and ending after it returns (I'm not sure if <code>raise_for_status()</code> blocks long enough for it to make a meaningful difference that the stopwatch ends after you return the response rather than after you create it).</p>\n\n<p>There are a lot of potential further directions to take this -- for example, you could create a logging superclass/mixin that also encapsulates the logging in <code>__init__</code>, or that handles logging-related state that needs to persist in between method calls (e.g. if you want to do any sort of aggregation), and thereby have the ability to make your logging significantly more sophisticated without exposing any of that complexity in the rest of your code. So this approach scales in lots of interesting ways, but again, whether it's worthwhile depends on whether you actually need that scaling.</p>\n\n<p>Making all these things work in a thoroughly typesafe way is also doable but adds a decent amount of complexity that I won't even go into here.</p>\n\n<p>A simpler approach that's less extensible but sticks a lot closer to your original implementation while still getting most of the code out of <code>execute</code> would be to use a higher order function within the class (similar to the decorator approach but with less magic):</p>\n\n<pre><code>class HTTPRequest(object):\n def __init__(self, url, method, **kwds):\n self.logger = logging.getLogger(__name__)\n self.url = url\n self.method = method\n self.request_kwds = kwds\n self.logger.debug(\"Created instance %s\" % self)\n\n def measure_request_time(self, func, *args, **kwargs):\n self.logger.debug(\"%s starting request\" % self)\n start_time = time.time()\n ret = func(*args, **kwargs)\n self.execution_time_seconds = time.time() - start_time\n self.logger.debug(\n \"%s received response %s after %.4f seconds\"\n % (self, ret, self.execution_time_seconds)\n )\n return ret\n\n def execute(self):\n self.response = measure_request_time(\n HTTPResponse,\n request=self,\n request_response=requests.request(\n url=self.url,\n method=self.method,\n **self.request_kwds\n )\n )\n self.response.raise_for_status()\n return self.response\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T14:48:21.750", "Id": "240448", "ParentId": "240440", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T11:09:11.507", "Id": "240440", "Score": "2", "Tags": [ "python", "object-oriented" ], "Title": "Clean Code, step down rule and SRP" }
240440
<p>Would like to have a code review so I can improve my knowledge and expertise in VBA more specifically with Dictionaries as this is the first time I used one.</p> <p>For context I have duplicate data and need to consolidate creating a unique list. To achieve this I used a Dictionary concatenating 2 fields to make a unique key. Also I have a function that uses Dictionaries to get a unique key so I can find the number of occurrence for each order number and add a suffix at the end if more than 999 rows used for the same order.</p> <pre><code>Option Explicit Sub UniqueListWithSumQty() Dim wsSource As Worksheet Dim ws As Worksheet Dim sh As Worksheet Dim strCell As String Dim i As Long, j As Long Dim LRow As Long Dim dict As Object Set ws = ActiveSheet Set dict = CreateObject("Scripting.Dictionary") With ws LRow = FindLastRow(ActiveSheet, 3, 21) .Range("C17:U" &amp; LRow).Sort key1:=.Range("C17:C" &amp; LRow), order1:=xlAscending, Header:=xlNo wsSource = .Range("C17:U" &amp; LRow).value End With With dict For i = 1 To UBound(wsSource, 1) strCell = Join(Array(wsSource(i, 1), wsSource(i, 3)), "|") If Not .Exists(strCell) Then .item(strCell) = .Count + 1 For j = 1 To UBound(wsSource, 2) wsSource(.Count, j) = wsSource(i, j) Next j Else wsSource(.item(strCell), 4) = wsSource(.item(strCell), 4) + wsSource(i, 4) End If Next i i = .Count End With Set sh = ActiveSheet sh.Range("C17:U" &amp; LRow).Clear With sh.Range("C17") .Resize(i, UBound(wsSource, 2)) = wsSource End With Call CheckOccurance(Range("C17:C" &amp; LRow), LRow, sh) End Sub Private Function CheckOccurance(rng As Range, LRow As Long, ws As Worksheet) Dim maxOrdNoRow As Double Dim timesOccured As Double Dim occur As Double Dim uniqueList As Object Dim i As Long Dim data As Variant Dim x As Long Dim key As Variant Dim lastUsedRow As Long Set uniqueList = CreateObject("Scripting.Dictionary") data = rng.value For i = 1 To UBound(data, 1) uniqueList(data(i, 1)) = Empty Next i For Each key In uniqueList maxOrdNoRow = Application.WorksheetFunction.CountIf(Range("C17:C" &amp; LRow), "=" &amp; key) timesOccured = maxOrdNoRow / 999 lastUsedRow = ws.Range("C:C").Find(what:=key, after:=ws.Range("C16")).Row If timesOccured &gt; 1 Then For x = 1 To WorksheetFunction.RoundUp(timesOccured, 0) If timesOccured &gt; x Then occur = timesOccured - (timesOccured - x) Else occur = timesOccured End If ws.Range(Cells(lastUsedRow, 3), Cells((occur * 999) + 16, 3)).value = key &amp; "-" &amp; x lastUsedRow = (occur * 999) + 17 Next x Else 'do nothing End If Next key End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:28:59.873", "Id": "471626", "Score": "0", "body": "If you want people to help you then you have to provide code that is understandable. Therefore your first task is to rework the code you have posted to provide meaningful variable names for third party reviewers (e.g. no i, ii, wsData,sCellData etc). A second point that is becoming increasingly relevant for VBA is, have you addressed all of the issues raised from a RubberDuck code inspection (Rubberduck is a fantastic and free addin for VBA that will do a much stricter check on your code than VBA and give you a list of issues, plus lots of other goodies.)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:34:27.543", "Id": "471628", "Score": "0", "body": "@Freeflow thanks I will address this issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T13:37:28.120", "Id": "471629", "Score": "0", "body": "Also, a helpful pointer might be that it is perfectly valid for an Item in a Dictionary to be another dictionary i.e If not dict.exists(myKey) then dict.add myKey, new Scripting.Dictionary" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:41:48.873", "Id": "471796", "Score": "1", "body": "Your code will not compile and there are numerous problems with it, such as the comma at the end of declaring `strCell`, `wsSource` is declared as a `Worksheet` but you're using it as an array, and the `FindLastRow` is completely missing. Please provide updated and working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:44:03.047", "Id": "471797", "Score": "0", "body": "@PeterT the code works perfectly and it dose what it needs I have validated the data and it matches with original except no duplicates and qty is matching as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:55:57.373", "Id": "471802", "Score": "0", "body": "I can get it to compile if I change the declaration of `wsSource` to `Dim wsSource As Variant` and then remove the comma from the fourth declaration line `Dim strCell As String,`, and then supply my own version of `FindLastRow`. These are the errors I was referring to, but tends to indicate posted code that is not fully vetted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:28:05.530", "Id": "471932", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. The line you changed is explicitly mentioned in the current answer." } ]
[ { "body": "<p>Unfortunately the exercise is a bit abstract to me, because I cannot visualize the data you are manipulating. A data sample would have been welcome to better comprehend your purpose.</p>\n\n<h2>A few comments anyway</h2>\n\n<ul>\n<li>I don't see the code for <code>FindLastRow</code></li>\n<li>You have multiple references to C17, so it should be defined as a <strong>constant</strong> variable. It could be named START_CELL or something. Using uppercase is common practice.</li>\n<li>999: another <strong>magic number</strong> that also appears multiple times. It should be made a constant too, MAX_ITERATIONS or something. Or it could be passed as a parameter to <code>CheckOccurance</code> (you already have 3). The aim is to <strong>avoid repetition</strong>, and leave room for <strong>flexibility</strong> (because you might want to change that value at some point).</li>\n<li>Warning: <code>CheckOccurance</code> is a typo</li>\n<li>You also have more 'arbitrary' values like 3, 4... I suppose they are offsets. Again it would better to use variables instead because they are more <strong>descriptive</strong>, this will make your code more <strong>readable</strong>, easier to understand and will reduce the risk of errors, especially if you shift rows/columns later. <em>And here, doing a search &amp; replace on 3 or 4 is not an option.</em></li>\n<li>This line has 3 <strong>hardcoded values</strong>: <code>ws.Range(Cells(lastUsedRow, 3), Cells((occur * 999) + 16, 3)).value = key &amp; \"-\" &amp; x</code>. And <code>x</code> is not the most <strong>meaningful</strong> name for a variable.</li>\n<li>Rather than using ranges like <code>\"C17:C\" &amp; LRow</code> with hardcoded references it would be better to use <strong>named ranges</strong>. They are more descriptive and more flexible. Like variables, you define them once, and reuse them multiple times. <a href=\"https://helpdeskgeek.com/office-tips/why-you-should-be-using-named-ranges-in-excel/\" rel=\"noreferrer\">Why You Should Be Using Named Ranges in Excel</a></li>\n<li>Using <code>ActiveSheet</code> is tricky, because the context could change, for example your macro could switch to another sheet or workbook, and ruin your assumptions. It would be safer to retrieve a named reference (from <code>ActiveSheet.Name</code>) to a variable and then use that variable. If you have no sheet selected, this property returns Nothing.</li>\n<li>If you are concatenating just two cells maybe using an array and JOINing is a bit overblown: <code>strCell = Join(Array(wsSource(i, 1), wsSource(i, 3)), \"|\")</code>. But the best is to run a benchmark and test performance using different approaches. Don't be afraid to experiment. Good code is code that is efficient while remaining intelligible.</li>\n<li>I don't understand why you declare your variable like this: <code>Dim wsSource As Worksheet</code> and then use it like this: <code>wsSource = .Range(\"C17:U\" &amp; LRow).value</code>. Did you mean <code>Range</code> ?</li>\n<li>The choice of <strong>data type</strong> for your variables is not always optimal: several variables are of type Double. From the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/double-data-type\" rel=\"noreferrer\">doc</a>: \"Double (double-precision floating-point) variables are stored as IEEE <strong>64-bit (8-byte)</strong> floating-point numbers ranging in value from: -1.79769313486231E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.79769313486232E308 for positive values\". Performance matters when you are doing arithmetic operations in loops.</li>\n<li>Even <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/long-data-type\" rel=\"noreferrer\">Long</a> is more than enough: \"Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647.\"</li>\n<li>FYI: Total number of rows and columns on a worksheet: 1,048,576 rows by 16,384 columns (source: <a href=\"https://support.office.com/en-gb/article/excel-specifications-and-limits-1672b34d-7043-467e-8e27-269d656771c3\" rel=\"noreferrer\">Excel specifications and limits</a>). So when working with columns, <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/integer-data-type\" rel=\"noreferrer\">Integer</a> is sufficient: \"Integer variables are stored as 16-bit (2-byte) numbers ranging in value from -32,768 to 32,767\".</li>\n<li><strong>But but but</strong> surprise: \"In recent versions, however, VBA converts all integer values to type Long, even if they're declared as type Integer. So there's no longer a performance advantage to using Integer variables; in fact, Long variables may be slightly faster because VBA does not have to convert them.\" (Source: <a href=\"https://docs.microsoft.com/en-us/previous-versions/office/developer/office2000/aa164506(v=office.10)?redirectedfrom=MSDN\" rel=\"noreferrer\">The Integer Data Types</a>).</li>\n</ul>\n\n<hr>\n\n<h2>Code structure</h2>\n\n<ul>\n<li>Overall, tabulation is OK except <code>UniqueListWithSumQty</code></li>\n<li>Usage of <strong>With</strong> where appropriate</li>\n<li><p>Some <strong>line spacing</strong> would be desirable, calls to external methods eg. <code>Call CheckOccurance</code> should be highlighted and not drowned with the rest of the code because it is important to be able to follow the processing stream.</p></li>\n<li><p>One problem: <strong>lack of comments</strong>. There are important for you too, because in a few weeks or months, you will have lost your train of thought and you will have to re-analyze your own code. It is also very helpful to put some data sample in comments when you extract or compute data, to have an idea of what the values look like. For example, when you extract rows from a range, copy-paste a row or a small portion of your range and add it to comment.</p></li>\n<li>It is important not just to document the individual steps, but also the general logic of your code, for this you add a few lines of comments at the top of your module.</li>\n</ul>\n\n<p>The code is quite short, but unfortunately it's not as easy to understand as it should be, because there are too many hardcoded values, and the underlying data is not known.</p>\n\n<hr>\n\n<h2>Strategy</h2>\n\n<p>Obviously this is what you are interested in and this is where I am going to be the least helpful, because I lack some insight.</p>\n\n<p>First of all, you did not give a clear definition of what qualifies as duplicate data. You've mentioned order numbers but that's the only thing we know. So I am assuming that you are really looking for duplicate order numbers but maybe that's not the whole story. You mention 'concatenating 2 fields' but what are they ?</p>\n\n<p>Maybe all of this was not even necessary, because Excel now has built-in tools to find duplicate data: <a href=\"https://www.wikihow.com/Find-Duplicates-in-Excel\" rel=\"noreferrer\">How to Find Duplicates in Excel</a>. But then, it this was not sufficient for your purpose it should have been made clear and maybe we could propose a better approach.</p>\n\n<p>A <code>COUNTIF</code> might suffice. You even use it in your code. Maybe there is a reason but what was it, I am wondering.\nDictionaries are certainly useful, but in the present case ?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T07:14:00.613", "Id": "471851", "Score": "0", "body": "thanks for the comments really helpful and insightful. I will address this issues. In essence I have order number and product to create unique identifier so I can add the duplicated keys qty together to consolidate the list without losing data values. I thought dictionaries are the best way to go. If I make the changes to provide more clarity are u able to reassess? Thanks again much appreciated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:23:48.363", "Id": "471890", "Score": "0", "body": "I am not convinced dictionaries are the most efficient approach in this scenario. Doing your own code inevitably adds overhead and is unlikely to perform better than the built-in functions. It's perfectly possible to use `COUNTIF` [with multiple criteria](https://www.ablebits.com/office-addins-blog/2014/07/10/excel-countifs-multiple-criteria/) so I think I would have tried this before, and come up with my own sauce only if it is not satisfactory or too cumbersome (PS: using named ranges is always a good idea)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T01:32:00.207", "Id": "471973", "Score": "0", "body": "@QuickSilver not sure what your data looks like exactly, but usually the unique/natural key for order details (this happens to be my domain ) involves an order number and an order line number: the product on the order detail level is an attribute of the order line item record, not part of its key. If you have something like an `OrderLine` column, that's your guy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T07:31:11.863", "Id": "471990", "Score": "0", "body": "@MathieuGuindon I have a order number and this can have >2000 rows of records for that one order number. Now in this order number for every row you have a product it can be duplicated across multiple rows that are not near to one another but the main thing is that I have unique product for ever order number and sum up their qty." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T23:46:42.057", "Id": "240534", "ParentId": "240444", "Score": "5" } } ]
{ "AcceptedAnswerId": "240534", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T12:44:17.667", "Id": "240444", "Score": "1", "Tags": [ "vba" ], "Title": "Adding qty If duplicates keys found VBA" }
240444
<p>I use React with material-ui.com and I love them both, but I'm tired with writing the boilerplate handlers like</p> <pre><code>onChange={(e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; setEmail(e.currentTarget.value)} </code></pre> <p>again and again. Especially when <code>stopPropagation</code> is needed (AFAICT it's always either needed or harmless), it gets pretty verbose.</p> <p>So I tried to extend <code>useState</code> so that it provides everything I need, so I can write things like:</p> <pre><code>const [email, setEmail, emailAgg] = useStateEx(''); ... onChange={emailAgg.changeHandler} </code></pre> <p>or</p> <pre><code>const [showPassword, , showPasswordAgg] = useStateEx(false); ... onClick={showPasswordAgg.toggleHandler} </code></pre> <p>and similar.</p> <hr> <p>My approach follows. I'd like it to be reviewed in general, especially for better typing (I had to use <code>@ts-ignore</code>) and improvements.</p> <p>I case you hate semicolons, please ignore them as my eslint is set up to require them. ;)</p> <pre><code>import { useState, Dispatch, SetStateAction } from 'react'; function booleanAgg(value: boolean, setter: (value: boolean) =&gt; void, makeSetter: (value: boolean) =&gt; ((event?: any) =&gt; void)) { return { value, setter, falseHandler: makeSetter(false), trueHandler: makeSetter(true), toggleHandler: makeSetter(!value), }; } function stringAgg(value: string, setter: (value: string) =&gt; void) { return { value, setter, changeHandler: (e: React.ChangeEvent&lt;HTMLInputElement|HTMLTextAreaElement&gt;) =&gt; { e.stopPropagation(); setter(e.currentTarget.value); } }; } function numberAgg(value: number, setter: (value: number) =&gt; void) { return { value, setter, changeHandler: (e: React.ChangeEvent&lt;HTMLInputElement|HTMLTextAreaElement&gt;) =&gt; { e.stopPropagation(); setter(+e.currentTarget.value); } }; } /** * Works like useState and adds a third element containing boolean-specific handlers directly useable in buttons and checkboxes. */ export function useStateEx(initialState: boolean) : [boolean, Dispatch&lt;SetStateAction&lt;boolean&gt;&gt;, ReturnType&lt;typeof booleanAgg&gt;]; /** * Works like useState and adds a third element containing string-specific handlers directly useable in text fields. */ export function useStateEx(initialState: string) : [string, Dispatch&lt;SetStateAction&lt;string&gt;&gt;, ReturnType&lt;typeof stringAgg&gt;]; /** * Works like useState and adds a third element containing number-specific handlers directly useable in text fields. */ export function useStateEx(initialState: number) : [number, Dispatch&lt;SetStateAction&lt;number&gt;&gt;, ReturnType&lt;typeof numberAgg&gt;]; /** * Prohibits use with any type not handled in the above overloads. */ export function useStateEx(initialState: any) : never; export function useStateEx&lt;S extends boolean|string|number&gt;(initialState: S) : unknown { const [value, setter] = useState(initialState); function makeSetter(value: S) { return function(e: any) { if (typeof e?.stopPropagation === 'function') e.stopPropagation(); setter(value); }; } if (typeof value === 'boolean') { // @ts-ignore return [value, setter, booleanAgg(value, setter, makeSetter)] } else if (typeof value === 'string') { // @ts-ignore return [value, setter, stringAgg(value, setter)]; } else if (typeof value === 'number') { // @ts-ignore return [value, setter, numberAgg(value, setter)]; } else { throw new Error('Only boolean, string and number is supported'); } } </code></pre>
[]
[ { "body": "<p>I must admit that my experience with <a href=\"/questions/tagged/typescript\" class=\"post-tag\" title=\"show questions tagged &#39;typescript&#39;\" rel=\"tag\">typescript</a> and <a href=\"/questions/tagged/react.js\" class=\"post-tag\" title=\"show questions tagged &#39;react.js&#39;\" rel=\"tag\">react.js</a> is quite limited so my review will be limited to basic syntax points. This code seems straight-forward. It makes good use of arrow functions and destruction assignment. There are just a couple suggestions I will make below.</p>\n\n<blockquote>\n<pre><code>if (typeof e?.stopPropagation === 'function') e.stopPropagation();\n</code></pre>\n</blockquote>\n\n<p>It is best to include brackets around the block, even if it is all on one line:</p>\n\n<pre><code>if (typeof e?.stopPropagation === 'function') { e.stopPropagation(); }\n</code></pre>\n\n<p>Some believe such blocks should never be on one line. If you are going to do it on one line, you could use short-circuiting:</p>\n\n<pre><code>typeof e?.stopPropagation === 'function' &amp;&amp; e.stopPropagation();\n</code></pre>\n\n<hr>\n\n<p>This block can be simplified somewhat:</p>\n\n<blockquote>\n<pre><code>if (typeof value === 'boolean') {\n // @ts-ignore\n return [value, setter, booleanAgg(value, setter, makeSetter)]\n} else if (typeof value === 'string') {\n // @ts-ignore\n return [value, setter, stringAgg(value, setter)];\n} else if (typeof value === 'number') {\n // @ts-ignore\n return [value, setter, numberAgg(value, setter)];\n} else {\n throw new Error('Only boolean, string and number is supported');\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>else</code> keywords can be avoided because preceding blocks have <code>return</code> statements.'</p>\n\n<pre><code>if (typeof value === 'boolean') {\n // @ts-ignore\n return [value, setter, booleanAgg(value, setter, makeSetter)]\n} \nif (typeof value === 'string') {\n // @ts-ignore\n return [value, setter, stringAgg(value, setter)];\n} \nif (typeof value === 'number') {\n // @ts-ignore\n return [value, setter, numberAgg(value, setter)];\n}\nthrow new Error('Only boolean, string and number is supported');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-22T20:10:26.013", "Id": "241028", "ParentId": "240452", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T15:37:59.413", "Id": "240452", "Score": "4", "Tags": [ "react.js", "typescript" ], "Title": "Extending react hook useState for use in event handlers" }
240452
<p>I've been studying C for a while, as a programmer coming from a C++ background, I'm used to the standard library, STL, etc., and I quickly realized that I need some kind of a containers library/data structure implementations in C. So as an exercise decided to write one! I also intend to use it on my personal C projects, so it's got to be good!</p> <p>Here is my stack implementation.</p> <p>cstack.h:</p> <pre class="lang-c prettyprint-override"><code>/** * @file cstack.h * * @brief Contains the definition for `cstack` along with the `cstack_*` function signatures. */ #ifndef CSTACK_H #define CSTACK_H typedef signed long long cstack_size_t; typedef struct { cstack_size_t item_size; /**&lt; The size of a single stack item, e.g. sizeof(int) */ char* data; /**&lt; The beginning of the stack. */ char* top; /**&lt; Pointer to the first empty 'slot' in the stack. */ char* cap; /**&lt; Pointer to the end of the stack. */ } cstack; /** * @brief Allocate a new stack. * * @param initial_items_count Specifies how many items should the function allocate space for upfront. * @param item_size The size (in bytes) of a single item, must be &gt; 0. e.g. `sizeof(int)`. * @return The newly allocated stack. NULL on failure. */ cstack* cstack_alloc(cstack_size_t initial_items_count,cstack_size_t item_size); /** * @brief Free the memory allocated by the stack. * * @param stack The stack whose memory to free. */ void cstack_free(cstack* stack); /** * @brief Push a new item onto the stack. * * @param stack The stack to push the item onto. * @param item The item to push onto the stack. * * @note * - The stack is modified in place. * - In the case where the stack is full, i.e. `cstack_full() != 0`, the stack is expanded as necessary. * - In case of failure, the stack remains intact, and the contents are preserved. */ void cstack_push(cstack* stack, void* item); /** * @brief Pop the last (top) item out of the stack. * * @param stack The stack which to pop the item from. * * @note * - The stack is modified in-place. * - In case the stack is already empty, `i.e. cstack_empty() != 0`, nothing is done. */ void cstack_pop(cstack* stack); /** * @brief Expand `stack` by `count`. * * @param stack The stack which to expand. * @param count Specifies the number of _extra items_ to add to the stack, must be &gt; 0. * @return The expanded stack. * * @note * - The stack is modified in-place. * - The stack is expanded by count _items_ (_NOT_ bytes). * - In case of failure, the function returns _NULL_, and the contents of `stack` are preserved. */ cstack* cstack_expand(cstack* stack, cstack_size_t count); /** * @brief Truncate/Shrink the stack. * * @param stack The stack to truncate. * @param count Specifies the number of items to remove from the stack, must be &gt; 0. * * The function Shrinks the stack by the amount of _items_ (_NOT_ bytes) specified * by count. * * The items removed are relative to the stack's capacity _Not_ size. * for example: * * stack is a cstack with a capacity of 10 and a size of 6, i.e. cstack_capacity() == 10 * and cstack_size() == 6, on a successful call to cstack_truncate(stack, 4), * the stack has the following properties: * 1. A capacity of 6. * 2. A size of 6. * 3. The contents (items) of the stack remain the same, since the 4 items where still non-existent. * * if you want to truncate all the extra items you may call cstack_truncate() with the result of cstack_free_items() * as the items count. * * @return The truncated stack. * * @note The stack is modified in-place. */ cstack* cstack_truncate(cstack* stack, cstack_size_t count); /** * @brief Copy the contents of src to dst. * * @param dst The stack to copy the data into. * @param src The stack to copy the data from. * @return dst is returned. * * @note * - dst should point to a valid (allocated using cstack_alloc()) stack. * - If src contains more items than dst's capacity, dst is expanded as necessary. * - dst's contents are _overwritten_ up-to src's size. */ cstack* cstack_copy(cstack* dst, const cstack* const src); /** * @brief Duplicate a stack. * * @param stack The stack to duplicate. * @return The new stack. * * @note * - The new stack is allocated using cstack_alloc() and should be freed using cstack_free(). * - In case of failure the function returns _NULL_. */ cstack* cstack_dupl(const cstack* const stack); /** * @brief Clear the stack. * * @param stack The stack to be cleared. * @return The cleared stack. * * This function resets the _top_ pointer, * and subsequent calls to cstack_push() will overwrite the existing data. * * @note After calling cstack_clear(), there is no guarantee that the data in the stack is still valid! */ cstack* cstack_clear(cstack* stack); /** * @brief Get the top-most item in the stack. i.e. the last cstack_push()ed item. * * @param stack The stack to get the item from. * @return The item at the top of the stack. * * @note * - If the stack is empty, the function returns _NULL_. * - The returned item is a `void*` which should be cast to the proper type if desired/needed. */ void* cstack_top(const cstack* const stack); /** * @brief Retrieve the size of a single stack item. * * @param stack The stack of which to get the item size of. * @return The item size in bytes. */ cstack_size_t cstack_item_size(const cstack* const stack); /** * @brief Retrieves the count of the items in the stack. * * @param stack The stack of which to get the items count of. * @return The items count. */ cstack_size_t cstack_items_count(const cstack* const stack); /** * @brief Retrieves the available (free) items in the stack. * * @param stack The stack to get the free items of. * @return The number of free items. */ cstack_size_t cstack_free_items(const cstack* const stack); /** * @brief Retrieves the size of the items in the stack. * * @param stack The stack of which to get the size of. * @return The size of the items in the stack, in _bytes_. */ cstack_size_t cstack_size(const cstack* const stack); /** * @brief Retrieves the total capacity of the stack. * * @param stack The stack of which to get the capacity of. * @return The capacity of the stack, in _bytes_. */ cstack_size_t cstack_capacity(const cstack* const stack); /** * @brief Retrieve the available (free) space in the stack. * * @param stack The stack to get the free space of. * @return The free space (in bytes) in the stack. */ cstack_size_t cstack_free_space(const cstack* const stack); /** * @brief Checks if the stack is empty, i.e. cstack_size() == 0. * * @param stack The stack to check. * @return Returns a non-zero value if empty, 0 otherwise. */ int cstack_empty(const cstack* const stack); /** * @brief Checks if the stack is full, i.e. cstack_size() == cstack_capacity(). * * @param stack The stack to check if full. * @return Returns a non-zero value if full, 0 otherwise. */ int cstack_full(const cstack* const stack); #endif // CSTACK_H </code></pre> <p>cstack.c</p> <pre class="lang-c prettyprint-override"><code>#include "cstack.h" #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #if defined(ENABLE_ASSERTS) #if defined(_WIN32) #define DEBUG_BREAK __debugbreak(); #elif defined(__linux__) || (!defined(_WIN32) &amp;&amp; (defined(__unix__) || defined(__unix))) #include &lt;signal.h&gt; #define DEBUG_BREAK raise(SIGTRAP) #else #define DEBUG_BREAK; #endif // WIN32 #include &lt;stdio.h&gt; #define ASSERT(x) \ if (x) { } \ else \ { \ fprintf(stderr, "%s (%d): Assertion failed: %s\n", __FILE__, __LINE__, #x); DEBUG_BREAK; \ } #else #define ASSERT(x) #endif #ifndef min #define min(x, y) (((x) &lt; (y)) ? (x) : (y)) #endif #ifndef max #define max(x, y) (((x) &gt; (y)) ? (x) : (y)) #endif cstack* cstack_alloc(cstack_size_t initial_items_count, cstack_size_t item_size) { ASSERT(initial_items_count &gt; 0); ASSERT(item_size &gt; 0); cstack* new_stack = malloc(sizeof(cstack)); if (!new_stack) { return NULL; } cstack_size_t size = initial_items_count * item_size; new_stack-&gt;data = malloc(size); if (!new_stack-&gt;data) { free(new_stack); return NULL; } new_stack-&gt;item_size = item_size; new_stack-&gt;top = new_stack-&gt;data; new_stack-&gt;cap = new_stack-&gt;data + (size); return new_stack; } void cstack_free(cstack* stack) { if (stack) { if (stack-&gt;data) { free(stack-&gt;data); stack-&gt;data = NULL; } stack-&gt;item_size = 0; stack-&gt;top = NULL; stack-&gt;cap = NULL; free(stack); } } void cstack_push(cstack* stack, void* item) { ASSERT(stack); ASSERT(item); if (cstack_full(stack)) { if (!cstack_expand(stack, 1)) { return; } } memcpy(stack-&gt;top, item, cstack_item_size(stack)); stack-&gt;top += cstack_item_size(stack); } void cstack_pop(cstack* stack) { ASSERT(stack); if (!cstack_empty(stack)) { stack-&gt;top -= cstack_item_size(stack); } } cstack* cstack_expand(cstack* stack, cstack_size_t count) { ASSERT(stack); ASSERT(count &gt; 0); cstack_size_t new_size = cstack_capacity(stack) + (count * cstack_item_size(stack)); cstack_size_t top_offset = stack-&gt;top - stack-&gt;data; char* data_backup = stack-&gt;data; stack-&gt;data = realloc(stack-&gt;data, new_size); if (!stack-&gt;data) { stack-&gt;data = data_backup; return NULL; } stack-&gt;top = stack-&gt;data + top_offset; stack-&gt;cap = stack-&gt;data + new_size; return stack; } cstack* cstack_truncate(cstack* stack, cstack_size_t count) { ASSERT(stack); ASSERT(count &gt; 0); ASSERT(count &lt;= cstack_items_count(stack)); cstack_size_t new_size = cstack_capacity(stack) - (count * cstack_item_size(stack)); cstack_size_t top_offset = min(new_size, cstack_size(stack)); char* data_backup = stack-&gt;data; stack-&gt;data = realloc(stack-&gt;data, new_size); if (!stack-&gt;data) { stack-&gt;data = data_backup; return NULL; } stack-&gt;top = stack-&gt;data + top_offset; stack-&gt;cap = stack-&gt;data + new_size; return stack; } cstack* cstack_copy(cstack* dst, const cstack* const src) { ASSERT(dst); ASSERT(src); ASSERT(cstack_item_size(dst) == cstack_item_size(src)); cstack_size_t extra_items = (cstack_size(src) - cstack_capacity(dst)) / cstack_item_size(dst); if (extra_items &gt; 0) { cstack_expand(dst, extra_items); } memcpy(dst-&gt;data, src-&gt;data, cstack_size(src)); cstack_size_t src_top_offset = src-&gt;top - src-&gt;data; cstack_size_t dst_top_offset = dst-&gt;top - dst-&gt;data; cstack_size_t offset = max(src_top_offset, dst_top_offset); dst-&gt;top = dst-&gt;data + offset; return dst; } cstack* cstack_dupl(const cstack* const stack) { ASSERT(stack); cstack* new_stack = cstack_alloc(cstack_items_count(stack), cstack_item_size(stack)); if (!new_stack) { return NULL; } cstack_copy(new_stack, stack); return new_stack; } cstack* cstack_clear(cstack* stack) { ASSERT(stack); stack-&gt;top = stack-&gt;data; return stack; } void* cstack_top(const cstack* const stack) { ASSERT(stack); if (cstack_empty(stack)) { return NULL; } // top points to the item after the last one. i.e. to the next empty 'slot' return (void*)(stack-&gt;top - cstack_item_size(stack)); } cstack_size_t cstack_item_size(const cstack* const stack) { ASSERT(stack); return stack-&gt;item_size; } cstack_size_t cstack_items_count(const cstack* const stack) { ASSERT(stack); return cstack_size(stack) / cstack_item_size(stack); } cstack_size_t cstack_free_items(const cstack* const stack) { ASSERT(stack); return cstack_free_space(stack) / cstack_item_size(stack); } cstack_size_t cstack_size(const cstack* const stack) { ASSERT(stack); return stack-&gt;top - stack-&gt;data; } cstack_size_t cstack_capacity(const cstack* const stack) { ASSERT(stack); return stack-&gt;cap - stack-&gt;data; } cstack_size_t cstack_free_space(const cstack* const stack) { ASSERT(stack); return cstack_capacity(stack) - cstack_size(stack); } int cstack_empty(const cstack* const stack) { ASSERT(stack); return cstack_size(stack) == 0; } int cstack_full(const cstack* const stack) { ASSERT(stack); return cstack_size(stack) == cstack_capacity(stack); } </code></pre> <p>main.c</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include "cstack.h" void print_stack(const cstack* const stack); int main() { cstack* stack = cstack_alloc(4, sizeof(int)); while (1) { int choice = 0; fprintf(stdout, "1. push\n"); fprintf(stdout, "2. pop\n"); fprintf(stdout, "3. print\n"); fprintf(stdout, "&gt;&gt;&gt; "); fscanf(stdin, "%d", &amp;choice); switch (choice) { case 1: fprintf(stdout, "Number to push: "); int num = 0; fscanf(stdin, "%d", &amp;num); cstack_push(stack, &amp;num); break; case 2: if (cstack_empty(stack)) { fprintf(stdout, "Stack is empty!\n"); continue; } fprintf(stdout, "Poping %d (at %p)\n", *(int*)cstack_top(stack), cstack_top(stack)); cstack_pop(stack); break; case 3: print_stack(stack); break; default: fprintf(stdout, "Invalid option!"); continue; } } cstack_free(stack); return 0; } void print_stack(const cstack* const stack) { fprintf(stdout, "Item size: %lld\n", cstack_item_size(stack)); fprintf(stdout, "Items count: %lld\n", cstack_items_count(stack)); fprintf(stdout, "Free items: %lld\n", cstack_free_items(stack)); fprintf(stdout, "Stack size: %lld\n", cstack_size(stack)); fprintf(stdout, "Stack cap: %lld\n", cstack_capacity(stack)); fprintf(stdout, "Stack free space: %lld\n", cstack_free_space(stack)); if (!cstack_empty(stack)) { fprintf(stdout, "Stack top: %d (at %p)\n", *(int*)cstack_top(stack), cstack_top(stack)); } } </code></pre> <p>As a beginner, I'm open to any suggestions, best practices, coding conventions, bugs (obviously), performance improvements, improvements to the interface/docs, etc.</p> <p>Any suggestions are very welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:36:12.617", "Id": "471671", "Score": "0", "body": "A common convention is that no line should be more than 80 character long, which you might want to consider." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:41:25.083", "Id": "471672", "Score": "0", "body": "I thought that convention was long gone! after taking a quick look [around](https://stackoverflow.com/questions/110928/is-there-a-valid-reason-for-enforcing-a-maximum-width-of-80-characters-in-a-code) i guess there are still some valid reasons to stick to it! Noted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T19:12:24.780", "Id": "471684", "Score": "2", "body": "It would be nice if there was a file with a `main()` function for testing purposes." } ]
[ { "body": "<h2>cstack_alloc failure</h2>\n\n<p>This:</p>\n\n<pre><code>cstack* stack = cstack_alloc(4, sizeof(int));\n</code></pre>\n\n<p>does not check for a null, which you return from here:</p>\n\n<pre><code>if (!new_stack)\n{\n return NULL;\n}\n</code></pre>\n\n<p>There are two problems with this. First, if it fails, it will not be graceful; it will likely segfault. Second, you are discarding <code>errno</code> information, and would be well-served to call <code>perror</code>.</p>\n\n<h2>Logic inversion</h2>\n\n<p>This is a matter of style, but I usually like to convert this kind of logic:</p>\n\n<pre><code>if (stack)\n{\n if (stack-&gt;data)\n {\n free(stack-&gt;data);\n stack-&gt;data = NULL;\n }\n\n stack-&gt;item_size = 0;\n stack-&gt;top = NULL;\n stack-&gt;cap = NULL;\n\n free(stack);\n}\n</code></pre>\n\n<p>into</p>\n\n<pre><code>if (!stack)\n return;\n// ...\n</code></pre>\n\n<p>It will probably not affect the output of the compiler, and is easier on the eyes and brain.</p>\n\n<h2>printf</h2>\n\n<p>Why <code>fprintf(stdout, \"1. push\\n\");</code> when you can simply <code>printf</code>? Better yet, <code>puts</code>, which does not need to process a format string.</p>\n\n<p>The same goes for <code>fscanf(stdin, \"%d\", &amp;choice);</code>, which can just use <code>scanf</code>.</p>\n\n<h2>Input validation</h2>\n\n<pre><code>fscanf(stdin, \"%d\", &amp;choice);\n</code></pre>\n\n<p>should return 1 on success. It's important that you validate this, in case someone entered text that is non-numeric.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:27:37.747", "Id": "471795", "Score": "0", "body": "I wrote this `main` function as a basic demo, and it's by no means \"production-ready\", i do agree on the first point though, i did rush a bit there and forgot to check the return value. Logic inversion, i didn't think of it that way! but i agree that it is more readable, I'll do that right away. Printf, i guess i just like `fprintf`ing everywhere :), no seriously though, `fprintf` is needed to print to `stderr` so i use it for `stdout` as well, for consistency. Input validation, i would definitely validate any input in an actual program but since this was just a demo i didn't see a need for it" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T14:50:26.390", "Id": "240504", "ParentId": "240455", "Score": "2" } }, { "body": "<p>The code is nicely documented, so keep that up! I see some things that may help you improve your code.</p>\n\n<h2>Use <code>int main(void)</code> in C</h2>\n\n<p>You mentioned that you were coming from C++, so although it's not a problem in this code, it's important to realize that C and C++ are different when it comes to the formal argument list of a function. In C, use <code>int main(void)</code> instead of <code>int main()</code>. See <a href=\"https://stackoverflow.com/questions/12225171/difference-between-int-main-and-int-mainvoid\">this question</a> for details.</p>\n\n<h2>Think of the user</h2>\n\n<p>The existing program has no graceful way for the user to end which also means that the <code>cstack_free()</code> function is never called. I'd suggest that instead of <code>while (1)</code>, you could do this:</p>\n\n<pre><code>bool running = true;\nwhile (running)\n</code></pre>\n\n<p>and then provide a menu choice for the user to quit.</p>\n\n<h2>Check return values for errors</h2>\n\n<p>The calls <code>malloc</code> are all properly checked, but <code>fscanf</code> can also fail. You must check the return values to make sure they haven't or your program may crash (or worse) when given malformed input. Rigorous error handling is the difference between mostly working versus bug-free software. You should, of course, strive for the latter.</p>\n\n<h2>Avoid function-like macros</h2>\n\n<p>Function-like macros are a common source of errors and the <code>min</code> and <code>max</code> macros are paricularly dangerous. The reason is that any invocation of that macro with a side effect will be executed multiple times. Here's an example:</p>\n\n<pre><code>int a = 7, b = 9;\nprintf(\"a = %d, b = %d\\n\", a, b);\nint c = max(++a, b++);\nprintf(\"a = %d, b = %d\\n\", a, b);\nprintf(\"c = %d\\n\", c);\n</code></pre>\n\n<p>The first <code>printf</code>, predictably, prints </p>\n\n<pre><code> a = 7, b = 9\n</code></pre>\n\n<p>However, the second two <code>printf</code> statements result in this:</p>\n\n<pre><code> a = 8, b = 11\n c = 10\n</code></pre>\n\n<p>What a mess! The solution is simple: write a function instead. That's particularly simple in this case because each macro is used only once anyway.</p>\n\n<h2>Use string concatenation</h2>\n\n<p>The menu includes these lines:</p>\n\n<pre><code>fprintf(stdout, \"1. push\\n\");\nfprintf(stdout, \"2. pop\\n\");\nfprintf(stdout, \"3. print\\n\");\nfprintf(stdout, \"&gt;&gt;&gt; \");\n</code></pre>\n\n<p>There are a couple ways in which this could be improved. First, since you're printing to <code>stdout</code>, you could simply use <code>printf</code>. Second, the strings can be concatenated and use a single invocation of <code>printf</code>:</p>\n\n<pre><code>printf(\"1. push\\n\"\n \"2. pop\\n\"\n \"3. print\\n\"\n \"&gt;&gt;&gt; \");\n</code></pre>\n\n<h2>Reconsider the interface</h2>\n\n<p>If a <code>cstack_push</code> fails because <code>realloc</code> fails, the user has no way to detect this condition because <code>cstack_push</code> does not return anything. It would be nice to provide a <code>bool</code> return instead.</p>\n\n<h2>Exercise all functions</h2>\n\n<p>It's understood that the sample program is just an illustration and not a comprehensive test, but it would be good to write test code that exercises all functions. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:02:23.223", "Id": "240512", "ParentId": "240455", "Score": "3" } }, { "body": "<h2>Reinventing the Wheel</h2>\n\n<p>The code contains it's own version of the <code>ASSERT()</code> macro. It might be better to use the <code>ASSERT()</code> macro provided by `#include so that anyone that has to maintain the code is familiar with the macro and it's usage. This will default to the macro being enabled when the code is being debugged.</p>\n\n<p>The original version of the code had included local versions of <code>assert.h</code> and <code>math.h</code>, it would have been better to just use the standard versions of those file.</p>\n\n<h2>Private Data</h2>\n\n<p>Not all of the functions listed in cstack.h need to be listed in cstack.h. Some examples are <code>cstack_size(const cstack* const stack)</code>, <code>cstack_size_t cstack_capacity(const cstack* const stack)</code> and <code>cstack_size_t cstack_free_space(const cstack* const stack)</code>.</p>\n\n<p>These functions are primarily for internal use of the library. They can be declared <code>static</code> functions which makes them private to <code>cstack.h</code>. To be able to print the values returned from those functions the function <code>print_stack()</code> should be added to <code>cstack.h</code> and the entire function should be moved to the bottom of <code>cstack.c</code>.</p>\n\n<pre><code>static cstack_size_t cstack_size(const cstack* const stack)\n{\n ASSERT(stack);\n\n return stack-&gt;top - stack-&gt;data;\n}\n\nstatic cstack_size_t cstack_capacity(const cstack* const stack)\n{\n ASSERT(stack);\n\n return stack-&gt;cap - stack-&gt;data;\n}\n\nstatic cstack_size_t cstack_free_space(const cstack* const stack)\n{\n ASSERT(stack);\n\n return cstack_capacity(stack) - cstack_size(stack);\n}\n</code></pre>\n\n<h2>Function Order</h2>\n\n<p>There really isn't any reason to have a function prototype for <code>print_stack()</code>. The order of <code>main()</code> and <code>print_stack()</code> can be swapped. This is also true of the 3 functions listed in the Private Data section. The beginning of a <code>C</code> source file should be the building blocks used by the rest of the functions, this is counter intuitive to those coming to <code>C</code> from C++ where it is better to list the public functions first.</p>\n\n<h2>Boolean Values</h2>\n\n<p>If the file <code>stdbool.h</code> is included, you can use variables of type bool and values of <code>true</code> and <code>false</code>. Then the function <code>cstack_empty()</code> can return a bool rather than an int.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:03:35.340", "Id": "471818", "Score": "0", "body": "_They can be declared static functions which makes them private to cstack.h_ - not quite, unfortunately. If they're declared in `cstack.h`, they are not \"private\" at all; a compile-time call to that function from another module would succeed and then linking would fail. Suggesting `static` is correct but insufficient - those functions should be pulled out of the header file entirely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:05:08.480", "Id": "471819", "Score": "0", "body": "I don't think my version of `ASSERT` differs that much from the standard `assert` (except for the fact that you don't have to put a semi-colon at the end!), and about `math.h` my [research](https://stackoverflow.com/questions/3437404/min-and-max-in-c#3437484) shows that `min` and `max` aren't defined, so i do have to write those, i guess?. Regarding the private data, i exposed them on purpose. for example, the stack allocates memory (expands) on demand, but never actually automatically release it, so you can utilize those functions to do that..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:05:29.090", "Id": "471820", "Score": "0", "body": "I thought I suggested that they be removed from cstack.h." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:06:14.887", "Id": "471821", "Score": "1", "body": "...e.g. `cstack_truncate(stack, cstack_free_items(stack))` simulates `shrink_to_fit` in C++. i can of course provide that function. i will also consider using `stdbool.h` since `true` and `false` makes more sense than `0` and `1`!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:38:17.343", "Id": "240515", "ParentId": "240455", "Score": "2" } } ]
{ "AcceptedAnswerId": "240512", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:30:20.857", "Id": "240455", "Score": "7", "Tags": [ "c", "stack" ], "Title": "Dynamic stack implementation in C" }
240455
<p>I've implemented a method to solve the following problem:</p> <blockquote> <p>Given a <code>dictionary</code> and a <code>text</code> string, find all words from the <code>dictionary</code> that are present in the <code>text.</code> One important point is that if the string is in double quotes, I should treat it a "single" value. If no matches found, the method should return 0.</p> </blockquote> <p>So for this input:</p> <pre><code>const text = `Hi. I am a developer. A "Hello world" program was my first code.`; const dictionary = "hi developer world"; </code></pre> <p>I should get this:</p> <pre><code>hi developer hello world </code></pre> <p><strong>This is my current solution:</strong></p> <pre><code>const fn = (text, dictionary) =&gt; { const knownWords = dictionary.toLowerCase().split(' '); const words = text.toLowerCase().match(/\w+|"[^"]+"/gi); const result = words.reduce((acc, word) =&gt; { if (word[0] == '"') { const wordsNoQuotes = word.replace(/"/g, "").split(' '); const shouldInclude = wordsNoQuotes.find(word =&gt; knownWords.includes(word)); if (shouldInclude) { return acc.concat(wordsNoQuotes); } } else if (knownWords.includes(word)) { acc.push(word) } return acc; }, []); return result.length === 0 ? 0 : [...new Set(result)].join('\n'); } </code></pre> <p>It works ok, but I would like to get some performance related improvements. I am happy to change the code (i.e using <code>indexOf</code> over <code>includes</code>) and so on. Any suggestions are welcome! Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T00:20:57.413", "Id": "471719", "Score": "0", "body": "*if the string is in double quotes, I should treat it a \"single\" value* This is a bit unclear to me, given the expected output example. Do you mean that if a matching word is included in double quotes, every word inside those double quotes should be matched as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T06:39:21.320", "Id": "471727", "Score": "0", "body": "@CertainPerformance, yes, if at least one of the words in quotes is in dictionary, all the of the words should be included in the returned result." } ]
[ { "body": "<p>The main potential performance improvement I can see is turning the array of words into a Set of words instead. For every match in the string, you're doing:</p>\n\n<pre><code>const shouldInclude = wordsNoQuotes.find(word =&gt; knownWords.includes(word));\n</code></pre>\n\n<p>The <code>.find</code> is <code>O(n)</code> (it iterates over all words in the array, worst-case), and the <code>.includes</code> is <code>O(n)</code> (it also iterates through all words in its array, worst-case). So this is an <code>O(n ^ 2)</code> operation which is already inside a loop. That could be a bit expensive when either or both arrays are large. Using a Set for one of the arrays instead will allow you to use <code>Set.prototype.has</code>, which is an <code>O(1)</code> operation. The <code>else</code> part also uses <code>.includes</code>, which can be changed to <code>.has</code>:</p>\n\n<pre><code>const knownWordsSet = new Set(dictionary.toLowerCase().split(' '));\nconst words = text.toLowerCase().match(/\\w+|\"[^\"]+\"/gi);\nconst result = words.reduce((acc, word) =&gt; {\n if (word[0] == '\"') {\n const wordsNoQuotes = word.replace(/\"/g, \"\").split(' ');\n const shouldInclude = wordsNoQuotes.find(word =&gt; knownWordsSet.has(word));\n if (shouldInclude) {\n return acc.concat(wordsNoQuotes);\n }\n } else if (knownWordsSet.has(word)) {\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const fn = (text, dictionary) =&gt; {\n const knownWordsSet = new Set(dictionary.toLowerCase().split(' '));\n const words = text.toLowerCase().match(/\\w+|\"[^\"]+\"/gi);\n const result = words.reduce((acc, word) =&gt; {\n if (word[0] == '\"') {\n const wordsNoQuotes = word.replace(/\"/g, \"\").split(' ');\n const shouldInclude = wordsNoQuotes.find(word =&gt; knownWordsSet.has(word));\n if (shouldInclude) {\n return acc.concat(wordsNoQuotes);\n }\n } else if (knownWordsSet.has(word)) {\n acc.push(word)\n }\n\n return acc;\n }, []);\n\n return result.length === 0 ? 0 : [...new Set(result)].join('\\n');\n}\nconsole.log(fn(\n `Hi. I am a developer. A \"Hello world\" program was my first code.`,\n \"hi developer world\"\n));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>But Sets have a small overhead as well, so while this will definitely be the best strategy for large inputs, it might do slightly worse for tiny inputs when there are only one or a couple of words. (But for such tiny inputs, performance is not an issue to worry about anyway)</p>\n\n<p>You're currently pushing to an array inside the loop, then the array only gets used to create a Set to deduplicate at the end of the function. It would be more efficient to use a Set of the result words from the beginning, instead of using an array and converting to one after the fact (converting an array to a Set and the other way around is an <code>O(n)</code> process). At this point, since the accumulator would be the same Set every time, <code>.reduce</code> would <a href=\"https://www.youtube.com/watch?v=TnZ7jMFCa4Y\" rel=\"nofollow noreferrer\">arguably not be appropriate</a>, so use a plain loop instead.</p>\n\n<p>A potential issue in your current code is that if the global <code>.match</code> has no matches, it will return <code>null</code>, <em>not</em> an empty array (unfortunately). So, to avoid occasionally throwing errors, you have to check to see if the match exists first before iterating over it.</p>\n\n<p>You're using <code>.find</code> to check if there are any elements in the <code>wordsNoQuotes</code> array which fulfill the condition. But you don't care about <em>which</em> element fulfills the condition - you just want to see if <em>any</em> element does. So, rather than using <code>.find</code> (which returns the matching element), it would be more semantically appropriate to use <code>.some</code> (which returns <code>true</code> if any elements pass a callback test, and <code>false</code> otherwise)</p>\n\n<p>When the match is a quote string, your</p>\n\n<pre><code>word.replace(/\"/g, \"\").split(' ');\n</code></pre>\n\n<p>iterates over and checks every character of the string <em>twice</em> - once to check for <code>\"</code>s to remove, and again to identify the positions of spaces. Since you already know the positions of the <code>\"</code>s are the first and last character, you could use <code>slice</code> instead:</p>\n\n<pre><code>word.slice(1, word.length - 1).split(' ');\n</code></pre>\n\n<p>But your <code>word</code> variable isn't necessarily a word - it may well be a quoted string which contains multiple words. To improve clarity, maybe call it <code>match</code> instead.</p>\n\n<p>Edited version in full:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const fn = (text, dictionary) =&gt; {\n const knownWordsSet = new Set(dictionary.toLowerCase().split(' '));\n const matches = text.toLowerCase().match(/\\w+|\"[^\"]+\"/gi);\n if (!matches) return 0;\n const resultSet = new Set();\n for (const match of matches) {\n if (match[0] == '\"') {\n const wordsNoQuotes = match.slice(1, match.length - 1).split(' ');\n const shouldInclude = wordsNoQuotes.some(word =&gt; knownWordsSet.has(word));\n if (shouldInclude) {\n for (const word of wordsNoQuotes) {\n resultSet.add(word);\n }\n }\n } else if (knownWordsSet.has(match)) {\n resultSet.add(match);\n }\n }\n return resultSet.size === 0 ? 0 : [...resultSet].join('\\n');\n}\nconsole.log(fn(\n `Hi. I am a developer. A \"Hello world\" program was my first code.`,\n \"hi developer world\"\n));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T08:52:21.000", "Id": "471746", "Score": "0", "body": "Perfect! Thank you very much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T08:28:36.887", "Id": "240489", "ParentId": "240456", "Score": "1" } } ]
{ "AcceptedAnswerId": "240489", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T17:33:00.767", "Id": "240456", "Score": "2", "Tags": [ "javascript", "performance", "ecmascript-6" ], "Title": "Find words from dictionary method. Performance improvements" }
240456
<p>I just started studying data structures and being the <code>std::vector</code> the container that I most use in C++ I decide to try to implement it mimicking its behavior the best I could.</p> <pre><code>#ifndef VECTOR_H_INCLUDED #define VECTOR_H_INCLUDED template&lt;typename T&gt; class Vector { T* values; size_t v_size; size_t v_capacity; public: using iterator = T*; using const_iterator = const T*; using reverse_iterator = std::reverse_iterator&lt;iterator&gt;; using const_reverse_iterator = std::reverse_iterator&lt;const_iterator&gt;; Vector(); Vector(size_t sz); Vector(size_t sz, const T&amp; v ); Vector(const std::initializer_list&lt;T&gt;&amp; i_list ); Vector(const Vector&amp;); Vector(const Vector&amp;&amp;); ~Vector() { delete [ ] values; } Vector&lt;T&gt;&amp; operator=(Vector&lt;T&gt;); Vector&lt;T&gt;&amp; operator=(Vector&lt;T&gt;&amp;&amp;) noexcept; // element access const T&amp; front() const; T&amp; front(); // actually I don't see why would we need this function to be a reference, I think it should be only a const reference, any insight? const T&amp; back() const; T&amp; back(); T&amp; operator[ ](size_t i); const T&amp; operator[ ](size_t i) const; T&amp; at(size_t i); const T&amp; at(size_t i) const; constexpr T* data() noexcept; constexpr const T* data() const noexcept; // iterators iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const; reverse_iterator rbegin() noexcept; const_reverse_iterator crbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator crend() const noexcept; // Modifiers template&lt;typename... ARGS&gt; void emplace_back(ARGS&amp;&amp;... args); // since C++17 the std::vector::emplace_back() function type is a reference T&amp;, why is that? what does this change brings to the table? template&lt;typename... ARGS&gt; iterator emplace(const T* pos, ARGS&amp;&amp;... args); iterator insert(iterator pos, const T&amp; v ); iterator insert(const_iterator pos, const T&amp; v ); iterator insert(const_iterator pos, T&amp;&amp; v ); void insert(iterator pos, size_t n, const T&amp; v ); iterator insert(const_iterator pos, size_t n, const T&amp; v ); void push_back(const T&amp; v); void push_back(T&amp;&amp; v); void pop_back(); iterator erase( const_iterator pos ); iterator erase( iterator first, iterator last ); void clear() noexcept; void resize(size_t n); void resize(size_t n, const T&amp; v); // capacity int size() const noexcept; int capacity() const noexcept; constexpr bool empty() const noexcept; void reserve(size_t n); void shrink_to_fit(); // Non-Member Functions template&lt;typename H&gt; friend bool operator==(const Vector&lt;H&gt;&amp; lhs, const Vector&lt;H&gt;&amp; rhs); // see https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom friend void swap(Vector&amp; first, Vector&amp; second) { using std::swap; swap(first.v_size, second.v_size); swap(first.v_capacity, second.v_capacity); swap(first.values, second.values); } private: bool ctor_initialized = false; void reallocate(); }; template&lt;typename T&gt; inline Vector&lt;T&gt;::Vector() { v_size = 0; v_capacity = 0; values = nullptr; } template&lt;typename T&gt; inline Vector&lt;T&gt;::Vector(size_t sz) { ctor_initialized = true; v_size = sz; v_capacity = sz; values = new T[v_capacity]; for(int i = 0; i &lt; sz; ++i) values[ i ] = T(); } template&lt;typename T&gt; inline Vector&lt;T&gt;::Vector(size_t sz, const T&amp; v) { ctor_initialized = true; v_size = sz; v_capacity = sz; values = new T[v_capacity]; for(int i = 0; i &lt; sz; ++i) values[ i ] = v; } template&lt;typename T&gt; inline Vector&lt;T&gt;::Vector(const std::initializer_list&lt;T&gt;&amp; i_list) { int sz = i_list.size(); v_size = sz; v_capacity = sz; values = new T[v_capacity]; for(auto iter = i_list.begin(), i = 0; iter != i_list.end(); ++i, ++iter) values[ i ] = *iter; } template&lt;typename T&gt; inline Vector&lt;T&gt;::Vector(const Vector&lt;T&gt;&amp; src) : v_size(src.v_size), v_capacity(src.v_capacity), values(new T[v_capacity]) { for(int i = 0; i &lt; v_size; ++i) values[ i ] = src.values[ i ]; } template&lt;typename T&gt; inline Vector&lt;T&gt;&amp; Vector&lt;T&gt;::operator=(Vector&lt;T&gt; src) { swap(*this, src); return *this; } template&lt;typename T&gt; inline Vector&lt;T&gt;::Vector(const Vector&lt;T&gt;&amp;&amp; mv) { swap(*this, mv); } template&lt;typename T&gt; inline Vector&lt;T&gt;&amp; Vector&lt;T&gt;::operator=(Vector&lt;T&gt;&amp;&amp; mv) noexcept { swap(*this, mv); return *this; } template&lt;typename T&gt; inline const T&amp; Vector&lt;T&gt;::back() const { return values[v_size - 1]; } template&lt;typename T&gt; inline T&amp; Vector&lt;T&gt;::back() { return values[v_size - 1]; } template&lt;typename T&gt; inline const T&amp; Vector&lt;T&gt;::front() const { return values[0]; } template&lt;typename T&gt; inline T&amp; Vector&lt;T&gt;::front() { return values[0]; } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::begin() noexcept { return values; } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::const_iterator Vector&lt;T&gt;::begin() const noexcept { return values; } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::end() noexcept { return values + v_size; } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::const_iterator Vector&lt;T&gt;::end() const noexcept { return values + v_size; } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::const_iterator Vector&lt;T&gt;::cbegin() const noexcept { return values; } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::const_iterator Vector&lt;T&gt;::cend() const { return values + v_size; } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::reverse_iterator Vector&lt;T&gt;::rbegin() noexcept { return reverse_iterator(end()); } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::reverse_iterator Vector&lt;T&gt;::rend() noexcept { return reverse_iterator(begin()); } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::const_reverse_iterator Vector&lt;T&gt;::crbegin() const noexcept { return rbegin(); } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::const_reverse_iterator Vector&lt;T&gt;::crend() const noexcept { return rend(); } template&lt;typename T&gt; inline T&amp; Vector&lt;T&gt;::operator[ ] (size_t i) { return values[ i ]; } template&lt;typename T&gt; inline T&amp; Vector&lt;T&gt;::at (size_t i) { if(i &gt;= v_size) throw std::runtime_error("out of range exception"); else return values[ i ]; } template&lt;typename T&gt; inline const T&amp; Vector&lt;T&gt;::operator[ ] (size_t i) const { return values[ i ]; } template&lt;typename T&gt; inline const T&amp; Vector&lt;T&gt;::at (size_t i) const { if(i &gt;= v_size) throw std::runtime_error("out of range exception"); else return values[ i ]; } template&lt;typename T&gt; inline constexpr T* Vector&lt;T&gt;::data() noexcept { return values; } template&lt;typename T&gt; inline constexpr const T* Vector&lt;T&gt;::data() const noexcept { return values; } template&lt;typename T&gt; template&lt;typename... ARGS&gt; void Vector&lt;T&gt;::emplace_back(ARGS&amp;&amp;... args) { if(v_size == v_capacity) { if(ctor_initialized) v_capacity *= 2; else { if (v_size == 0) v_capacity = 1; else if(v_size &lt; 8) v_capacity++; else if (v_size &gt;= 8) v_capacity *= 2; } reallocate(); } values[v_size++] = std::move(T(std::forward&lt;ARGS&gt;(args)...)); } template&lt;typename T&gt; template&lt;typename... ARGS&gt; inline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::emplace(const T* pos, ARGS&amp;&amp;... args) { // I found a lot of examples implementing this function but they were confusing so I came up with this, is this ok? const size_t dist = pos - begin(); if(dist == v_capacity) { emplace_back(T(std::forward&lt;T&gt;(args)...)); } else { if(v_size == v_capacity) { v_capacity *= 2; reallocate(); } std::move_backward(begin() + dist, end(), end() + 1); iterator iter = &amp;values[dist]; *iter = std::move(T(std::forward&lt;ARGS&gt;(args)...)); ++v_size; return iter; } } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::insert(iterator pos, const T&amp; v ) { emplace(pos, v); } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::insert(const_iterator pos, const T&amp; v ) { emplace(pos, v); } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::insert(const_iterator pos, T&amp;&amp; v ) { emplace(pos, std::forward&lt;T&gt;(v)); } template&lt;typename T&gt; void Vector&lt;T&gt;::insert(iterator pos, size_t n, const T&amp; v ) { const size_t dist = pos - begin(); if(v_size + n &gt; v_capacity) { v_capacity *= 2; reallocate(); } std::move_backward(begin() + dist, end(), end() + n); for(int i = dist; i &lt; dist + n; ++i) values[ i ] = v; v_size += n; } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::insert(const_iterator pos, size_t n, const T&amp; v ) { const size_t dist = pos - begin(); if(v_size + n &gt; v_capacity) { v_capacity *= 2; reallocate(); } T* iter = &amp;values[dist]; std::move_backward(begin() + dist, end(), end() + n); for(int i = dist; i &lt; dist + n; ++i) *iter++ = v; v_size += n; return &amp;values[dist]; } template&lt;typename T&gt; inline void Vector&lt;T&gt;::push_back(const T&amp; v) { emplace_back(v); } template&lt;typename T&gt; inline void Vector&lt;T&gt;::push_back(T&amp;&amp; v) { emplace_back(std::forward&lt;T&gt;(v)); } template&lt;typename T&gt; inline void Vector&lt;T&gt;::pop_back() { --v_size; // what if I use this below, what would be happening and what would be the difference?? /* values[--v_size].~T(); */ } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::erase( const_iterator pos ) { /* I cloud use other implementation of this function that is pretty shorter than this but I chose this one that I camne up with, is this ok? */ /*The reason why I chose this is because when I triy erasing on empty Vector and it doesn't crash like the std::vector, instead it just doesn't do anything and neither does it crach when you pass an iterator that is out of range. Not sure if this is good or bad. Any insight? */ const size_t dist = pos - begin(); if(v_size != 0) --v_size; int inc; for(inc = 2; v_size &gt; pow(2, inc); ++inc); if(v_size == 0) v_capacity = 0; else v_capacity = pow(2, inc); if(v_capacity != 0) { T* temp = new T[v_capacity]; for(int i = 0, j = 0; j &lt;= v_size; ++j) { if(j != dist) temp[ i++ ] = values[ j ]; } delete [ ] values; values = temp; } return &amp;values[ dist ]; } template&lt;typename T&gt; inline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::erase( iterator first, iterator last ) { const size_t n = last - first; std::move(last, end(), first); v_size -= n; } template&lt;typename T&gt; inline void Vector&lt;T&gt;::clear() noexcept { v_size = 0; } template&lt;typename T&gt; inline void Vector&lt;T&gt;::shrink_to_fit() { v_capacity = v_size; reallocate(); } template&lt;typename T&gt; inline void Vector&lt;T&gt;::reserve(size_t n) { if (n &gt; v_capacity) { v_capacity = n; reallocate(); } } template&lt;typename T&gt; inline void Vector&lt;T&gt;::resize(size_t n) { if(n &gt; v_capacity) { ctor_initialized = true; v_capacity = n; reallocate(); } v_size = n; } template&lt;typename T&gt; inline void Vector&lt;T&gt;::resize(size_t n, const T&amp; v) { if(n &gt; v_capacity) { ctor_initialized = true; v_capacity = n; reallocate(); } if(n &gt; v_size) { for(int i = v_size; i &lt; n; ++i) values[ i ] = v; } v_size = n; } template&lt;typename T&gt; inline int Vector&lt;T&gt;::size() const noexcept { return v_size; } template&lt;typename T&gt; inline int Vector&lt;T&gt;::capacity() const noexcept { return v_capacity; } template&lt;typename T&gt; inline constexpr bool Vector&lt;T&gt;:: empty() const noexcept { return begin() == end(); } template&lt;typename T&gt; inline void Vector&lt;T&gt;::reallocate() { T* temp = new T[ v_capacity ]; for(int i = 0; i &lt; v_size; ++i) temp[ i ] = values[ i ]; delete[ ] values; values = temp; } template&lt;typename H&gt; inline bool operator==(const Vector&lt;H&gt;&amp; lhs, const Vector&lt;H&gt;&amp; rhs) { if(lhs.v_size != rhs.v_size) return false; for(int i = 0; i &lt; lhs.v_size; ++i) if(lhs.values[ i ] != rhs.values[ i ]) return false; return true; } #endif // VECTOR_H_INCLUDED <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:46:14.883", "Id": "471816", "Score": "0", "body": "@M.Winter it is supposed to construct those elements even though it is not used, `malloc` is plain C and `new` should be used instead unless there is a strong reason not to, in this case I think there isn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T18:07:08.020", "Id": "471824", "Score": "0", "body": "@M.Winter Maybe there is strong reason to but as said the idea is to mimic the `std::vector`,. \"`static_cast<T*>(new char[sizeof(T) * v_capacity])`\", I don't understand this code (what is this char), could you please explain?" } ]
[ { "body": "<p>You have two functions defined inline in the class definition, with the rest defined later. For consistency these should be defined outside of the class like the others.</p>\n\n<p>The <code>ctor_initialized</code> member variable is defined at the end of the class, while the rest of the members are defined at the top. All the member variables should be grouped together, since it is very easy to miss that one extraneous variable. But you don't need <code>ctor_initialized</code> at all. It is only read in one place - <code>emplace_back</code> - and its use there is nonsensical (other places where you attempt to resize the vector don't look at it).</p>\n\n<p>You could simplify your list of constructors by making use of default parameters and by using the <em>mem-initializer-list</em> with them. For example, by using a default value in <code>Vector(size_t sz, const T&amp; v = T());</code> you can get rid of <code>Vector(size_t sz);</code>. This constructor should be <code>explicit</code> to avoid accidental conversions of integers to Vectors.</p>\n\n<p>All of the template out-of-class member function definitions do not need the <code>inline</code> keyword, since a template function definition is implicitly an inline function.</p>\n\n<p>The code to do a reallocation should be completely contained in a member function. You have multiple places with code that follows the \"double capacity, then reallocate\" pattern. Some of them will misbehave if the capacity is 0, or the needed size is more than twice the current capacity (<code>insert(iterator pos, size_t n, const T&amp; v )</code> is one place if <code>n</code> is sufficiently large). All this should be centralized, so that there is only one place in the code that modifies <code>m_capacity</code>. Tweaks to <code>reallocate</code> should do it. Pass in the new minimum size required, then <code>reallocate</code> can determine what the new capacity should be (which may be more than twice the existing capacity).</p>\n\n<p>Your class will not work with types that are not default constructable. If you set the capacity to 100, you'll construct 100 objects. The real <code>std::vector</code> allocates character arrays and uses placement new to solve these problems.</p>\n\n<p>The move constructor <code>Vector(const Vector&lt;T&gt;&amp;&amp; mv)</code> is broken, because you're swapping with an unconstructed object (<code>*this</code>). This will result in Undefined Behavior.</p>\n\n<p>The <code>emplace</code> looks wrong. <code>pos</code> doesn't seem to be the right type. Should this be an integer or an iterator? In its current form you pass a pointer to a <code>T</code>, which can be anywhere. The calculation of <code>dist</code> will be undefined if <code>pos</code> does not point to an element of the <code>values</code> array.</p>\n\n<p>In <code>erase( const_iterator pos )</code>, the use of <code>pow</code>, which is a floating point function, is a potential source of error. You can simply use the bit shift operator, <code>1 &lt;&lt; inc</code>, to calculate a power of two. Why does this function do any memory allocations? It shouldn't be. The two parameter version does not, resulting in different behavior for <code>erase(p)</code> vs <code>erase(p, p + 1)</code>.</p>\n\n<p><code>empty()</code> can be simplified to just <code>return v_size == 0;</code>.</p>\n\n<p>Your size and capacity members are <code>size_t</code> (assuming this is <code>std::size_t</code>, it is an unsigned type), but many of your uses compare those values with a signed number (often <code>int i</code>). This can result in a compiler warning on some platforms (comparing a signed value with an unsigned one). If <code>size_t</code> is a larger integer than an <code>int</code> (64 vs 32 bits), you'll have problems when <code>i</code> overflows.</p>\n\n<p>The <code>size()</code> and <code>capacity()</code> functions return unsigned quantities as potentially smaller signed values.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T19:44:59.037", "Id": "471686", "Score": "0", "body": "Thanks for the partial review, hope you can come back for a full review later" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T19:46:42.250", "Id": "471688", "Score": "0", "body": "\"(other places where you attempt to resize the vector don't look at it)\" - didn't fully understand" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T19:48:54.420", "Id": "471689", "Score": "0", "body": "\"The code to do a reallocation should be completely contained in a member function.\" - I had it but I was afraid I was breaking the DRY rule." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T19:53:11.167", "Id": "471690", "Score": "0", "body": "\" All this should be centralized.\" - How?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T20:07:08.810", "Id": "471693", "Score": "0", "body": "\"pos is the wrong type.\" - what type should I be using then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T20:08:29.237", "Id": "471694", "Score": "0", "body": "\" It is only read in one place\" - I created it for that purpose only" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T20:12:14.027", "Id": "471696", "Score": "0", "body": "The other notes are right, I am working to fix them" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T20:21:32.423", "Id": "471699", "Score": "0", "body": "\" Some of them will misbehave if the capacity is 0\" - IO tried calling the function `shrink_to_fit` on a empty default constructed object and nothing happened. Wasthis a good way to test it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:12:19.613", "Id": "471715", "Score": "0", "body": "I don't think your statement about the for-loop in the `size_t` constructor is correct for scalar types. `new int[100]` will create 100 uninitialized ints, not 100 zeros." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T18:29:03.340", "Id": "471826", "Score": "0", "body": "@MarkH I was in the middle of this when I was interrupted. I've rephrased some things and expanded my review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:03:37.590", "Id": "471911", "Score": "0", "body": "@1201ProgramAlarm \"Why does this function do any memory allocations? It shouldn't be.\" - I know, that's why I asked if the implementation of that function is ok at the top of the function in the comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:06:01.367", "Id": "471914", "Score": "0", "body": "@1201ProgramAlarm \"This can result in a compiler warning on some platforms\" - Actually it does in mine. I will have it changed, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:07:22.133", "Id": "471915", "Score": "0", "body": "@1201ProgramAlarm - \"The size() and capacity() functions return unsigned quantities as potentially smaller signed values.\" - Could you please elaborate more on this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:41:57.823", "Id": "471936", "Score": "0", "body": "@HBatalha On a typical 64 bit system, `size_t` is an unsigned 64-bit integer, while `int` is a signed 32-bit integer (so you only have a 31 bit index). While this won't normally be a problem, if your `Vector` object has a large number of elements in it you'll have problems when `i` goes negative (and some of the elements will not be accessible with a 31 bit index)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T22:26:13.443", "Id": "472235", "Score": "0", "body": "@1201ProgramAlarm How will my `i` go negative. | so you are saying that size() and capacity() should also be a `size_t` right?" } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T19:35:44.947", "Id": "240460", "ParentId": "240457", "Score": "3" } }, { "body": "<p>I'll answer some of the questions in your code comments.</p>\n\n<hr>\n\n<pre><code>T&amp; front(); // actually I don't see why would we need this function to be\n // a reference, I think it should be only a const reference,\n // any insight?\n</code></pre>\n\n<p>This is the non-const version of <code>front()</code>, so it should allow the vector to be modified in some way. This method returns a non-const reference so that the item at the front can be modified.</p>\n\n<pre><code>std::vector&lt;int&gt; numbers;\nnumbers.push_back(2);\nnumbers.front() += 10;\n</code></pre>\n\n<p>The last line would not be possible if <code>front()</code> returned a const reference.</p>\n\n<hr>\n\n<pre><code>template&lt;typename... ARGS&gt;\nvoid emplace_back(ARGS&amp;&amp;... args); // since C++17 the std::vector::emplace_back()\n // function type is a reference T&amp;, why is\n // that? what does this change brings to the\n // table?\n</code></pre>\n\n<p>This change was for the convenience of the programmer. Emplace methods take arguments to a constructor, but the constructed object was not immediately accessible. So, programmers would have to do the following to get the just-constructed object:</p>\n\n<pre><code>things.emplace_back(arg1, arg2, arg3);\nauto&amp; last_thing = things.back(); // or, constantly type things.back()\n</code></pre>\n\n<p>Now, this can be reduced to a single line.</p>\n\n<pre><code>auto&amp; last_thing = things.emplace_back(arg1, arg2, arg3);\n</code></pre>\n\n<p>I've seen some people say that returning <code>void</code> was a feature. The reason for this being that references to items contained in a vector are invalidated when the vector is reallocated (e.g., calling <code>push_back()</code> when <code>size() == capacity()</code>), so the returned reference can be fragile if not tracked carefully.</p>\n\n<hr>\n\n<pre><code>template&lt;typename T&gt;\ninline void Vector&lt;T&gt;::pop_back()\n{\n --v_size;\n\n // what if I use this below, what would be happening and what would be the difference??\n /* values[--v_size].~T(); */\n}\n</code></pre>\n\n<p>If you call the commented version of <code>pop_back()</code> and then the vector goes out of scope, the destructor of the vector element will be called again on the same item, most likely crashing your program. The <code>delete [] values;</code> calls the destructor of each of the items in the vector.</p>\n\n<hr>\n\n<pre><code>// see https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\n</code></pre>\n\n<p>The copy-and-swap idiom is great when you want the strong exception guarantee: if assignment fails, no data is changed. It's as if the assignment was never attempted. There is a trade-off. Because of the copy required by this idiom, it is slower and there are optimizations that cannot be done by the compiler. This is just a reminder to think about what your code needs before automatically picking a common practice.</p>\n\n<p>For example:</p>\n\n<pre><code>template&lt;typename T&gt;\ninline Vector&lt;T&gt;&amp; Vector&lt;T&gt;::operator=(Vector&lt;T&gt; src)\n{\n swap(*this, src);\n\n return *this;\n}\n</code></pre>\n\n<p>If the vector being assigned to already has enough space, then there's no need to allocate memory (which is being done by the by-value parameter). A const-ref version might look like this:</p>\n\n<pre><code>template&lt;typename T&gt;\ninline Vector&lt;T&gt;&amp; Vector&lt;T&gt;::operator=(const Vector&lt;T&gt;&amp; src)\n{\n if(src.size() &lt;= capacity())\n {\n std::copy(src.cbegin(), src.cend(), begin());\n v_size = src.size();\n }\n else\n {\n auto src_copy = src;\n swap(*this, src_copy);\n }\n\n return *this;\n}\n</code></pre>\n\n<p>The first branch reuses already allocated memory, so it can be much faster.</p>\n\n<p>Now, if assignment can throw, then it might be the case that the assignment is left half done if an exception is thrown. If this cannot be allowed to happen, use copy-and-swap and take the performance penalty.</p>\n\n<ul>\n<li>Here's a great talk about this by C++ expert Howard Hinnant: <a href=\"https://www.youtube.com/watch?v=vLinb2fgkHk\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=vLinb2fgkHk</a>\n\n<ul>\n<li>Same video, Skipped ahead to the copy-and-swap commentary: <a href=\"https://youtu.be/vLinb2fgkHk?t=2127\" rel=\"nofollow noreferrer\">https://youtu.be/vLinb2fgkHk?t=2127</a></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>One last thing: check if your for-loops can be replaced by something out of <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\"><code>&lt;algorithm&gt;</code></a>. In your case, look at <a href=\"https://en.cppreference.com/w/cpp/algorithm/copy\" rel=\"nofollow noreferrer\"><code>std::copy()</code></a> and <a href=\"https://en.cppreference.com/w/cpp/algorithm/fill\" rel=\"nofollow noreferrer\"><code>std::fill()</code></a>.</p>\n\n<hr>\n\n<hr>\n\n<p>Answers to follow-up questions:</p>\n\n<blockquote>\n <p>I have been going over the video you gave me the link (2nd one), in the talk Howard Hinnant said that the solution is default everything, wouldn't that create a shallow copy issue?</p>\n</blockquote>\n\n<p>Yes, if a class contains pointers and is responsible for deleting them (\"owning pointers\" in modern C++ parlance), then the default copy constructor and default assignment operator (as well as their move versions) will do the wrong thing. Your vector class has such pointers, so you need to follow the <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"nofollow noreferrer\">Rule of 5</a>, that if you need to write custom version of any of the following, then you probably need to write a custom version of all of them: destructor, copy constructor, move constructor, copy assignment operator, move assignment operator.</p>\n\n<p>Your other choice is to replace members that cause problems (non-smart pointers that need deletion, a.k.a., \"raw pointers\") with smart pointers that handle all of this automatically. That way, the default versions of the constructors/destructors/assignment operators all do the correct thing by default with no code that needs to be written by you. Then you would be following the <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"nofollow noreferrer\">Rule of 0</a>.</p>\n\n<p>In all cases, you need to consider whether the default versions of the special methods do the correct thing. If not, you have two choices: write the correct methods yourself, or change the class members so that the default methods do the correct thing.</p>\n\n<blockquote>\n <p>Is the code you provided me about the copy constructor the fix for this?</p>\n</blockquote>\n\n<p>No. The purpose of my version of the copy-assignment operator was to be more efficient and faster than the copy-and-swap idiom version. Your code that uses the copy-and-swap idiom is also a correct fix to the shallow copy problem.</p>\n\n<blockquote>\n <p>Shouldn't the line be <code>if(src.capacity() &lt;= capacity())</code> instead of <code>if(src.size() &lt;= capacity())</code>?</p>\n</blockquote>\n\n<p>In one sense, the capacity of a vector is an implementation detail. Everything with an index larger than <code>size() - 1</code> and up to <code>capacity() - 1</code> is garbage data, so there's no need to make room for it in the vector being assigned to. Consider the following stupid code:</p>\n\n<pre><code>vector two_numbers = {1, 2};\nvector million_numbers{};\nfor(auto i = 0; i &lt; 1'000'000; ++i)\n million_numbers.push_back(i);\nwhile(million_numbers.size() &gt; 2)\n million_numbers.pop_back()\ntwo_numbers = million_numbers;\n</code></pre>\n\n<p>Now, the capacity of <code>million_numbers</code> is at least one million and the capacity of <code>two_numbers</code> is two. Should memory be allocated for a million numbers when only two will be copied?</p>\n\n<p>In fact, my version of the copy assignment operator isn't even optimal. In the branch where the <code>src.size()</code> is greater than the <code>*this</code> capacity, enough memory is allocated to store the capacity of the <code>src</code> vector instead of just the size due to the copying of <code>src</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T13:46:41.313", "Id": "471782", "Score": "0", "body": "Thanks for the answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T23:32:23.910", "Id": "472241", "Score": "0", "body": "I have been going over the video you gave me the link (2nd one) , in the talk Howard Hinnant said that the solution is default everything, wouldn't that create a shallow copy issue?? Is the code you provided me about the copy constructor the fix for this and in the same code isn't this line this `if(src.capacity() <= capacity())` instead of this `if(src.size() <= capacity())`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T03:13:03.240", "Id": "472249", "Score": "0", "body": "@HBatalha I've added answers to your questions to the end of my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T19:28:01.463", "Id": "472316", "Score": "0", "body": "regarding of your statement that your\" version of the copy assignment operator isn't even optimal\", I think that a possible fix would be to change the condition line to this: `if(src.size() <= capacity() || src.size() < src.capacity() /* + 'a large number' */ )`. with the commented part or just without it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T04:53:41.350", "Id": "472353", "Score": "0", "body": "@HBatalha Run the code here and look at the output: http://cpp.sh/74abg When a std::vector is copied, the capacity of the copy is equal to the size of the original. Allocating more memory than you need for a copy is inefficient (as determined by the std::vector library writers). At the time I wrote my non-optimal example, I didn't want to write a completely optimized version as that would be too complex for this answer and take too much time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T14:57:00.310", "Id": "472419", "Score": "0", "body": "oh I see. Check this line of code then : `template<typename T>\ninline Vector<T>::Vector(const Vector<T>& src) : v_size(src.v_size), v_capacity(src.v_size),\n values(static_cast<T*>(::operator new (sizeof(T) * v_size)))` -- Does this solve the issue?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T15:02:01.633", "Id": "472421", "Score": "0", "body": "\"At the time I wrote my non-optimal example, I didn't want to write a completely optimized version as that would be too complex for this answer and take too much time\" -- That'd be great though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-19T20:52:20.833", "Id": "472487", "Score": "0", "body": "@HBatalha I'm not sure what issue you're talking about. The line you wrote is the same as your original code, just with a `char*` representing the data instead of a `T*`. As for the optimized assignment operator, that would require modifying other sections of your code. The most important being centralizing all of the memory allocation code. Create a private method called `Vector::allocate_space(size_t n)` that will allocate memory for `n` objects if there is not already enough room. Then, call this method from every method that increases the size of the vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T12:01:06.230", "Id": "472552", "Score": "0", "body": "The line I wrote is not the same as the original code because in this the copy constructor set the capacity of the copy equal to the size of the original just like the std::vector does (thus the issue I was referring to). In the code you provided me in the link to C++ Shell, in the moment of the copy, the compiler calls the copy constructor not the copy assignment operator, that's why I showed the changed code of my copy constructor. Here is the full updated code (in case you want to take a look) : https://drive.google.com/open?id=1p7swugZcl8jcOIIwbqYOp0HSvSH0mjly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T13:36:38.143", "Id": "472561", "Score": "0", "body": "@HBatalha I see now. Yes, that copy constructor should work. My version of the assignment operator is still more efficient than copy-swap when the destination vector already has enough memory. Here's an example of what std::vector does on assignment when there's already enough space: http://cpp.sh/7ltau" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T22:58:18.457", "Id": "472639", "Score": "0", "body": "Now I am wondering why did the copy-swap idiom become such a common practice if the destination vector not having enough memory.can occur very often. Is it only because of the strong exception guarantee." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T00:02:22.293", "Id": "472644", "Score": "0", "body": "@HBatalha The copy-swap idiom is easy to write and it provides a strong exception guarantee. Both aspects are important to software developers. There is a risk of bugs in writing your own assignment operator, so defining it in terms of the easier-to-write copy constructor is a valid choice if the decrease in performance is judged to be worth it. The strong exception guarantee, where an exception thrown during assignment leaves all data unchanged, can be essential for some applications, so the performance hit doesn't matter. This is an engineering choice that requires thinking about trade-offs." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:06:11.020", "Id": "240467", "ParentId": "240457", "Score": "5" } }, { "body": "<p>I am no expert at all, but you are missing some optimization which <code>std::vector</code> implements with some certainty.</p>\n\n<p>Note that you can make almost no assumptions about the type <code>T</code>, e.g. you do not know how expensive it is to construct or destruct instances, or how much dynamic memory it consumes.\nAlso, a constructor might have side effect, and a user might expect that for an empty <code>Vector</code> with non-zero capacity, no instances where created and no side effects happened.\nIn short: you should minimize the call of constructors/destructors.</p>\n\n<p>Here is an example: in the constructor \n<code>Vector&lt;T&gt;::Vector(size_t sz)</code> you write</p>\n\n<pre><code>values = new T[v_capacity];\n\nfor(int i = 0; i &lt; sz; ++i)\n values[ i ] = T();\n</code></pre>\n\n<p>The for-loop is unnecessary. The <code>new T[...]</code> already creates an array of instances, and calls the standard constructor for each of these. In other words: for each element of <code>values</code> you call the constructor <code>T::T()</code>, then the destructor <code>T::~T()</code>, and then the constructor again.</p>\n\n<p>Another example is your resize function, which when called as <code>Vector::resize(n)</code> on an empty <code>Vector</code> calls the constructor <code>T::T()</code> <code>n</code> times, even though the vector still does not contain any actual elements (from the perspective of the user).</p>\n\n<p><strong>The solution</strong></p>\n\n<p>There are ways to allocate memory for <code>T* values</code> without calling the constructors, and only calling them later when actual elements are added.</p>\n\n<p>Instead of <code>values = new T(n)</code> you might write</p>\n\n<pre><code>values = (T*)(new char[sizeof(T) * n]);\n</code></pre>\n\n<p>to allocate a block of memory, equivalent to the one allocated with <code>new T(n)</code>, but without calling any constructors (<code>char</code> is used because it is of size 1 byte, and <code>sizeof(T)</code> gives the size of <code>T</code> in bytes).\nThis is also the same as <code>malloc(sizeof(T) * n)</code> but is actual <code>C++</code>.</p>\n\n<p>If you want to call the constructor of the <code>i</code>-th element of <code>values</code>, you could use <a href=\"https://en.cppreference.com/w/cpp/language/new#Placement_new\" rel=\"nofollow noreferrer\"><em>placement new</em></a>, which goes as folllows:</p>\n\n<pre><code>new (values + i) T();\n</code></pre>\n\n<p>or you write <code>values[i]-&gt;T()</code>. Equivalently if you want to destruct an element explicitly use <code>values[i]-&gt;~T()</code>. With the latter, in the destructore <code>Vector::~Vector</code> you would call the destructor only for the actually initialized elelemts of <code>values</code> with indices 0, ..., <code>v_size-1</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T17:31:15.903", "Id": "471909", "Score": "0", "body": "Hello, first of all, thanks for the whole answer on this. I tried using `values = static_cast<T*>(new char[sizeof(T) * n]);` but it throws a compile error in its line: `invalid static_cast from type 'char*' to type 'int*'`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:03:53.803", "Id": "471912", "Score": "0", "body": "@HBatalha Ok, `static_cast` seems not to be made for this task. I suppose `reintepret_cast` will work, but I feel unfomfortable using it. Anyway, I changed the answer to use C-style cast, which at least compiles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:21:24.103", "Id": "471919", "Score": "0", "body": "you haven't actually" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:28:59.850", "Id": "471933", "Score": "0", "body": "@HBatalha It reads `values = (T*)(new char[sizeof(T) * n]);` now, doesn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T22:38:40.053", "Id": "471966", "Score": "0", "body": "sorry, only paid attention starting from new" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T18:40:08.547", "Id": "240522", "ParentId": "240457", "Score": "4" } }, { "body": "<h2>Overall</h2>\n\n<p>Please put your code in your own namespace.<br>\nIt is more than likely that other people have created a \"Vector\" type. But in general you need to keep all your code in your own namespace.</p>\n\n<p>Your main issue is that you construct all the elements in the vector even if you are not using them. This can be expensive if T is expensive or you never use most of the elements in the vector.</p>\n\n<p>Your secondary issue is that you check and allocate extra capacity i nearly all functions that add elements. You need to simplify this and move this code into its own function. Then call this function from each member that adds elements to the vector.</p>\n\n<pre><code>void checkForEnoughSpaceAndAllocateIfRequried(std::size_t totalSpaceRequired);\n</code></pre>\n\n<h3>My full explanation of how to build a vector</h3>\n\n<p><a href=\"https://lokiastari.com/blog/2016/02/27/vector/index.html\" rel=\"nofollow noreferrer\">Vector - Resource Management Allocation</a><br>\n<a href=\"https://lokiastari.com/blog/2016/02/29/vector-resource-management-ii-copy-assignment/index.html\" rel=\"nofollow noreferrer\">Vector - Resource Management Copy Swap</a><br>\n<a href=\"https://lokiastari.com/blog/2016/03/12/vector-resize/index.html\" rel=\"nofollow noreferrer\">Vector - Resize</a><br>\n<a href=\"https://lokiastari.com/blog/2016/03/19/vector-simple-optimizations/index.html\" rel=\"nofollow noreferrer\">Vector - Simple Optimizations</a><br>\n<a href=\"https://lokiastari.com/blog/2016/03/20/vector-the-other-stuff/index.html\" rel=\"nofollow noreferrer\">Vector - The Other Stuff</a> </p>\n\n<h2>Code Review</h2>\n\n<p>When using move construction you can't pass by const reference.</p>\n\n<pre><code> Vector(const Vector&amp;&amp;);\n</code></pre>\n\n<p>You are going to modify the input value if you remove its content.</p>\n\n<hr>\n\n<p>If T is non trivial and needs a destructor call then this will call the destructor for all elements in <code>values</code> (assuming it was correctly allocated).</p>\n\n<pre><code> ~Vector()\n {\n delete [ ] values;\n }\n</code></pre>\n\n<p><strong>BUT</strong> you have <code>v_capacity</code> member. This means that not all members of <code>values</code> have been constructed (or potentially the elements have been removed and thus destructed). So this is probably wrong.</p>\n\n<p>Or you always construct all the members and keep them constructed. This is an issue if the type <code>T</code> is expensive to construct, there is some special property of T that counts the number of valid entities of T etc.</p>\n\n<p>i.e. you should not construct the members of the vector until they are placed in the vector and they should be destroyed (via destructor) when they are removed erased from the vetctor.</p>\n\n<hr>\n\n<pre><code> T&amp; front(); // actually I don't see why would we need this function to be a reference, I think it should be only a const reference, any insight?\n const T&amp; back() const;\n</code></pre>\n\n<p>You need this so you can modify the front element in the vector (you don't need \"need\" it but it is very useful).</p>\n\n<hr>\n\n<p>What about the const version of <code>back()</code> ?</p>\n\n<pre><code> T&amp; back();\n</code></pre>\n\n<hr>\n\n<p>Not sure why you want this to be a friend rather than a member.</p>\n\n<pre><code> // Non-Member Functions\n template&lt;typename H&gt; friend bool operator==(const Vector&lt;H&gt;&amp; lhs, const Vector&lt;H&gt;&amp; rhs);\n</code></pre>\n\n<p>Normally the reason to use friend functions is to allow auto conversion of both the right and left hand sides if one side is not a vector. Since you don't really want auto conversion for a comparison I don't see the need.</p>\n\n<hr>\n\n<p>This is the basics actions needed for swap.</p>\n\n<pre><code> friend void swap(Vector&amp; first, Vector&amp; second)\n {\n using std::swap;\n\n swap(first.v_size, second.v_size);\n swap(first.v_capacity, second.v_capacity);\n swap(first.values, second.values);\n }\n</code></pre>\n\n<p>But probably is not the best way to implement it. Some internal functions also need the ability to swap and calling an external function seems overkill. So I would implement it like this:</p>\n\n<pre><code> // This is useful to provide as a public function.\n // But provides a member function that allows other members to use swap.\n void swap(Vector&amp; other) noexcept\n {\n using std::swap;\n\n swap(v_size, other.v_size);\n swap(v_capacity, other.v_capacity);\n swap(values, other.values);\n }\n\n\n// Now the implementation of the swap function (in the same namespace as Vector)\n// Becomes really simple.\nvoid swap(Vector&amp; lhs, Vector&amp; rhs)\n{\n lhs.swap(rhs);\n}\n</code></pre>\n\n<hr>\n\n<p>Prefer to use the initializer list rather than construct members the body.</p>\n\n<pre><code>template&lt;typename T&gt;\ninline Vector&lt;T&gt;::Vector()\n{\n v_size = 0;\n v_capacity = 0;\n values = nullptr;\n}\n</code></pre>\n\n<p>In this case it makes no difference. <strong>BUT</strong> if the types of the members has non trivial constructor or assignment then you are doing extra work. And one of the things about C++ is that we often come around and simply change the type of a member and expect the type to continue working the same. If you do this type of initialization suddenly your class becomes ineffecient.</p>\n\n<p>So it is better to do it like this:</p>\n\n<pre><code>template&lt;typename T&gt;\nVector&lt;T&gt;::Vector()\n : v_size(0)\n , v_capacity(0)\n , values(nullptr)\n{}\n</code></pre>\n\n<hr>\n\n<p>The problem here is that you are initializing every member of the array.</p>\n\n<pre><code> values = new T[v_capacity];\n</code></pre>\n\n<p>This is not very efficient especially if <code>T</code> is expensive to initialize (or it is not appropriate to initialize members that the user has not created). TO mimik <code>std::vector</code> you should allocate the space but <strong>NOT</strong> call the constructors on the members.</p>\n\n<p>Members are not constructed until objects are added to the array.</p>\n\n<p>To add an object to memory that is allocated but not initialized you need to use placement new. This is a new where you tell new the memory location to use.</p>\n\n<pre><code> // Allocate Memory\n values = static_cast&lt;T*&gt;(::operator new(sizeof(T) * v_capacity);\n\n\n // Put an element into the memory space.\n // that has not be initialized by calling constructor\n\n new (&amp;values[i]) T(&lt;constructor parameters&gt;);\n</code></pre>\n\n<p>Notice the extra parameter to new here (a pointer to a memory location). This means new will not allocate memory but will use the pointer provided.</p>\n\n<p>Conversely when these locations are no longer used you must manually call the destructor.</p>\n\n<pre><code> values[i].~T();\n</code></pre>\n\n<hr>\n\n<p>Lets re-write this version using the guidelines above:</p>\n\n<pre><code>template&lt;typename T&gt;\ninline Vector&lt;T&gt;::Vector(size_t sz, const T&amp; v)\n : v_size(sz)\n , v_capacity(sz)\n , values(static_cast&lt;T*&gt;(::operator new(sizeof(T) * v_capacity))\n , ctor_initialized(true)\n{ \n for(int i = 0; i &lt; sz; ++i) {\n new (&amp;values[ i ]) T(v);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Prefer to use the range based for:</p>\n\n<pre><code> for(auto iter = i_list.begin(), i = 0; iter != i_list.end(); ++i, ++iter)\n values[ i ] = *iter;\n</code></pre>\n\n<p>Simpler to write as:</p>\n\n<pre><code> for(auto const&amp; val: i_list) {\n push_back(val);\n }\n</code></pre>\n\n<hr>\n\n<p>This constructor is making a copy of <code>mv</code> before swapping it!</p>\n\n<pre><code>template&lt;typename T&gt;\ninline Vector&lt;T&gt;::Vector(const Vector&lt;T&gt;&amp;&amp; mv)\n{\n swap(*this, mv);\n}\n</code></pre>\n\n<p>This is correctly written like this:</p>\n\n<pre><code>template&lt;typename T&gt;\ninline Vector&lt;T&gt;::Vector(Vector&lt;T&gt;&amp;&amp; mv) noexcept\n{\n swap(mv);\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li>This constructor should be <code>noexcept</code></li>\n<li>Use the internal version of swap()</li>\n</ol>\n\n<hr>\n\n<p>All these methods are correct and fine. But they are simple one liners.</p>\n\n<pre><code>template&lt;typename T&gt;\ninline typename Vector&lt;T&gt;::iterator Vector&lt;T&gt;::begin() noexcept\n{\n return values;\n}\n</code></pre>\n\n<p>I would simply declare them in the class and make them one liners.</p>\n\n<pre><code>iterator begin() noexcept {return values;}\nconst_iterator begin() noexcept const {return values;}\nconst_iterator cbegin() noexcept const {return values;}\nreverse_iterator rbegin() noexcept {return reverse_iterator(end());}\nconst_reverse_iterator crbegin() noexcept const {return rbegin();}\niterator end() noexcept {return values + v_size;}\nconst_iterator end() noexcept const {return values + v_size;}\nconst_iterator cend() const {return values + v_size;}\nreverse_iterator rend() noexcept {return reverse_iterator(begin());}\nconst_reverse_iterator crend() noexcept const {return rend();}\n</code></pre>\n\n<p>When I lined them up all nice (and moved const to the right of noexcept). I notices that <code>cend()</code> is different. It is not only one you have not declared <code>noexcept</code>. Why?????</p>\n\n<hr>\n\n<p>Why do you have the else here?</p>\n\n<pre><code>template&lt;typename T&gt;\ninline T&amp; Vector&lt;T&gt;::at (size_t i)\n{\n if(i &gt;= v_size)\n throw std::runtime_error(\"out of range exception\");\n else\n return values[ i ];\n}\n</code></pre>\n\n<p>Normally when you check pre-conditions your code looks like this:</p>\n\n<pre><code> if (precondition-fail) {\n throw excpetion\n }\n\n Normal Code\n</code></pre>\n\n<p>You put the precondition check at the top then all your normal code can go at the normal indent level (not be indent an extra level.</p>\n\n<hr>\n\n<p>Every one of your functions that adds members checks to see if there is room and increases capacity!</p>\n\n<p>You don't think there should be a separate method that does this check and if there is not enough capacity allocates the appropriate amount of memory.</p>\n\n<pre><code>template&lt;typename T&gt;\ntemplate&lt;typename... ARGS&gt;\nvoid Vector&lt;T&gt;::emplace_back(ARGS&amp;&amp;... args)\n{\n if(v_size == v_capacity)\n {\n if(ctor_initialized)\n v_capacity *= 2;\n else\n {\n if (v_size == 0)\n v_capacity = 1;\n else if(v_size &lt; 8)\n v_capacity++;\n else if (v_size &gt;= 8)\n v_capacity *= 2;\n }\n\n reallocate();\n }\n\n values[v_size++] = std::move(T(std::forward&lt;ARGS&gt;(args)...));\n}\n</code></pre>\n\n<hr>\n\n<p>You don't need <code>std::move here</code>:</p>\n\n<pre><code> values[v_size++] = std::move(T(std::forward&lt;ARGS&gt;(args)...));\n</code></pre>\n\n<p>The expression <code>T(std::forward&lt;ARGS&gt;(args)...)</code> is already an r-value reference (its an unamed variable).</p>\n\n<hr>\n\n<p>You should definately want to use the destructor remove elements when they are removed. Unfortunately you can't because of the way you have created the constructors/destructor.</p>\n\n<p>Currently destroying the element would lead to the destructor re-destroying the element. </p>\n\n<pre><code>template&lt;typename T&gt;\ninline void Vector&lt;T&gt;::pop_back()\n{\n --v_size;\n\n // what if I use this below, what would be happening and what would be the difference??\n /* values[--v_size].~T(); */\n}\n</code></pre>\n\n<p>You do want to do this. But first you must change your code to use inpace new operator everywhere else.</p>\n\n<hr>\n\n<p>If T is expensive to create you may want to move objects from the original to the destination rather than copying them.</p>\n\n<pre><code>template&lt;typename T&gt;\ninline void Vector&lt;T&gt;::reallocate()\n{\n T* temp = new T[ v_capacity ];\n\n for(int i = 0; i &lt; v_size; ++i)\n temp[ i ] = values[ i ]; // This is a copy of T\n\n delete[ ] values;\n values = temp;\n}\n</code></pre>\n\n<p>You have not considered what would happen if a copy failed! If a copy of T failed during your loop (and throws an exception). Then you leak the memory that was allocated and assigned to <code>temp</code>.</p>\n\n<p>A better technique is to create a new <code>Vector</code> object. If it works then swap the content out of the this new vector object into your own Vector.</p>\n\n<pre><code>template&lt;typename T&gt;\ninline void Vector&lt;T&gt;::reallocate()\n{\n Vector&lt;T&gt; temp;\n temp.reserve(v_capacity);\n\n for(int i = 0; i &lt; v_size; ++i) {\n temp.emplace_back(values[ i ]);\n }\n\n swap(temp); \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:14:46.280", "Id": "471916", "Score": "0", "body": "Thanks, I have actually fixed some topics you pointed like the member-initializer-list" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:16:42.440", "Id": "471917", "Score": "0", "body": "\"Prefer to use the range based for:\" - I have actually changed the code to instead of using 'for' to use 'std::copy' and `std::fill` from `<algorithm>` library." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:19:29.463", "Id": "471918", "Score": "0", "body": "Refer to the first answer of this question \"The move constructor Vector(const Vector<T>&& mv) is broken, because you're swapping with an unconstructed object (*this). This will result in Undefined Behavior.\", I have changed the code to something like this `inline Vector<T>::Vector(const Vector<T>&& mv) : Vector()`, without `noexcept` yet though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:22:36.783", "Id": "471920", "Score": "0", "body": "\" It is not only one you have not declared `noexcept`. Why?????\" - No idea, I have it in my code. Maybe I added it after posting the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:25:05.137", "Id": "471921", "Score": "0", "body": "\"What about the const version of back() ?\" - it is there, you have actually used in your answer, just above this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:28:30.413", "Id": "471922", "Score": "0", "body": "\"You should definately want to use the destructor remove elements when they are removed.\" - have a look at this question I posted here http://www.cplusplus.com/forum/beginner/269502/ , and tell me what you think" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:50:49.700", "Id": "471924", "Score": "0", "body": "\"TO mimik std::vector you should allocate the space but NOT call the constructors on the members.\" - How to do allocate and set it all to zero like `std::vector` does instead of just garbage?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:58:07.117", "Id": "471928", "Score": "0", "body": "There is a problem in the last snippet of code you provide , you create a Vector `temp` that calls the `reserve` function which in turn calls the `reallocate` function, this will result in an infinite loop. I see what you are saying though so I would create the Vector `temp` like this `Vector<T> temp(v_capacity)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:05:20.533", "Id": "471930", "Score": "0", "body": "I tested the last snippet of code and it crashed, I am tracking down the bug. -> Tracked, the function `emplace_back` also calls the function `reallocate`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:06:53.907", "Id": "471942", "Score": "0", "body": "`How to do allocate and set it all to zero like std::vector`? `std::vector` does not set it all to zero, or should I say is not required to. An implementation can make `std::vector` do this and probably will in debug versions but this is totally optional. You should just allocate the space with the standard allocators (as I have shown above). If they want to zero out the memory (in debug mode) then that's a nice side affect but not required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:08:05.520", "Id": "471943", "Score": "0", "body": "`this will result in an infinite loop`? Sure in your code. But in good implementations are designed so that does not happen so you can use this technique to get leak free allocation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:09:46.067", "Id": "471945", "Score": "0", "body": "If you read the articles I wrote. They walk you through all these issues and explain in detail all the list design things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:15:14.593", "Id": "471946", "Score": "0", "body": "I have a whole article dedicated to writing resize correctly: https://lokiastari.com/blog/2016/03/12/vector-resize/index.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T22:48:51.063", "Id": "471967", "Score": "0", "body": "I had read those articles before I started writing the implementation for guidance, now after finishing the implementation and going back there I see the whole article with different eyes as I see that I hadn't understood a lot of things, thanks for the links and for this whole review, it was really useful and helpful." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:05:09.763", "Id": "240569", "ParentId": "240457", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T18:26:06.453", "Id": "240457", "Score": "4", "Tags": [ "c++", "reinventing-the-wheel", "vectors" ], "Title": "std::vector implementation C++" }
240457
<p>I've implemented the following Fibonacci iterator:</p> <p><strong>lib.rs</strong></p> <pre class="lang-rust prettyprint-override"><code>// lib.rs // num-traits = 0.2.11 extern crate num_traits; use num_traits::PrimInt; pub struct Fibonacci&lt;T&gt; { curr: T, next: T, } impl&lt;T&gt; Fibonacci&lt;T&gt; where T: PrimInt { pub fn new() -&gt; Self { Self { curr: T::zero(), next: T::one() } } } impl&lt;T&gt; Iterator for Fibonacci&lt;T&gt; where T: PrimInt { type Item = T; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { let next = self.curr + self.next; let prev = self.curr; self.curr = self.next; self.next = next; Some(prev) } } </code></pre> <p><strong>main.rs</strong></p> <pre class="lang-rust prettyprint-override"><code>// main.rs use my_crate::Fibonacci; fn main() { let fibonacci: Vec&lt;u128&gt; = Fibonacci::new().take(100).collect(); println!("{:?}", fibonacci); } </code></pre> <p>I want to make sure that I'm following proper naming conventions and that the code is well-implemented, both in terms of correctness and performance.</p> <p>Thanks,</p>
[]
[ { "body": "<p>You are calculating next but it will not be used until two calls later, so when you reach the end of the range of the data type the code will overflow before you get the last values calculated.</p>\n\n<p>The trait you are using is <code>num_traits::identities</code> and not <code>num_traits::PrimInt</code> so I guess it should be <code>where T: num_traits::identities</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T02:37:46.430", "Id": "240481", "ParentId": "240463", "Score": "0" } }, { "body": "<p>You're pretty good as-is, but there's a few things that could be changed:</p>\n\n<h2><code>extern crate</code> is no longer needed</h2>\n\n<p>In Rust 2018 edition, <code>extern crate</code> is no longer needed unless you're using it with <code>#[macro_use]</code>.</p>\n\n<h2>Detect overflow</h2>\n\n<p>Your program could panic (debug mode) or worse, produce weird values (release mode) when it overflows. Instead, use:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>let next = self.curr.checked_add(&amp;self.next)?;\n</code></pre>\n\n<p>This uses the fancy <code>?</code> operator to return <code>None</code> when <a href=\"https://rust-num.github.io/num/num/trait.CheckedAdd.html\" rel=\"nofollow noreferrer\">that function</a> returns <code>None</code>, stopping the iterator.</p>\n\n<h2>Provide a <code>Default</code> implementation</h2>\n\n<p>It's handy to be able to create an automatic default implementation for use in derived structs. See this example:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Default)]\nstruct Foo {\n data: u32,\n fib: Fibonacci&lt;u128&gt;,\n}\n</code></pre>\n\n<p>By implementing <code>Default</code>, you make it easy for your users to use your type later on. Someone can just say <code>Foo::default()</code> without writing any initialization code.</p>\n\n<h2>(Optional) Derive more traits</h2>\n\n<p>Several traits could be helpful in your application, such as <code>Debug</code> which would allow you to see the inside of the generator, and <code>Clone</code> to create a new generator with the same state. This is especially helpful when putting your struct in another struct which uses those traits, as I normally throw at least a <code>#[derive(Debug)]</code> on all my structs. Normally, this is done with the <code>#[derive()]</code> macro:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Copy, Clone, Debug, PartialEq)]\npub struct Fibonacci&lt;T: Copy, Clone, Debug, PartialEq&gt; {\n curr: T,\n next: T,\n}\n</code></pre>\n\n<p>However, you'd loose out on types that aren't i.e. <code>Copy</code>, such as BigInts that are heap-allocated. In that case, you can do:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use std::fmt;\n\nimpl&lt;T: Copy&gt; Copy for Fibonacci&lt;T&gt; {}\n\nimpl&lt;T: Clone&gt; Clone for Fibonacci&lt;T&gt; {\n fn clone(&amp;self) -&gt; Self {\n Self {\n curr: self.curr.clone(),\n next: self.next.clone(),\n }\n }\n}\n\nimpl&lt;T: PartialEq&gt; PartialEq for Fibonacci&lt;T&gt; {\n fn eq(&amp;self, rhs: &amp;Self) -&gt; bool {\n self.curr == rhs.curr &amp;&amp; self.next == rhs.next\n }\n}\n\nimpl&lt;T: fmt::Debug&gt; fmt::Debug for Fibonacci&lt;T&gt; {\n fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result {\n f.debug_struct(\"Fibonacci\")\n .field(\"curr\", &amp;self.curr)\n .field(\"next\", &amp;self.next)\n .finish()\n }\n}\n</code></pre>\n\n<p>(note that I normally prefer the <code>T: Trait</code> syntax. You can use <code>where</code> instead) Unfortunately, yes, that does create a lot of repeated noise. However, you require that your types are <code>PrimInt</code>s anyways, so you will never have a type that isn't <code>Copy</code>, <code>Clone</code>, <code>Debug</code>, or <code>PartialEq</code>. But the end result isn't much prettier:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Copy, Clone, Debug, PartialEq)]\npub struct Fibonacci&lt;T: Copy + Clone + Debug + PartialEq&gt; {\n curr: T,\n next: T,\n}\n\nimpl&lt;T&gt; Fibonacci&lt;T&gt; where T: Copy + Clone + Debug + PartialEq + PrimInt {\n pub fn new() -&gt; Self {\n Self { curr: T::zero(), next: T::one() }\n }\n}\n\nimpl&lt;T&gt; Default for Fibonacci&lt;T&gt; where T: Copy + Clone + Debug + PartialEq + PrimInt {\n fn default() -&gt; Self {\n Self::new()\n }\n}\n\nimpl&lt;T&gt; Iterator for Fibonacci&lt;T&gt; where T: Copy + Clone + Debug + PartialEq + PrimInt {}\n</code></pre>\n\n<p>One way to fix this is to create a new trait that has all five of those bounds. In fact, there's a <a href=\"https://github.com/rust-lang/rust/issues/41517\" rel=\"nofollow noreferrer\">current issue</a> to do just that. However, we can create our own trait in the meantime to fix that:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>pub trait Primitive: Copy + Clone + Debug + PartialEq + PrimInt {}\nimpl&lt;T: Copy + Clone + Debug + PartialEq + PrimInt&gt; Primitive for T {}\n</code></pre>\n\n<p>So now we have:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use std::fmt::Debug;\n\npub trait Primitive: Copy + Clone + Debug + PartialEq + PrimInt {}\nimpl&lt;T: Copy + Clone + Debug + PartialEq + PrimInt&gt; Primitive for T {}\n\n#[derive(Copy, Clone, Debug, PartialEq)]\npub struct Fibonacci&lt;T: Primitive&gt; {\n curr: T,\n next: T,\n}\n\nimpl&lt;T&gt; Fibonacci&lt;T&gt; where T: Primitive {\n pub fn new() -&gt; Self {\n Self { curr: T::zero(), next: T::one() }\n }\n}\n\nimpl&lt;T&gt; Default for Fibonacci&lt;T&gt; where T: Primitive {\n fn default() -&gt; Self {\n Self::new()\n }\n}\n\nimpl&lt;T&gt; Iterator for Fibonacci&lt;T&gt; where T: Primitive {}\n</code></pre>\n\n<p>So, all in all, you don't have to do this if you don't want, as it's quite source-heavy.</p>\n\n<h2>(Optional) use <code>mem::replace</code></h2>\n\n<p>This part:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {\n let next = self.curr + self.next;\n let prev = self.curr;\n self.curr = self.next;\n self.next = next;\n Some(prev)\n}\n</code></pre>\n\n<p>Can be changed to:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use std::mem;\n\nfn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {\n let next = self.curr + self.next;\n let prev = mem::replace(&amp;mut self.curr, self.next);\n self.next = next;\n Some(prev)\n}\n</code></pre>\n\n<p>It's not any faster or shorter, but it's your choice whether it expresses your intent better. I think it does, but it doesn't matter that much.</p>\n\n<h1>Final code</h1>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use num_traits::PrimInt;\nuse std::mem;\nuse std::fmt::Debug;\n\npub trait Primitive: Copy + Clone + Debug + PartialEq + PrimInt {}\nimpl&lt;T: Copy + Clone + Debug + PartialEq + PrimInt&gt; Primitive for T {}\n\n#[derive(Copy, Clone, Debug, PartialEq)]\npub struct Fibonacci&lt;T: Primitive&gt; {\n curr: T,\n next: T,\n}\n\nimpl&lt;T&gt; Fibonacci&lt;T&gt; where T: Primitive {\n pub fn new() -&gt; Self {\n Self { curr: T::zero(), next: T::one() }\n }\n}\n\nimpl&lt;T&gt; Default for Fibonacci&lt;T&gt; where T: Primitive {\n fn default() -&gt; Self {\n Self::new()\n }\n}\n\nimpl&lt;T&gt; Iterator for Fibonacci&lt;T&gt; where T: Primitive {\n type Item = T;\n\n fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {\n let next = self.curr.checked_add(&amp;self.next)?;\n let prev = mem::replace(&amp;mut self.curr, self.next);\n self.next = next;\n Some(prev)\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T03:15:40.130", "Id": "240482", "ParentId": "240463", "Score": "1" } } ]
{ "AcceptedAnswerId": "240482", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T21:39:59.133", "Id": "240463", "Score": "2", "Tags": [ "rust", "iterator", "fibonacci-sequence" ], "Title": "Fibonacci iterator" }
240463
<p>(Last Post) <a href="https://codereview.stackexchange.com/questions/240310/mail-crypt-cli-encrypted-email-wrapper-for-gmail">Mail Crypt CLI encrypted email wrapper for Gmail</a></p> <p>I've spent the past few days re-writing the logic of my program as a library to improve the structure and readability of my code. The idea behind MailCrypt is for it to be a python based client/library that allows you to locally encrypt messages and send them through Gmail or any SMTP/IMAP server. The encryption scheme is based off of hybrid RSA/AES encryption, where the message body is encrypted with AES and the one time session key is RSA PKCS1 OEAP. It also provides validation of the sender by hashing and signing the hash with your private key. For this to run it needs pycryptodome but it's imported as Crypto, as well as less secure connections need to be enabled on the Gmail account. Any feedback would be greatly appreciated.</p> <pre><code>"""Library for send and receiveing encrypted emails.""" import pickle import email import imaplib import smtplib from Crypto.Hash import SHA512 from Crypto.Cipher import PKCS1_OAEP from Crypto.Cipher import AES from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Signature import pss class MailCrypt: """Core compents for encryption/decryption and key generation.""" aes_session_key_length = 32 def __init__(self, private_key, public_key): """Takes in public key, private key.""" self.private_key = private_key self.public_key = public_key def encrypt_msg(self, message, recpient_public_key): """Generates a session key to use with AES to encrypt the message, then encrypts the session key with the recipients public key. Everything is returned in hex format to be better sent over email.""" session_key = get_random_bytes(self.aes_session_key_length) aes_cipher = AES.new(session_key, AES.MODE_EAX) aes_cipher_text, tag = aes_cipher.encrypt_and_digest(message) return ( aes_cipher_text.hex() + ' ' + tag.hex() + ' ' + aes_cipher.nonce.hex() + ' ' + PKCS1_OAEP.new(recpient_public_key).encrypt(session_key).hex() + ' ' + pss.new(self.private_key).sign(SHA512.new(message)).hex() ) def decrypt_msg(self, message, sender_public_key): """Splits the message into its sections Indicies: 0 aes_cipher_text 1 tag 2 nonce 3 enc_session_key 4 signature Decrypts the session key, then decrypts the message body. If aes_cipher.verify throws an error that means an invalid tag was provided If pss.new throws an error that means the message signature is invalid""" seperated_msg = [ value.encode().fromhex(value) for value in message.split(' ') ] aes_cipher = AES.new( PKCS1_OAEP.new(self.private_key).decrypt(seperated_msg[3]), AES.MODE_EAX, nonce=seperated_msg[2], ) clear_text = aes_cipher.decrypt(seperated_msg[0]) try: aes_cipher.verify(seperated_msg[1]) tag_status = True except ValueError: tag_status = False try: pss.new(sender_public_key).verify(SHA512.new(clear_text), seperated_msg[4]) sig_status = True except ValueError: sig_status = False return tag_status, sig_status, clear_text def update_keys(self, private_key, public_key): """Updates the keys in the mailcrypt object if new keys are generated""" self.public_key = public_key self.private_key = private_key class Keys: """Handles key pair creation and storage.""" rsa_key_length = 4096 my_private_key = None my_public_key =None def __init__(self): self.key_dict = {} def load_my_keys(self, passwd): """Loads saved keys in from file.""" with open('private_key.pem', 'r') as fprivate_key_save, \ open('my_public_key.pem', 'r') as fpublic_key_save: self.my_public_key = RSA.import_key(fpublic_key_save.read()) self.my_private_key = RSA.import_key(fprivate_key_save.read(), passphrase=passwd) def load_keys(self): """Read public keys in from file. Must be in same folder as script is run from.""" with open('public_key_bank.pkl', 'rb') as fpublic_key_file: self.key_dict = pickle.load(fpublic_key_file) def export_keys(self): """Saves key_dict to file.""" with open('public_key_bank.pkl', 'wb') as fpublic_key_file: pickle.dump(self.key_dict, fpublic_key_file) def add_key(self, address, key): """Adds key to to key_dict.""" self.key_dict[address] = key def retreive_key(self, address): """Retrievs public key based on email.""" return RSA.import_key(self.key_dict[address]) def generate_keys(self, passwd): """Generates public and private key pairs and exports them as .pem files.""" private_key = RSA.generate(self.rsa_key_length) public_key = private_key.publickey() with open('my_public_key.pem', 'wb') as fpub, \ open('private_key.pem', 'wb') as fpri: fpub.write(public_key.export_key('PEM')) fpri.write(private_key.export_key('PEM', passphrase=passwd)) def generate_keys_test(self): """"Used for testing, returns key pair.""" private_key = RSA.generate(self.rsa_key_length) public_key = private_key.publickey() return private_key, public_key @classmethod def change_rsa_key_length(cls, length): """Changes the key length for the key pair generation must be powers of 256""" cls.rsa_key_length = length @classmethod def change_aes_key_length(cls, length): """Changes the AES session key length must be 8, 16, or 32""" cls.aes_session_key_length = length class Email: """Handles all of the imap and smtp connections and functionality""" smtp_port = 465 def __init__(self, smtp_server_address, imap_server_address, username, passwd, mailcrypt_instance, keys_instance): """Opens a connections to specified imap and smtp servers, logs in with the given username and passwords and navagaits to the inbox folder.""" self.smtp = smtplib.SMTP_SSL(smtp_server_address, self.smtp_port) self.imap = imaplib.IMAP4_SSL(imap_server_address) self.username = username self.passwd = passwd self.smtp.ehlo() self.smtp.login(username, passwd) self.imap.login(username, passwd) self.mailcrypt = mailcrypt_instance self.imap.select('inbox') self.keys = keys_instance @classmethod def change_smtp_port(cls, port): """Allows you to change the port for the smtp connection if useing a non-standard configuraation.""" cls.smtp_port = port def send(self, recipient, message): """Sends plain text email.""" self.smtp.sendmail(self.username, recipient, message) def read(self, uid): """Fetches plain text email based on uid and returns the message body.""" _, email_data = self.imap.uid('fetch', uid, '(RFC822)') msg = email.message_from_bytes(email_data[0][1]) return msg.get_payload() def send_encrypted(self, recipient, message): """Sends encrypted message.""" message = self.mailcrypt.encrypt_msg(message.encode(), self.keys.retreive_key(recipient)) self.smtp.sendmail(self.username, recipient, message) def read_encrypted(self, uid): """Fetches email from given uid and returns clear text.""" _, email_data = self.imap.uid('fetch', uid, '(RFC822)') msg = email.message_from_bytes(email_data[0][1]) return self.mailcrypt.decrypt_msg(msg.get_payload(), self.keys.retreive_key(msg['From'])) def mark_delete(self, uid): """Moves the specified email to trash folder. If useing email provider other than gmail 'Trash' needs to be changed to whatever folder that service uses.""" self.imap.uid('store', uid, '+X-GM-LABELS', '(\\Trash)') def delete_all(self): """Empties the trash folder.""" self.imap.expunge() def import_key(self): """Checks message payloads for public keys, if found it yeilds the senders email address and the public key.""" for message in self.get_emails(): msg_body = self.read(message[0]) if 'PUBLIC' in msg_body: yield message[1], msg_body def get_emails(self): """Yeilds tuple with uid and senders address for every message in the inbox folder.""" _, data = self.imap.uid('search', None, 'ALL') for uid in data[0].split(): _, email_data = self.imap.uid('fetch', uid, '(RFC822)') msg = email.message_from_bytes(email_data[0][1]) yield uid.decode(), msg['From'] def share_public_key(self, recipient): """Sends public key.""" self.send(recipient, self.mailcrypt.public_key.export_key('PEM')) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T22:52:39.607", "Id": "471710", "Score": "0", "body": "Can you explain why you've made the changes you have. Merging `Email` and `MailCypt` into one class, why you've merged `PublicStore` and `PersonalKey`, and why some methods that were not defined on classes now are attached to classes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:03:38.197", "Id": "471713", "Score": "0", "body": "MailCrypt and Email are separate classes, unless your referring to where a MailCrypt object is being pass as an argument to the email class. If that is the case then I did that to use with the send_encrypted and read_encrypted, in hind sight it might have been better to not assign the keys in MailCrypt's __init__ and just have them passed in as an argument when the encryption/decryption function is needed. As for the merging of PublicStore and PersonalKey, I wasn't sure if I should have them as stand alone class or include them in Keys, in an attempt to group everything key related." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:05:51.343", "Id": "471714", "Score": "0", "body": "No, that's not what I'm referring to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:13:59.783", "Id": "471716", "Score": "0", "body": "I'm confused, could you elaborate more on what you meant then?" } ]
[ { "body": "<h2>Typo</h2>\n\n<p><code>seperated_msg</code> -> <code>separated_msg</code></p>\n\n<p><code>Retrievs</code> -> <code>Retrieves</code></p>\n\n<h2>Hex-able join</h2>\n\n<p>This:</p>\n\n<pre><code> return (\n aes_cipher_text.hex()\n + ' ' + tag.hex()\n + ' ' + aes_cipher.nonce.hex()\n + ' ' + PKCS1_OAEP.new(recpient_public_key).encrypt(session_key).hex()\n + ' ' + pss.new(self.private_key).sign(SHA512.new(message)).hex()\n )\n</code></pre>\n\n<p>can be converted into a <code>join</code>, since everything there has <code>hex</code> called on it:</p>\n\n<pre><code>pub = PKCS1_OAEP.new(recpient_public_key).encrypt(session_key)\npriv = pss.new(self.private_key).sign(SHA512.new(message))\nreturn ' '.join(\n part.hex() for part in (\n aes_cipher_text,\n tag,\n aes_cipher.nonce,\n pub,\n priv,\n )\n)\n</code></pre>\n\n<p>I also think that <code>pub</code> and <code>priv</code> should be separated due to their length.</p>\n\n<h2>Unpacking</h2>\n\n<p>On the other end, in <code>decrypt_msg</code>, you should not be using array indices into <code>seperated_msg</code>. Instead,</p>\n\n<pre><code>aes_cipher_text, tag, none, enc_session_key, signature = (\n value.encode().fromhex(value)\n for value in message.split(' ')\n)\n</code></pre>\n\n<p>Somewhat similarly, this:</p>\n\n<pre><code> for message in self.get_emails():\n msg_body = self.read(message[0])\n if 'PUBLIC' in msg_body:\n yield message[1], msg_body\n</code></pre>\n\n<p>should unpack whatever <code>message</code> is into two different iteration variables.</p>\n\n<h2>Boolean returns</h2>\n\n<p><code>tag_status</code> and <code>sig_status</code> are not very Pythonic ways of capturing error information. If it's important to separate failure types in this way, rather than returning two different booleans, throw (potentially) two different custom exception types that <code>throw from e</code> (rethrow) <code>ValueError</code>.</p>\n\n<h2>Statics</h2>\n\n<p>These three have problems:</p>\n\n<pre><code>class Keys:\n rsa_key_length = 4096\n my_private_key = None\n my_public_key =None\n</code></pre>\n\n<p>The first should be capitalized since it's a class constant. The second and third probably should not be statics, and should be instance variables instead.</p>\n\n<h2>Symmetric nomenclature</h2>\n\n<p>Rather than <code>load_keys</code> / <code>export_keys</code>, consider either <code>load_keys</code>/<code>save_keys</code> or <code>export_keys</code>/<code>import_keys</code>.</p>\n\n<h2>Bundled context manager</h2>\n\n<p>This:</p>\n\n<pre><code> with open('my_public_key.pem', 'wb') as fpub, \\\n open('private_key.pem', 'wb') as fpri:\n fpub.write(public_key.export_key('PEM'))\n fpri.write(private_key.export_key('PEM', passphrase=passwd))\n</code></pre>\n\n<p>should be separated into two different <code>with</code> statements. Those two files are independent and should not share a context scope.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:45:01.150", "Id": "471718", "Score": "1", "body": "This all looks like good stuff. At first by \"split\" in \"bundled context manager\" you meant nested. I'm assuming you mean they should be split into a public and private `with`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T00:46:28.543", "Id": "471720", "Score": "1", "body": "Thanks. Yes, a `with` for `fpub` and a `with` for `fpri`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T22:56:57.210", "Id": "240466", "ParentId": "240465", "Score": "6" } } ]
{ "AcceptedAnswerId": "240466", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T22:38:23.543", "Id": "240465", "Score": "4", "Tags": [ "python", "python-3.x", "email", "encryption" ], "Title": "Mail Crypt Library for encrypted email" }
240465
<p>I've just learned the OOP concept of abstraction, and I was wondering if I was implementing it correctly in my code and if you guys can point out any bad practices.</p> <h3>test1.java</h3> <pre><code>package OOPConcepts; import java.util.Scanner; public class test1 { static public Scanner input = new Scanner(System.in); public static void main(String[] args) { String fName, lName; int age; Student newPerson = new Student(); input.close(); } } </code></pre> <h3>Person.java</h3> <pre><code>package OOPConcepts; public class Person { static private int pNumber = 0; private int pID; public int age; private String type; public String fName, lName; Person() { pNumber++; pID = pNumber; System.out.println("Enter first name:"); String fName = test1.input.next(); System.out.println("Enter last name:"); String lName = test1.input.next(); System.out.println("Enter age:"); int age = test1.input.nextInt(); type = "person"; describe(fName, lName, age); System.out.println("Made a " + type); } public void setType(String type){ this.type = type; } public String getType() { return this.type; } public void describe(String fName, String lName, int age) { this.fName = fName; this.lName = lName; this.age = age; System.out.println("Name: " + this.fName + " " + this.lName + "|Age: " + this.age); } } </code></pre> <h3>Student.java</h3> <pre><code>package OOPConcepts; public class Student extends Person{ static private int sNumber = 0; private int studentID; public String major; Student() { sNumber++; studentID = sNumber; setType("student"); System.out.println("Who is also a " + getType()); System.out.println("Enter major: "); String major = test1.input.next(); this.major = major; } public void setStudentID(int idNumber) { this.studentID = idNumber; } public int getStudentID() { return this.studentID; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T14:03:56.697", "Id": "471785", "Score": "0", "body": "I think that the inheritance between `Student` and `Person` is not a correct relationship. While in natural language we can say a student is a type of person, but to model it in software a person is a student when they're enrolled at a school. To elaborate on what I'm describing, what if this person goes to two schools? A class such as `class Student { +School school, +Person person, int studentNumber }` may map better to reality." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T09:37:59.990", "Id": "471857", "Score": "0", "body": "@Matthew: The important part is how studenthood is defined for the current application. Is it a property of a person, or is it a property of a person's enrollment in an institute? If the former, then there is no duplication issue regardless of exactly how many enrollments a person may have. If the latter, then your comment is pointing out a valid issue." } ]
[ { "body": "<p>Sorry, you are not implementing OOP well, since it is true that you are defining a class, declaring its fields and instantiating it, this is being done in a wrong way.</p>\n<h3>The Good</h3>\n<ul>\n<li>The abstraction is carried out properly for an exercise (because in a real design you may need more details)</li>\n<li>The idea of giving a person an ID aka <code>pNumber</code> is something which will be closely related to ORM (Object Relational Mappings) which is a way to communicate your database(s) with your object oriented design</li>\n</ul>\n<h3>Review</h3>\n<ul>\n<li><strong>Don't Declare Public Variables</strong>, you have Getter/Setter methods to access the values or modify them.</li>\n<li>In the class which owns your main method is where should go all the data gathering. Doing this</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> Person()\n {\n pNumber++;\n pID = pNumber;\n //...\n</code></pre>\n<p>Is a bad practice you should (must) untie the logic from the view. Even if this is concept from the MVC (model view controller) pattern it is important to do that in each project in order to improve software quality, reduce errors and having a independent work structure so that when you change the UI for the user it won't affect the logic.</p>\n<p>The alternative is to create a parametrized constructor:</p>\n<pre class=\"lang-java prettyprint-override\"><code> Person(String fName, String lname, int age)\n {\n //also conssider call pID as personId (be descriptive)\n this.pID = ++pNumber;\n this.fName = fName;\n this.lName = lName;\n this.age = age;\n }\n\n///how to use (in your main method)\n Person person = new Person(&quot;Syntëy&quot;, &quot;Emyl&quot;, 27);\n</code></pre>\n<ul>\n<li>The variable <code>type</code> in Person class is something ambiguous (yes it is the type of the person but which implications does it have? which values may it take?), you should add a comment before the variable to describe it.</li>\n</ul>\n<h3>Some suggestions</h3>\n<ul>\n<li>Always use private fields.</li>\n<li>The names given to your variables, it is quite short, it is not bad but it is better to specify them well so that your getter/setter have a quick meaning, <code>fName</code>, <code>lName</code> could be changed by <code>firstName</code>, <code>lastName</code>.</li>\n<li>The static variable <code>pNumber</code> or <code>sNumber</code> could be named <code>personIdCounter</code> <code>studentIdCounter</code></li>\n<li>It is not a standard but most people works with a regular expression which matches the following:\n<code>[AccessModifier] [DataType] [FieldName];</code> and for static variables <code>[AccessModifier] static [DataType] [FieldName];</code></li>\n<li>Try to not declare multiple fields (attributes) in the same line as in <code>public String fName, lName;</code></li>\n</ul>\n<p>Finally, I hope it has been helpful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T02:07:38.203", "Id": "471722", "Score": "1", "body": "Thank you so much! Yes this helps a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T00:46:31.197", "Id": "240475", "ParentId": "240468", "Score": "8" } }, { "body": "<p><strong>What is OOP?</strong></p>\n\n<p>There is more to OOP than just class inheritance and your example shows painfully clearly why class hierarchy is almost always completely unable to represent the real world. If a student is a specialized type of a person, then a person can not be a student and a teacher at the same time (e.g. an assistant to a teaching professor). Also, that person can no longer be a part time employee at the cafeteria either, because the person's status has been locked into being a student and student only. Clearly, class inheritance is the wrong tool here. The relation should be composition:</p>\n\n<pre><code>public class Student {\n private final StudentId studentId;\n private final Person person;\n\n public Student(StudentId studentId, Person person) {\n this.studentId = studentId;\n this.person = person;\n }\n\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T14:09:28.730", "Id": "471786", "Score": "0", "body": "I think this is a very good point, I added a comment to the question without seeing this first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T20:35:02.200", "Id": "472619", "Score": "0", "body": "Hi, thank you so much for your input! How would you structure this code so that a person can have multiple occupations like Student, and Worker? I was thinking of adding an array list in the person object, and this array list will store all the occupancy objects. That way I all I have to do in order to reference to a person's occupancy is access the arraylist in the person object. I have yet to implement this in code. I wanted to ask you if there was a better approach. Thank you so much again Torben." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T05:04:40.283", "Id": "240484", "ParentId": "240468", "Score": "9" } }, { "body": "<p>Miguel has made some excellent points; I won’t repeat those. Here are some more comments / suggestions:</p>\n\n<hr>\n\n<p>The <code>type</code> field is effectively public, because you have <code>public void setType(String type)</code>, yet it is clear that this field should not be settable externally. It shouldn’t exist at all, since we can simply ask:</p>\n\n<pre><code>if (person instanceof Student) {…}\n</code></pre>\n\n<p>instead of needing to check a string to see if it is equal to <code>\"student\"</code> (or was that \"Student\"? Or maybe it was <code>\"STUDENT\"</code>??? Maybe you should be using named constants ... or better ... an <code>enum</code>!)</p>\n\n<hr>\n\n<p><code>age</code> is a horrible field. As time goes by, it changes. If you have multiple people in a database, you are constantly updating the records. Store their birthdate, and compute their age.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T09:37:30.577", "Id": "471856", "Score": "0", "body": "imho I think that age can be a valid field, depending on the meaning/usage of the class. If it's representing a db object, I would say it's bad. If it's a domain object, a view layer class with a age field that gets for instance calculated, then it sounds acceptable to me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T05:06:20.727", "Id": "240485", "ParentId": "240468", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-13T23:49:55.690", "Id": "240468", "Score": "7", "Tags": [ "java", "object-oriented" ], "Title": "Practicing OOP with Student and Person" }
240468
<p>My codes are not good, I want to konw how to solve my problem efficicently and learn writing some elegant R codes.Thanks in advance!</p> <p>"r" is the starting value in <code>matrix[loop,T]</code>, I want to use it to do the simulation for 45years in 10 times,which means that I will get a new <code>matrix[loop,T]</code> also name "r" after first for-loop.Then, I want to use the second column data in this new matrix "r" to do the simulation again,which means that I will use <code>r[1,2],r[2,2],r[3,2]...r[loop,2]</code> to do the simulation, in this way,each data in r[,2] will create a matrix name "b"<code>[loop,T]</code>,so I compute the average value of the second column in each matrix "b"<code>[loop,T]</code>, then I get 10(=loop) new starting values again to do the simulation.At last,I have the final_data output</p> <pre><code>alpha&lt;-0.0212;beta&lt;-0.0063;sigma&lt;-0.0012;dt&lt;-1;T&lt;-46;loop&lt;-10 r&lt;-matrix(rep(-0.0002,loop*T),loop,T) for(i in 1:loop) { for(j in 2:T) { r[i,j]&lt;-r[i,j-1]+alpha*(beta-r[i,j-1])*dt+sigma*sqrt(dt)*rnorm(1,0,1) } } c&lt;-matrix(rep(0,loop*1),loop,1) for(k in 1:loop) { b&lt;-matrix(rep(r[k,2],loop*T),loop,T) for(i in 1:loop) { for(j in 2:T) { b[i,j]&lt;-b[i,j-1]+alpha*(beta-b[i,j-1])*dt+sigma*sqrt(dt)*rnorm(1,0,1) } } c[k,1]&lt;-mean(b[,2]) } e&lt;-matrix(rep(0,loop*1),loop,1) for(k in 1:loop) { d&lt;-matrix(rep(c[k,1],loop*T),loop,T) for(i in 1:loop) { for(j in 2:T) { d[i,j]&lt;-d[i,j-1]+alpha*(beta-d[i,j-1])*dt+sigma*sqrt(dt)*rnorm(1,0,1) } } e[k,1]&lt;-mean(d[,2]) } final_data&lt;-data.frame(r[,2],c,e) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:41:12.987", "Id": "483206", "Score": "0", "body": "Can you explain what you are trying to simulate?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T00:23:52.833", "Id": "240474", "Score": "1", "Tags": [ "r", "simulation", "iteration" ], "Title": "conditional simulation(path dependent simulation) in R" }
240474
<p>I wrote these lines of rust yesterday. It turns 27 bits from a 32 bit integer into a 3x9 byte array, but my gut feeling is this should be done without having a mutable variable <code>ans</code>.</p> <pre><code>pub fn u32_to_preformated_vector(image:u32) -&gt;[[u8;9];3] { let mut ans:[[u8; 9]; 3]= [[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]]; let image = !image; for i in 0..27 { ans[i/9][i%9] = 1 &amp; (image &gt;&gt; i) as u8; } ans } </code></pre> <p>What would make the cleanest code here? <em>A macro</em> or some <em>iterator magic</em>?</p>
[]
[ { "body": "<p>Please also see also the code here: <a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=574d96b16d82c5816ebc35c5d88acda2\" rel=\"nofollow noreferrer\">https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=574d96b16d82c5816ebc35c5d88acda2</a></p>\n\n<p>The name of the function <code>u32_to_preformated_vector</code> let me assume I get something else that what I'm actually get. So I think the naming could improve:</p>\n\n<ul>\n<li>the function actually does not return a vector, but an array;</li>\n<li>the function does invert the input bits. That's completely invisible in the name.</li>\n<li>You might even indicate the bit order you handle the conversion in, as not everybody might expect to get the least significant bit/the least significant nonet first.</li>\n</ul>\n\n<p>Keeping the mutable array, I came to this code:</p>\n\n<pre><code>pub fn u32_to_preformatted_array(image: u32) -&gt; [[u8; 9]; 3] {\n let mut result = [[0u8; 9]; 3];\n let inverted = !image;\n for n in 0..3 {\n let nonet = inverted &gt;&gt; n * 9;\n for m in 0..9 {\n result[n][m] = 1 &amp; (nonet &gt;&gt; m) as u8;\n }\n }\n result\n}\n</code></pre>\n\n<p>I thought it would help if I bind the inverted <code>image</code> to a new name (<code>inverted</code>). That way in the <code>for</code> loop the reader sees that it is a different value to the one that was passed to the function as the argument.</p>\n\n<p>I also converted the single <code>for</code> loop to two nested <code>for</code> loops. While nesting these loops in general might cause performance problems, it does no harm here, as the number of iterations in the inner code keep the same (27). That way I think the index handling is clearer than doing a divide and a remainder to calculate them. It might also make the bit order more obvious.</p>\n\n<p>The initial value of the array can be initialized in a compacter way as all values in it are the same (<code>0u8</code> in this case).</p>\n\n<p>I don't think having a mutable array inside the function is a big deal. While I very much go for immutability in general, here the context within which mutation is possible is quite limited. As this is the place where the value gets built, there is no danger of it being used at a different place. From the point you return the value, it will be immutable by the declaration of your function.</p>\n\n<p>I was also trying to get rid of this single <code>mut</code> by using iterators. It's quite easy as long as you change the return type of the function from arrays to vectors:</p>\n\n<pre><code>pub fn u32_to_preformatted_vec(image: u32) -&gt; Vec&lt;Vec&lt;u8&gt;&gt; {\n let inverted = !image;\n (0..3)\n .map(|i| (inverted &gt;&gt; 9 * i) &amp; 0b111_111_111) // `&amp;` not strictly needed\n .map(|nonet| (0..9).map(|i| 1 &amp; (nonet &gt;&gt; i) as u8).collect())\n .collect()\n}\n</code></pre>\n\n<p>In general I have the impression working in a map/reduce style works a lot better with <code>Vec</code> than on arrays. You can also convert the <code>Vec</code> to a slice, but the conversion to an array is harder and often is done using functions like <code>.clone_from_slice()</code> which require a previously allocated array that is mutable again. I also tried to get a slice for the <code>Vec</code> and then use the <a href=\"https://stackoverflow.com/questions/25428920/how-to-get-a-slice-as-an-array-in-rust\"><code>TryFrom</code> trait</a> to convert it to an array. While I got this working for single dimensional array, I didn't get it to work for the multidimensional array <code>[[u8; 9]; 3]</code>.</p>\n\n<p>There is also rarely a need to go from a <code>Vec</code> to an array when designing the solution. <code>Vec</code> is just a little bit of code around an array (that's why to can get a slice from it so easily). So you don't really save anything when using an array.</p>\n\n<p>Thinking about the whole problem as such, I wonder what's the reason for this conversion. You're blowing a 4 byte value up to using 27 bytes of memory. That way you increase the memory usage of your program, and I don't know what you get for it. I don't think that it will actually improve performance because you loose locality when accessing the data. The caching in your computer will not work as good as by using the original 4 byte value.</p>\n\n<p>If the goal you try to get from the conversion is improved readability, I think you might try to define helper functions to get (or set) the individual bits. The calculations are actually quite easy, are performed in the CPU registers and can be inlined by the compiler. That should be quite fast … faster than converting the data to this two dimensional array which requires a lot of access to the computer's memory because it cannot be done in registers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T01:08:57.187", "Id": "472101", "Score": "0", "body": "I will comment on this more later but for now- yes the whole code seems strange but the reason for this crazy conversion is to use my small u32 encoded images in the microbit crate which takes a 3x9 array as argument." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T10:54:57.717", "Id": "240614", "ParentId": "240480", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T02:23:45.303", "Id": "240480", "Score": "0", "Tags": [ "rust" ], "Title": "Unroll for loop as macro to make array unmutable" }
240480
<p>As you can see <a href="https://codereview.stackexchange.com/questions/240382/roman-numbers-in-java">here</a>, I wrote the methods <code>public static int romanToArabic(String number)</code> and <code>public static String arabicToRoman(int number)</code> to convert roman numbers to arabic numbers and vice versa.</p> <p>I now wrote a unit-testing-class to test these methods. It is my first attempt to write a (real) unit test, so I would like to know your opinion.</p> <p>Here's the code:</p> <pre><code>import org.junit.Test; import static org.junit.Assert.*; public class TestCases { @Test public void testRomanToArabic() { String[] input = {null, "", "I", "V", "XXXIII", "DCCXLVII", "CMXXIX", "MCCXXXII", "MMMCMXCIX", "MMMMXI", "KMXI", "VX", "VL", "VC", "VD", "VM", "LC", "LD", "LM", "DM", "IL", "IC", "ID", "IM", "XD", "XM", "CXLV", "MIXI", "IXI", "MXIII", "MMMM", "IIII"}; int[] expectedOutput = {-1, -1, 1, 5, 33, 747, 929, 1232, 3999, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 145, -1, -1, 1013, -1, -1}; for(int i = 0; i &lt; input.length; i++) { int k = RomanNumbers.romanToArabic(input[i]); try { assertEquals(k, expectedOutput[i]); } catch(AssertionError assertFailed) { System.out.println("Test failed!"); System.out.println("Input: " + input[i]); System.out.println("Output: " + k + "| Expected: " + expectedOutput[i]); } } } @Test public void testArabicToRoman() { int[] input = {-1, 1, 5, 33, 747, 929, 1232, 3999, 4000}; String[] expectedOutput = {"Error", "I", "V", "XXXIII", "DCCXLVII", "CMXXIX", "MCCXXXII", "MMMCMXCIX", "Error"}; for(int i = 0; i &lt; input.length; i++) { String k = RomanNumbers.arabicToRoman(input[i]); try { assertEquals(k, expectedOutput[i]); } catch(AssertionError assertFailed) { System.out.println("Test failed!"); System.out.println("Input: " + input[i]); System.out.println("Output: " + k + "| Expected: " + expectedOutput[i]); } } } } </code></pre> <p>Is this the way to go, or is it considered bad practice to put more than one test in a method? Do you have any other suggestions on improving the code?</p>
[]
[ { "body": "<p>I have two suggestions:</p>\n\n<ol>\n<li>I like tests to be very easily human-readable. Instead of separate arrays of input and output, which are not aligned with each other, find a way to put the input and the expected output on one line.</li>\n</ol>\n\n<p>The easiest way in this case would be to add a method</p>\n\n<pre><code>private void testRomanToArabic(String input, int expectedOutput) {\n assertEquals(RomanNumbers.romanToArabic(input), expectedOutput);\n}\n</code></pre>\n\n<p>and then use this method repeatedly like</p>\n\n<pre><code>testRomanToArabic(\"XXXIII\", 33);\n</code></pre>\n\n<p>etc. There are other ways to put input and expected output next to each other (e.g. create an object holding both), but this is the simplest.</p>\n\n<ol start=\"2\">\n<li>Don't catch the AssertionError and print the result yourself. The test should be run by a test runner which will handle this part for you. I always do this from the Eclipse IDE by selecting \"Run As JUnit Test\", but there is for sure a way to do the same thing from the command line.</li>\n</ol>\n\n<p>By catching the AssertionError, you hide the error from external tools, meaning you have to read the output yourself. If the AssertionError is thrown, your testing framework is aware of the error, which becomes very important when you have hundreds of tests: it can highlight for you the handful that are failing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T11:24:10.040", "Id": "240497", "ParentId": "240490", "Score": "4" } }, { "body": "<h1>Noise...noise...noise</h1>\n\n<p>There's quite a lot of noise in your tests. As has been pointed out by @OpenSauce, part of that is because you're catching the <code>AssertionError</code>. If you stop catching it, then your test runner will report the message embedded in the exception. As it stands, this message will be wrong, because you're passing your parameters to <code>assertEquals</code> the wrong way round:</p>\n\n<blockquote>\n <p>assertEquals(k, expectedOutput[i]);</p>\n</blockquote>\n\n<p>They should be:</p>\n\n<pre><code>assertEquals(expectedValue, actualValue)\n</code></pre>\n\n<p>Another source of noise is the iteration. Having loops like this in your tests obscures the relevant elements of the test. There are two obvious approaches for extracting the iteration aspect from the test.</p>\n\n<ol>\n<li><p>Extract each iteration into its own test. This allows tests to be given meaningful names and means that when you change related behaviour, you only have to change the impacted test. So, you might end up with some tests like:</p>\n\n<pre><code>romanToArabic_null_minusOne\nromanToArabic_empty_minusOne\nromanToArabic_I_one\n</code></pre>\n\n<p>etc. There's some repetition here, but there's a trade off because each individual test is more specific and easier to understand. It also helps you to understand your expectations, does it really make sense for <code>null/\"\"</code> to return <code>-1</code>, or should it throw an exception?</p></li>\n<li><p>Use a <a href=\"https://github.com/junit-team/junit4/wiki/Parameterized-tests\" rel=\"nofollow noreferrer\">parameterised</a> test. These allow the test behaviour to be separated from the test data. The test runner will then run the test, for each dataset, displaying the values passed in for each execution. This removes a lot of the need for the custom error handling to log the inputs into the test (which can get forgotten).</p></li>\n</ol>\n\n<p>You've also got some naming noise in your tests... Rather than calling your <code>TestCases</code>, give it a meaningful name that describes what it's testing. A common practice is to link it in some way to the class being tested, i.e. <code>RomanNumbersTests</code>. Having <code>test</code> at the start of all of your test names also seems redundant. They have <code>@Test</code> attributes and they're in a test class, so the runner can find them. I think of it as the class name, method name (and in the case of parameterised tests the parameters) combining to present a high level overview what each test is doing.</p>\n\n<p>Using meaningful names instead of <code>k</code>, such as <code>calculatedRomanValue</code> or <code>calculatedArabicValue</code> would also make your assertions easier to follow. Anything that makes the tests easier to read is positive.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-07T15:21:19.870", "Id": "241887", "ParentId": "240490", "Score": "2" } } ]
{ "AcceptedAnswerId": "240497", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T09:09:34.927", "Id": "240490", "Score": "3", "Tags": [ "java", "unit-testing", "junit" ], "Title": "Unit testing Roman-Arabic-Roman numeric converter" }
240490
<p>For the ADMIN: I wrote this tread on S.O. <a href="https://stackoverflow.com/questions/61183026/extract-data-from-wharehouse-stock-group-by-article-but-if-description-change">questions/61183026</a>, but I think that is more correct to post this tread here, if you think no, please scuse me and delete this message.</p> <p>Hi, I've one xls table with the stock values of goods into my warehouse, in the same file are the stock values from last 3 years. The Product Code are Unique, but the descriprione has been update some time. <a href="https://i.stack.imgur.com/XpNuV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XpNuV.png" alt="enter image description here"></a></p> <p>I need to check the difference from one year to other, if I group by Codice Articolo is easy, but i need to add the description. with the std qry I get one recordset for each different description like: <a href="https://i.stack.imgur.com/5EiWv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5EiWv.png" alt="enter image description here"></a></p> <p>my goal are group the recordset by Codice Articolo and use the last description used, I would practically use the description from the last year for each Codice Articolo. As I wrote, my table are in excel sheet and I post the results into another sheet, I use Microsoft.ACE.OLEDB.12.0 (ADODB.Recordset) This is my simple qry:</p> <pre><code>Set cn = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") Set rs = New ADODB.Recordset cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" &amp; ThisWorkbook.FullName &amp; "; Extended Properties=""Excel 8.0;HDR=Yes;"";" strsql = "SELECT [Codice Articolo], [Descrizione], Sum(IIf([anno]=2017,[qta],0)) AS Qta2017, Sum(IIf([anno]=2017,[Tot],0)) AS Val2017, Sum(IIf([anno]=2017,[€Pz],0)) AS Cad2017, Sum(IIf([anno]=2018,[Qta],0)) AS Qta2018, Sum(IIf([anno]=2018,[Tot],0)) AS Val2018, Sum(IIf([anno]=2018,[€pz],0)) AS Cad2018, Sum(IIf([anno]=2019,[Qta],0)) AS Qta2019, Sum(IIf([anno]=2019,[Tot],0)) AS Val2019, Sum(IIf([anno]=2019,[€pz],0)) AS Cad2019 FROM [temp$] GROUP BY [Codice Articolo], [Descrizione];" rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdUnspecified rs.MoveFirst Sheets("db").Range("A2").CopyFromRecordset rs </code></pre> <p>Into my head the code will be like at this:</p> <pre><code>strsql = "SELECT [Codice Articolo], (Select [Descrizione] FROM [temp$] where [anno]= max([anno]) and [Codice Articolo] = [Codice Articolo]) as Descr, Sum(IIf([anno]=2017,[qta],0)) AS Qta2017, Sum(IIf([anno]=2017,[Tot],0)) AS Val2017, Sum(IIf([anno]=2017,[€Pz],0)) AS Cad2017, Sum(IIf([anno]=2018,[Qta],0)) AS Qta2018, Sum(IIf([anno]=2018,[Tot],0)) AS Val2018, Sum(IIf([anno]=2018,[€pz],0)) AS Cad2018, Sum(IIf([anno]=2019,[Qta],0)) AS Qta2019, Sum(IIf([anno]=2019,[Tot],0)) AS Val2019, Sum(IIf([anno]=2019,[€pz],0)) AS Cad2019 FROM [temp$] GROUP BY [Codice Articolo], Descr;" </code></pre> <p>for obtain one result like this: <a href="https://i.stack.imgur.com/64wo1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/64wo1.png" alt="enter image description here"></a></p> <p>But, off course it not run.</p> <p>First I need to understad:</p> <ol> <li>thats I need is not possible <ul> <li>I've to search one work around </li> </ul></li> <li>is the correct way, but I need to change code <ul> <li>thank in advance for any suggestions</li> </ul></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T09:33:51.567", "Id": "471755", "Score": "3", "body": "Hello, unfortunately it seems your question is off-topic here because this site is for code working as expected, for further details you can check [Code Review ontopic](https://codereview.stackexchange.com/help/on-topic). I know it doesn't help but as you already described in your post SO probably is the right site for your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T09:39:38.273", "Id": "471756", "Score": "3", "body": "\"But, off course it not run\" If the code doesn't work, it's not ready for review. Please take a look at our [help/on-topic] for more information." } ]
[ { "body": "<p>I mistakenly mistaken CodeReview as an \"adjustment\" of our code, sorry.</p>\n\n<p>I was sure that the solution to my problem was with JOIN QUERY, I can't see the light because I needed two JOIN.</p>\n\n<p>below the solution that I found, I'm not sure is the Best solution, but it works as expected.\nsorry for the intrusion</p>\n\n<pre><code>strsql = \"SELECT t1.[Codice Articolo], t2.Descrizione,\" &amp; _\n\"Sum(IIf(t1.[Esercizio]=2017,t1.[NrPz],0)) AS Qta2017,\" &amp; _\n\"Sum(IIf(t1.[Esercizio]=2017,t1.[€Tot],0)) AS Val2017,\" &amp; _\n\"Sum(IIf(t1.[Esercizio]=2017,t1.[€Pz],0)) AS Cad2017,\" &amp; _\n\"Sum(IIf(t1.[Esercizio]=2018,t1.[NrPz],0)) AS Qta2018,\" &amp; _\n\"Sum(IIf(t1.[Esercizio]=2018,t1.[€Tot],0)) AS Val2018,\" &amp; _\n\"Sum(IIf(t1.[Esercizio]=2018,t1.[€pz],0)) AS Cad2018,\" &amp; _\n\"Sum(IIf(t1.[Esercizio]=2019,t1.[NrPz],0)) AS Qta2019,\" &amp; _\n\"Sum(IIf(t1.[Esercizio]=2019,t1.[€Tot],0)) AS Val2019,\" &amp; _\n\"Sum(IIf(t1.[Esercizio] = 2019, t1.[€pz], 0)) As Cad2019 \" &amp; _\n\"FROM ([temp$] t1 INNER JOIN [temp$] AS t2 ON t1.[Codice Articolo] = t2.[Codice Articolo]) INNER JOIN (SELECT Max([Esercizio]) AS maxdiEsercizio, [Codice Articolo] FROM [temp$] GROUP BY [Codice Articolo]) t3 ON (t2.[Codice Articolo] = t3.[Codice Articolo]) AND (t2.Esercizio = t3.maxdiEsercizio) \" &amp; _\n\"GROUP BY t1.[Codice Articolo], t2.Descrizione;\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T12:51:28.933", "Id": "240499", "ParentId": "240491", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T09:14:51.413", "Id": "240491", "Score": "-1", "Tags": [ "sql", "excel", "adodb" ], "Title": "SQL Group qry by codeProduct and Last(description)" }
240491
<p>With much of the world in lockdown at the moment, my friends and I wanted a way to play our favourite game, <a href="https://en.wikipedia.org/wiki/Celebrity_(game)" rel="nofollow noreferrer">Celebrity</a>, over video chat.</p> <p>This seemed like a fun coding project, so I put together a little web app. The functionality it would need to provide would be the ability for everyone to put names into a virtual hat, and for everyone to then take turns drawing names from the hat at random.</p> <p>My experience is in desktop application programming, and I have essentially none in web development. My goal was to get something minimally functional as quickly as possible, with no thought given to code elegance or maintainability, and to learn a little bit along the way.</p> <p>I settled on a pattern which was sufficient for this goal, but is unlikely to scale well for larger projects. This pattern is illustrated at the bottom of the post, together with my main questions, but I have some more specific minor questions along the way.</p> <p>The complete code is on <a href="https://github.com/merman25/Celebrity" rel="nofollow noreferrer">github</a>, but hopefully there's enough detail in this post for you to answer my questions without looking at all of it.</p> <p>Some decisions I took straight away:</p> <ul> <li>The game would run on the server, so that there would be a single authority on the game's current state</li> <li>The server would be written in Java, since it's the language I'm most familiar with</li> <li>The client would use HTML forms + buttons, and Javascript, since my background knowledge suggested this would be the quickest and simplest path to take.</li> </ul> <p>And the key bits of knowledge I was missing:</p> <ul> <li>How do I set up an HTTP server?</li> <li>How do I send data back and forth between browser and server, such as the celebrity names, whose turn it is, when a player has started/ended their turn, and what a player is doing on their turn?</li> <li>How do I create a webpage whose content changes dynamically in response to user actions or messages from the server?</li> <li>How do I keep track of individual clients and their sessions?</li> </ul> <h2>Setting up an HTTP Server</h2> <p>A bit of Googling told me there were <em>many</em> ways to do this, and I was a bit overwhelmed by choice. It looks like probably the most standard way to do something robust and scaleable would be to use Apache, but I saw some suggestions that this could be overkill for simple projects, and I didn't get as far as learning how Apache would run my own code. In the end, I went with the solution in <a href="https://stackoverflow.com/a/3732328/583274">this answer</a>, using the <code>com.sun.net.httpserver.HttpServer</code> class, since the Hello World example in that answer worked immediately.</p> <blockquote> <p>What would be the disadvantages of implementing a larger and feature-richer server using this class?</p> <p>I found I had to write my own code to find the HTML and Javascript files, map their names to URLs the users could access, and read these files and send their content when the associated URL was requested. Is this normal? Isn't there a way to just say &quot;serve all files in this directory&quot;?</p> </blockquote> <h2>Client-Server Communication</h2> <p>It quickly became clear that the standard way to send data from client to server is to create an <code>XMLHttpRequest</code> in Javascript, and send it using a <code>GET</code> or <code>POST</code> request. All my client-&gt;server communication was handled this way, except for submission of forms, since the form has a built-in mechanism to submit <code>GET</code> or <code>POST</code> requests.</p> <p>After looking at some examples, I settled on the following pattern, which was sufficient to achieve what I wanted. The client sent a request like so (Javascript):</p> <pre><code>xmlhttprequest.open(&quot;POST&quot;, &quot;test&quot;, true); xmlhttprequest.send(&quot;param=paramValue&amp;param2=paramValue2&quot;); </code></pre> <p>And the server could receive this with code like the below (Java):</p> <pre><code>httpServer.createContext( &quot;/test&quot;, new HttpHandler() { public void handle(HttpExchange aExchange) throws IOException { // get the text &quot;param=paramValue&amp;param2=paramValue2&quot; from aExchange.getResponseBody() // process it as required // send a response as text } } ); </code></pre> <p>The response text was then set to the <code>responseText</code> field of the <code>XMLHttpRequest</code>, and again could be processed as required. The response text was also sent as an <code>&amp;</code>-separated list of key-value pairs.</p> <p>What I found strange about this was that there was no hard requirement to use XML! I always got errors in the Javascript console that the response text was not well-formed XML, but this didn't break anything. But I assume there must be something I've missed that would mean I could avoid parsing the strings myself.</p> <blockquote> <p>Aren't there Javascript functions and Java methods for creating and reading tree-like or graph-like data structures, which can be written/read as XML under the hood, without the programmer needing to process the message content directly?</p> <p>Sometimes I found that the <code>XMLHttpRequest</code> wasn't sent successfully unless I added a 0.5s wait using <code>setTimeout</code>, before sending the request. I can do more testing and get more detail if necessary, but does anyone know what could be going on there?</p> </blockquote> <p>For communication server-&gt;client, without any initial request from the client, I didn't find a solution. So I settled on each client requesting the entire state of the game every half a second. Since the game state was very small (less than 1 kb in text form), this was sufficient.</p> <blockquote> <p>What's a better way for the server to send data to the client without any request from the client?</p> </blockquote> <h2>Dynamically Updating The Page</h2> <p>I found two ways to do this, and used both liberally:</p> <ol> <li>Update the <code>innerHTML</code> field of a document element</li> <li>Lots of hidden <code>div</code>s which could be unhidden as needed</li> </ol> <p>I came to prefer the second option, since the final HTML is easier to read - you can see everything that can potentially be displayed. In the future, I would only use the first option for content that isn't known at write-time.</p> <blockquote> <p>Are there any disadvantages to this approach?</p> </blockquote> <p>I can see that if I want to keep certain content initially hidden from users, I'd have to avoid this, as they could see it using <code>View Source</code>. But if they can read Javascript, they could also see anything I'm going to set to an <code>innerHTML</code> field using a script. So if I really wanted to keep it hidden, I guess I'd have to generate it server-side. Anyway, that wasn't a concern for this game.</p> <h2>Session Handling</h2> <p>I used a very simple solution which probably doesn't count as creating a true session. There is a single HTML page to load, and the server dynamically modifies it by inserting some code to set a cookie with the name-value pair <code>session=&lt;a randomly chosed UUID&gt;</code>. I found that each further request to the server automatically included this cookie, so I could keep track of identities.</p> <blockquote> <p>Is that all there is to it?</p> </blockquote> <h2>Putting it all together: Ctrl-F Oriented Programming</h2> <p>The below code snippets illustrate the pattern used throughout the application. They handle the <code>pass</code> function, in which a user gives up on getting their team to guess the current name, puts the name back in the hat, and draws another one. There's a button defined in HTML, a Javascript function which sends a request to the server to say that the user is passing on a given index in the list of names, a handler in the server to re-shuffle the names and return the new list to the client, and an inner function in the client to handle this response.</p> <p>The main problem I have with this pattern is that it uses a lot of &quot;Ctrl-F oriented programming&quot;. All the following strings need to be kept identical in multiple places, with no automatic check for errors, meaning I need to do a lot of manual checking of the files:</p> <ul> <li>The button ID <code>&quot;passButton&quot;</code></li> <li>The Javascript function name <code>&quot;pass&quot;</code></li> <li>The string <code>&quot;pass&quot;</code> used as the second arg to <code>XMLHttpRequest.open</code> and the string <code>&quot;/pass&quot;</code> used as the first arg to <code>HttpServer.createContext</code></li> <li>The parameter <code>&quot;passNameIndex&quot;</code> used in the <code>POST</code> request</li> <li>The parameter <code>&quot;nameList&quot;</code> used in the response to the <code>POST</code> request</li> </ul> <p>In such a small application, this isn't a major problem. In a larger one it would surely become a nightmare.</p> <blockquote> <p>Are there tools to handle this kind of problem? For example, ways to define tightly-coupled client and server code in the same file (e.g. if the server code was also written in Javascript)? Or ways to define such strings in a separate file used by both the server and the client, with a compile-time check that only pre-defined strings are used?</p> </blockquote> <p>Code snippets follow. HTML defines the button:</p> <pre><code>&lt;button id=&quot;passButton&quot; onclick=&quot;pass()&quot;&gt;Pass&lt;/button&gt; </code></pre> <p>Javascript sends the request and processes the response:</p> <pre><code>function pass() { document.getElementById(&quot;passButton&quot;).style.display = 'none' // hide button while processing the pass setTimeout( function() { // timeout mysteriously needed for request to work var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 &amp;&amp; this.status == 200) { document.getElementById(&quot;passButton&quot;).style.display = 'block' // restore button // The game maintains a shuffled list of celebrity names, which is modified in response to the pass. // Here we process the response by updating the client's shuffled name list to hold the list provided by the server var arr = toAssocArr(this.responseText) var nameListString = arr[&quot;nameList&quot;]; if ( nameListString != null ) { nameList = nameListString.split(&quot;,&quot;); updateCurrentNameDiv(); } } } // send request xhttp.onload = function() {} xhttp.open(&quot;POST&quot;, &quot;pass&quot;, true); xhttp.send(&quot;passNameIndex=&quot; + current_name_index); }, 500 ); } </code></pre> <p>Java processes the request and sends the response:</p> <pre><code>server.createContext( &quot;/pass&quot;, new HttpHandler() { @Override protected void handle(HttpExchange aExchange) throws IOException { // From cookie, get Session, then Player, then Game String sessionID = HttpExchangeUtil.getSessionID(aExchange); Session session = SessionManager.getSession(sessionID); if ( session != null ) { Player player = session.getPlayer(); Game game = player.getGame(); // Convert input string like &quot;passNameIndex=5&quot; to a LinkedHashMap LinkedHashMap&lt;String, String&gt; requestBody = HttpExchangeUtil.getRequestBodyAsMap(aExchange); String passNameIndexString = requestBody.get(&quot;passNameIndex&quot;); if ( passNameIndexString != null ) { // parse the provided passNameIndex, process it, and send the new shuffled name list as a response try { int passNameIndex = Integer.parseInt(passNameIndexString); game.setPassOnNameIndex( passNameIndex ); sendResponse(aExchange, HTTPResponseConstants.OK, &quot;nameList=&quot; + String.join(&quot;,&quot;, game.getShuffledNameList())); } catch ( NumberFormatException e ) { e.printStackTrace(); } } } // No error handling for if session/player/game isn't found, can deal with that later } } ); </code></pre> <p>As I said, essentially the whole application followed this pattern. My main questions are:</p> <ol> <li>For experienced web developers with a similar goal (i.e. something quick 'n' dirty which just manages to work), what would you have done similarly or differently?</li> <li>If you were aiming for something bigger, like a long-term project which would scale to a large number of users, and with new features continually being added, what would you have done differently?</li> </ol> <h2>Miscellaneous Questions</h2> <blockquote> <p>If I go bigger on my next project, what security issues do I need to consider? As far as I can see, there's no possibility of code injection via the HTML forms, because the input is encoded by default, but have I missed something?</p> </blockquote> <p>The complete code is on <a href="https://github.com/merman25/Celebrity" rel="nofollow noreferrer">github</a>. To answer the misc question, you probably just need to check the headers and forms in <a href="https://github.com/merman25/Celebrity/blob/master/client/celebrity.html" rel="nofollow noreferrer">celebrity.html</a>.</p>
[]
[ { "body": "<p>Welcome to Code Review. Here some suggestions for you :</p>\n\n<blockquote>\n<pre><code>LinkedHashMap&lt;String, String&gt; requestBody = HttpExchangeUtil.getRequestBodyAsMap(aExchange);\n</code></pre>\n</blockquote>\n\n<p>Declare <code>requestBody</code> as <code>Map</code>, if you can choose always the most generic interface.</p>\n\n<blockquote>\n<pre><code>try { //send your response \n} \ncatch (NumberFormatException e) { \n e.printStackTrace();\n}\n</code></pre>\n</blockquote>\n\n<p>Usually requests are logged using for example <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html\" rel=\"nofollow noreferrer\">Logger</a> saving them in a log file, so you can proceed with exam of requests and see eventually what's gone wrong.</p>\n\n<p>It seems me from your code you have already clear the main concepts about web programming like sessions, these are my personal answers to your questions based on my experience:</p>\n\n<blockquote>\n <p>For experienced web developers with a similar goal (i.e. something\n quick 'n' dirty which just manages to work), what would you have done\n similarly or differently?</p>\n</blockquote>\n\n<p>Normally web java projects are based on existing complex frameworks, for me the best option is always rely on which framework is used for the project and model my service using just framework libraries if it is possible. What happens if your code work perfectly on your pc and not work within the framework?</p>\n\n<blockquote>\n <p>If you were aiming for something bigger, like a long-term project\n which would scale to a large number of users, and with new features\n continually being added, what would you have done differently?</p>\n</blockquote>\n\n<p>Almost the same answer before, check which one well known framework has the characteristics you are looking for and use it from the start, avoid if possible all security problems and let the framework does its job. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:56:13.987", "Id": "471926", "Score": "0", "body": "Thanks for looking at it. My personal preference when using `LinkedHashMap` is to declare it as such, because there's typically a reason I've used it, and I want to remember that's what it is. In this case, I don't think I ended up iterating over it, and could change it to `HashMap` and indeed declare it as `Map`. I know about `Logger`, but for now haven't bothered with it, since at the moment this server only runs when I or others want to play a game, and then I'm sitting in front of it watching the console" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:59:35.360", "Id": "471929", "Score": "0", "body": "About frameworks, I'm not sure they're appropriate for such a simple project? Unless you count the Java `com.sun.net.httpserver` package as a framework. It would be more information to learn, and the benefit isn't clear to me. Do you have a framework you can suggest for simple type-and-click multiplayer games?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T07:50:41.360", "Id": "471992", "Score": "0", "body": "@OpenSauce, I understand your point of view, for learning concepts on web applications like sessions, cookies, etc. you started form java std classes and it seems you have a clear idea about these concepts. About frameworks like for example [spring](https://spring.io/) , I wanted to tell you that in complex projects you will work on well known frameworks so you will never start from scratch like your project." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:05:59.327", "Id": "471996", "Score": "0", "body": "@OpenSauce Keep in mind that if possible it is always better write less code using already made libraries and your game is based on html + javascript pages and java code , so you can take a look to the spring tutorials which one can match better your game." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T10:15:36.910", "Id": "240549", "ParentId": "240492", "Score": "1" } }, { "body": "<blockquote>\n <p>Aren't there Javascript functions and Java methods for creating and reading tree-like or graph-like data structures, which can be written/read as XML under the hood, without the programmer needing to process the message content directly?</p>\n</blockquote>\n\n<p>When communicating between the client and server, the de-facto standard format to use for data structures is <a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON\" rel=\"nofollow noreferrer\">JSON</a>. It's much more concise than XML, is easily parseable (on both ends), and is easily created from an object (on both ends). That is, on the client-side, rather than</p>\n\n<pre><code>game_arr = toAssocArr(this.responseText)\n</code></pre>\n\n<p>You'd like to be able to do</p>\n\n<pre><code>game_arr = JSON.parse(this.responseText);\n</code></pre>\n\n<p>You'd also like the sent response to contain the data <em>as you want it</em>, without requiring further Javascript processing. For example, you wouldn't want to have to do</p>\n\n<pre><code>var nameListString = game_arr[\"nameList\"]\nif ( nameListString != null ) {\n nameList = nameListString.split(\",\")\n}\n</code></pre>\n\n<p>Preferably, the <code>nameList</code> property would <em>already</em> be an array of strings after you <code>JSON.parse</code> it, rather than a string you have to split later. On the Java side of things, there are <a href=\"https://stackoverflow.com/questions/8876089/how-to-fluently-build-json-in-java\">various ways</a> to build the JSON that is required. Once it's built, just call <code>sendResponse</code> with the JSON string, and the <code>JSON.parse</code> on the client-side will transform it into a Javascript object.</p>\n\n<p>If you want your script to use modern web standards, consider using the <a href=\"https://developer.mozilla.org/en/docs/Web/API/Fetch_API\" rel=\"nofollow noreferrer\">Fetch API</a> instead of XMLHttpRequest. <code>fetch</code> is a lot more concise, and uses Promises, which are usually a lot easier to work with than callbacks, especially when you have multiple asynchronous actions. For example, rather than</p>\n\n<pre><code>function updateGameState(gameID) {\n var xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 &amp;&amp; this.status == 200) {\n game_arr = toAssocArr(this.responseText)\n // 150 more lines of code\n }\n }\n\n xhttp.open(\"POST\", \"requestGameState\", true);\n xhttp.send(\"gameID=\" + gameID);\n}\n</code></pre>\n\n<p>you could use</p>\n\n<pre><code>function updateGameState(gameID) {\n fetch('requestGameState', { method: 'POST', body: 'gameID=' + gameID });\n .then(res =&gt; res.json()) // this will automatically call JSON.parse\n .then((result) =&gt; {\n gameArr = result;\n // more code here\n })\n .catch((err) =&gt; {\n // don't forget to handle network/server errors here!\n // better to gracefully degrade than to fail silently\n });\n</code></pre>\n\n<p>The <code>// 150 more lines of code</code> is a bit smelly - consider splitting it up into separate functions. Consider implementing the <a href=\"https://stackify.com/solid-design-principles/\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>. For a reasonably-sized script (more than 200 lines of code or so), I highly recommend using modules instead - this allows you to split up hundreds of lines of code into smaller self-contained script files, which make things a <em>lot</em> easier to understand once you're past the initial hurdle of figuring out how they work.</p>\n\n<p>(like always, if you want ancient obsolete browsers to be able to run your code as well, use a <a href=\"https://github.com/github/fetch\" rel=\"nofollow noreferrer\">polyfill</a>)</p>\n\n<blockquote>\n <p>What's a better way for the server to send data to the client without any request from the client?</p>\n</blockquote>\n\n<p>You could use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API\" rel=\"nofollow noreferrer\">websockets</a> instead, which allow for the server to communicate to the client whenever the server wishes, after the client has made an initial request. On the client-side, this could look like:</p>\n\n<pre><code>const socket = new WebSocket('gamestate');\nsocket.addEventListener('message', (event) =&gt; {\n // process event.data, assign to gameArr\n});\n</code></pre>\n\n<p>Note that your <code>gameArr</code> (or <code>game_arr</code>) <em>isn't actually an array</em> - it's a plain object. An array is an ordered collection of values. An object is a collection of <em>key-value</em> pairs, which is what you're working with. A less misleading variable name might be <code>gameState</code>.</p>\n\n<p>By far, the most common variable naming convention used in Javascript is camelCase for nearly everything (except <code>class</code>es). You're using both camelCase and snake_case in your script; you might consider deciding on <em>one</em> convention, and then sticking to it. Once you have a standard, that's one less thing to have to keep in mind while writing or debugging. You may also consider using a <a href=\"http://eslint.org/\" rel=\"nofollow noreferrer\">linter</a> to enforce code styles - not only for variable names, but for other problems which are likely to lead to bugs and harder-to-read code (such as missing semicolons, using bracket notation <code>obj[\"prop\"]</code> instead of dot notation <code>obj.prop</code>, using loose equality comparison <code>==</code> instead of strict equality comparison <code>===</code>, etc. There are a <em>large amount</em> of potential improvements that could be made on these fronts.)</p>\n\n<p>Regarding control-F programming:</p>\n\n<p>I wouldn't worry too much about having to make sure the <code>nameList</code> property being parsed in JS matches the property sent in Java. You need <em>some</em> sort of API standard regardless; it's not a code smell, there's no other choice, given that the client and server are completely separate mediums.</p>\n\n<blockquote>\n <p>The button ID \"passButton\"</p>\n</blockquote>\n\n<p>In order to not repeat it more than necessary, save it in a variable, then reference that variable instead of selecting the element again. You could also consider not using IDs at all - they create global variables, which can result in bugs. Consider using classes instead. For example, if the button has a <code>passButton</code> class:</p>\n\n<pre><code>const passButton = document.querySelector('.passButton');\npassButton.style.display = 'none';\n// later, reference passButton instead of calling document.querySelector again\n</code></pre>\n\n<blockquote>\n <p>The Javascript function name \"pass\"</p>\n</blockquote>\n\n<p>This <em>is</em> a problem, and only partially for the reason you said. Inline handlers <a href=\"https://stackoverflow.com/a/59539045\">have too many problems</a> to be worth using; they have a demented scope chain, require global pollution, and have quote escaping issues. Use <code>addEventListener</code> instead. Once you have a reference to the button with <code>querySelector</code>, you can do:</p>\n\n<pre><code>passButton.addEventListener('click', () =&gt; {\n // put all the code that used to be inside the \"pass\" function here\n});\n</code></pre>\n\n<p>(and, of course, remove the <code>onclick=\"pass()\"</code> from the HTML. Best to do the same for all your other inline handlers, you have many of them.)</p>\n\n<blockquote>\n <p>The parameter \"passNameIndex\" used in the POST request</p>\n</blockquote>\n\n<p>Since the name of the endpoint already indicates what the value being sent is, why not just send the plain value?</p>\n\n<pre><code>xhttp.send(current_name_index);\n</code></pre>\n\n<p>(or the equivalent with <code>fetch</code>)</p>\n\n<p>Then, on the Java side, rather than <code>getRequestBodyAsMap</code>, just extract the <em>plain request body</em> as a string, and you have the <code>passNameIndexString</code> variable that you need.</p>\n\n<blockquote>\n <p>what security issues do I need to consider?</p>\n</blockquote>\n\n<p>The biggest issue I saw was this pattern, present in a few places:</p>\n\n<pre><code>htmlTeamList += \"&lt;h3&gt;\" + teamName + \"&lt;/h3&gt;\\n\" + \"&lt;ul&gt;\\n\";\nfor ( var j=1; j&lt;teamNameArr.length; j++) {\n htmlTeamList += \"&lt;li&gt;\" + teamNameArr[j] + \"&lt;/li&gt;\\n\"\n}\n</code></pre>\n\n<p>Directly writing an HTML string by concatenating variables is a potential security hazard, unless you're absolutely certain that the input is trustworthy. Otherwise, it'll allow for arbitrary code execution, and user cookie information could be sent to a malicious actor. For example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const teamName = `&lt;img src onerror=\"alert('evil')\"&gt;`;\nconst teamNameArr = [];\n\nlet htmlTeamList = '';\nhtmlTeamList += \"&lt;h3&gt;\" + teamName + \"&lt;/h3&gt;\\n\" + \"&lt;ul&gt;\\n\";\nfor ( var j=1; j&lt;teamNameArr.length; j++) {\n htmlTeamList += \"&lt;li&gt;\" + teamNameArr[j] + \"&lt;/li&gt;\\n\"\n}\n\ndocument.querySelector('div').innerHTML = htmlTeamList;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I think it would be good to get into the habit of either never concatenating an HTML string with variables, or of always escaping strings first (though this can easily bite you if you happen to forget to do it). (To sanitize, remove the <code>&lt;</code> <code>&gt;</code> brackets from strings before inserting them)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T14:24:25.193", "Id": "471881", "Score": "0", "body": "+1 Lot of useful informations. I am a javascript beginner and probably mine is a dumb question, but Mozilla documentation can be considered as a standard de facto for javascript ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T14:30:14.810", "Id": "471883", "Score": "1", "body": "MDN is like a wiki for developers. Like wikis, it's usually pretty accurate, and its examples and stuff are usually pretty good. But it's very occasionally inaccurate - it's not authoritative. It's a great detailed reference site, I'd go there first when looking something up, but for *absolute proof* on why/how something works the way it does, look up the [official Ecmascript specification](https://tc39.es/ecma262/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T14:42:11.717", "Id": "471887", "Score": "0", "body": "Thank you for your explanation and your time, surely I will look up the specification you posted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:52:57.423", "Id": "471925", "Score": "0", "body": "Thanks a lot! Lots of great advice here, which I'll definitely implement. This is exactly what I was hoping for. I'll wait a bit before accepting, and see if anybody else has any input" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T12:19:39.247", "Id": "240556", "ParentId": "240492", "Score": "2" } } ]
{ "AcceptedAnswerId": "240556", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T10:25:17.157", "Id": "240492", "Score": "4", "Tags": [ "java", "javascript", "design-patterns", "http", "ajax" ], "Title": "Quickly throwing together a text-and-button-based client-server web game" }
240492
<p>As working on a little private programming challenge, I tried "<em>Rock Paper Scissors</em>" without arrays or if-statements. It works as intended, though, I am sure this can be done a little bit more optimized. Especially in the context of Math/Programming.</p> <p>What I try to achieve:</p> <ul> <li>Create 2 <em>Players</em>, one <em>Computer</em> one <em>Human</em>. </li> <li>They both can make a <em>Gesture</em> (<em>Rock, Paper or Scissors</em> at <em>Random</em> or to <em>Choose</em> for the <em>Human Player</em>). </li> <li>The value of each <em>Gesture</em> is calculated into a <em>Score</em> </li> <li>The calculated <em>Scores</em> are calculated into a <em>Winner</em> of the <em>Duel</em></li> </ul> <p>The <em>Players</em> are two classes that implement an abstract class. The <em>Winner</em> and <em>Gesture</em> are Enums with specified values</p> <p>The random Method just sets a random Gesture value for the player like:</p> <pre><code> public void Random() =&gt; _gesture = (Gesture)_random.Next(0, 3); </code></pre> <p>The score for a single Hand is created <strong>as if it were points on a circle</strong> at 0, 120 and 240 degrees <a href="https://i.stack.imgur.com/wsZ1P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wsZ1P.png" alt="sample"></a></p> <pre><code>((double)(_winner + 1) * 3 + (double)_gesture * 2) % 6 * Math.PI / 3; </code></pre> <p>The opposite hand is done the same, however, it starts at 180 degrees ( 180, 300, 60 degrees)</p> <p>I try to find the position of both hands on the circle and calculate that into a unique value that results in a winner.</p> <pre><code>(Winner)(Math.Round(Math.Sin(other.Score() - this.Score())) * -(int)_winner); </code></pre> <p>This all works nice, however I suppose that the latter both rules could be reduced.</p> <pre><code>double Score() =&gt; ((double)(_winner + 1) * 3 + (double)_gesture * 2) % 6 * Math.PI / 3; public Winner Duel(Player other) =&gt; (Winner)(Math.Round(Math.Sin(other.Score() - this.Score())) * -(int)_winner); </code></pre> <p><strong>Complete code:</strong></p> <pre><code>using System; namespace RockPaperScissors { public enum Winner { Draw = 0, Computer = -1, Human = 1 } public enum Gesture { Rock = 0, Paper = 1, Scissors = 2, } public abstract class Player { private static readonly Random _random = new Random(DateTime.Now.Millisecond); private readonly Winner _winner; protected Gesture _gesture; protected Player(Winner winner) { _winner = winner; } public Gesture Gesture =&gt; _gesture; public void Random() =&gt; _gesture = (Gesture)_random.Next(0, 3); double Score() =&gt; ((double)(_winner + 1) * 3 + (double)_gesture * 2) % 6 * Math.PI / 3; public Winner Duel(Player other) =&gt; (Winner)(Math.Round(Math.Sin(other.Score() - this.Score())) * -(int)_winner); } public class Computer : Player { public Computer() : base(Winner.Computer) { } } public class Human : Player { public Human() : base(Winner.Human) { } public void Choose(Gesture gesture) =&gt; _gesture = gesture; } class Program { static void Main(string[] args) { Computer computer = new Computer(); Human human = new Human(); for(int i = 0; i &lt; 10; i ++) { computer.Random(); human.Random(); Console.WriteLine($"Computer does {computer.Gesture}, Human does {human.Gesture}"); Console.WriteLine($"Winner = {computer.Duel(human)}"); Console.WriteLine($"Winner = {human.Duel(computer)}"); Console.ReadLine(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T13:41:14.113", "Id": "471781", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to ask a new question instead, although I'd recommend waiting at least 24 hours between questions. More answers may be coming in." } ]
[ { "body": "<p>This will do</p>\n\n<pre><code>int a = _random.Next(0, 3);\nint b = _random.Next(0, 3);\nint winner = (a - b + 4) % 3 - 1;\n</code></pre>\n\n<p>There is no need to subtract angles in radians or degrees as you can simply use integers. Technically <code>a - b</code> is sufficient to determine the winner and <code>+ 4 % 3 - 1</code> wraps it to the <code>-1/0/+1</code> interval.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T13:21:00.190", "Id": "471780", "Score": "0", "body": "So indeed, it becomes *public Winner Duel(Player other) => (Winner)((((int)Gesture - (int)other.Gesture + 4) % 3 - 1) * (int)_winner);* (I added a bit for the function working on both players)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T13:04:42.697", "Id": "240501", "ParentId": "240494", "Score": "3" } } ]
{ "AcceptedAnswerId": "240501", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T10:55:34.487", "Id": "240494", "Score": "3", "Tags": [ "c#", "performance", "mathematics" ], "Title": "Rock Paper Scissors without arrays and if-statements, how to reduce" }
240494
<h1>Problem</h1> <p>Perfect forwarding is known to be imperfect when it comes to list-initialization; I'll use <a href="https://en.cppreference.com/w/cpp/memory/construct_at" rel="nofollow noreferrer"><code>std::construct_at</code></a> as an example:</p> <pre><code>std::vector a(3, 9); // OK: [9, 9, 9] std::construct_at(p, 3, 9); // OK: [9, 9, 9] std::vector b{3, 9}; // OK: [3, 9] std::construct_at(p, {3, 9}); // error: can't deduce type from braced-init-list </code></pre> <p>Even for non-list-initialization, we have this problem:</p> <pre><code>using Data = std::tuple&lt;std::vector&lt;int&gt;, std::vector&lt;int&gt;&gt;; Data c{(3, 9), (3, 9)}; // oops: [[0; 9], [0; 9]] Data d{{3, 9}, {3, 9}}; // OK: [[3, 9], [3, 9]] </code></pre> <p>where <code>[0; 9]</code> means <code>[0, 0, 0, 0, 0, 0, 0, 0, 0]</code>. This problem can be worked around by explicitly creating the object, for movable types:</p> <pre><code>std::construct_at(p, std::vector{3, 9}); // OK: [9, 9, 9] Data e{std::vector(3, 9), std::vector(3, 9)}; // OK: [[9, 9, 9], [9, 9, 9]] </code></pre> <p>For non-movable types, this workaround does not work, because guaranteed copy elision does not apply to rvalue references. Moreover, moving is unacceptable even for some movable types (e.g., <code>std::array&lt;int, 100000&gt;</code>). (Not to mention the verbosity.)</p> <h1>Existing solutions</h1> <p>Different facilities of standard library addresses this problem in a number of ways:</p> <ul> <li><p><code>std::array</code> &mdash; uses aggregate initialization instead of perfect forwarding;</p></li> <li><p><code>std::optional</code> &amp; <code>std::variant</code> &mdash; have an overload for argument lists starting with an <code>std::initializer_list</code>.</p></li> </ul> <p>However, these solutions all have drawbacks:</p> <ul> <li><p>Aggregates can't have constructors;</p></li> <li><p>Having an overload for <code>std::initializer_list</code> doesn't scale (how about arguments preceding initializer list arguments), and aggregate initialization still doesn't work (until C++20).</p></li> </ul> <p>Other things (<code>std::tuple</code>, <code>std::construct_at</code>, etc.) completely ignore this problem, rendering themselves unusable with non-movable types ...</p> <h1>My solution</h1> <p>... well, actually, there's a way to work around the limitation of C++ not being able to forward prvalues &mdash; we can make wrappers that convert to the destination type, which enables us to do this:</p> <pre><code>std::construct_at(p, brace(3, 9)); // OK Data e{paren(3, 9), paren(3, 9)}; // OK </code></pre> <p>Apparently, this solution is not as elegant as a hypothetical <code>std::construct_at(p, {3, 9})</code>, but it has a valuable property &mdash; it works seamlessly with ordinary perfect forwarding and non-intrusively adapt to existing things! This solution also only works since C++17, because guaranteed copy elision is required.</p> <p>All the magic is powered by two surprisingly simple function templates <code>brace</code> and <code>paren</code>:</p> <p><strong>init_utils.hpp</strong></p> <pre><code>#ifndef INIT_UTILS_HPP_t0EeVIMqJL #define INIT_UTILS_HPP_t0EeVIMqJL #include &lt;tuple&gt; #include &lt;type_traits&gt; namespace init_utils::detail { template &lt;typename T, typename... Args&gt; class list_traits { template &lt;typename U = T&gt; static constexpr auto check(int) noexcept(noexcept(U{std::declval&lt;Args&gt;()...})) -&gt; decltype((void)U{std::declval&lt;Args&gt;()...}, std::true_type{}); static constexpr auto check(...) noexcept(false) -&gt; std::false_type; public: static constexpr bool constructible = decltype(check(0))::value; static constexpr bool nothrow = noexcept(check(0)); }; } namespace init_utils { template &lt;typename T, typename... Args&gt; struct is_list_constructible : std::bool_constant&lt;detail::list_traits&lt;T, Args...&gt;::constructible&gt; {}; template &lt;typename T, typename... Args&gt; inline constexpr bool is_list_constructible_v = is_list_constructible&lt;T, Args...&gt;::value; template &lt;typename T, typename... Args&gt; struct is_nothrow_list_constructible : std::bool_constant&lt;detail::list_traits&lt;T, Args...&gt;::nothrow&gt; {}; template &lt;typename T, typename... Args&gt; inline constexpr bool is_nothrow_list_constructible_v = is_nothrow_list_constructible&lt;T, Args...&gt;::value; template &lt;typename T, typename Tuple&gt; constexpr T list_make_from_tuple(Tuple&amp;&amp; tuple) { return std::apply( [](auto&amp;&amp;... args) -&gt; T { return T{std::forward&lt;decltype(args)&gt;(args)...}; }, std::forward&lt;Tuple&gt;(tuple) ); } template &lt;typename... Args&gt; class direct_init_args : std::tuple&lt;Args&amp;&amp;...&gt; { using Base = std::tuple&lt;Args&amp;&amp;...&gt;; public: using Base::Base; template &lt;typename T, std::enable_if_t&lt;std::is_constructible_v&lt;T, Args...&gt;, int&gt; = 0&gt; constexpr operator T() noexcept(std::is_nothrow_constructible_v&lt;T, Args...&gt;) { return std::make_from_tuple&lt;T&gt;(std::move(static_cast&lt;Base&amp;&gt;(*this))); } }; template &lt;typename... Args&gt; class list_init_args : std::tuple&lt;Args&amp;&amp;...&gt; { using Base = std::tuple&lt;Args&amp;&amp;...&gt;; public: using Base::Base; template &lt;typename T, std::enable_if_t&lt;is_list_constructible_v&lt;T, Args...&gt;, int&gt; = 0&gt; constexpr operator T() noexcept(is_nothrow_list_constructible_v&lt;T, Args...&gt;) { return list_make_from_tuple&lt;T&gt;(std::move(static_cast&lt;Base&amp;&gt;(*this))); } }; } namespace init_utils::wrappers { template &lt;typename... Args&gt; constexpr auto paren(Args&amp;&amp;... args) noexcept { return direct_init_args&lt;Args...&gt;(std::forward&lt;Args&gt;(args)...); } template &lt;typename... Args&gt; constexpr auto brace(Args&amp;&amp;... args) noexcept { return list_init_args&lt;Args...&gt;(std::forward&lt;Args&gt;(args)...); } } #endif </code></pre> <p>Usage example:</p> <pre><code>#include "init_utils.hpp" #include &lt;initializer_list&gt; #include &lt;iostream&gt; #include &lt;tuple&gt; // non-copyable, non-movable struct S { int value; S(int, int) : value{1} { } S(std::initializer_list&lt;int&gt;) : value{2} { } S(S&amp;&amp;) = delete; S&amp; operator=(S&amp;&amp;) = delete; }; int main() { using namespace init_utils::wrappers; std::tuple&lt;S, S&gt; tuple{paren(1, 2), brace(3, 4)}; std::cout &lt;&lt; std::get&lt;0&gt;(tuple).value &lt;&lt; ' ' &lt;&lt; std::get&lt;1&gt;(tuple).value &lt;&lt; '\n'; } </code></pre> <p>What do you think of this idea?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T11:07:37.480", "Id": "240495", "Score": "3", "Tags": [ "c++", "c++17", "template-meta-programming" ], "Title": "A wrapper for (perfect forwarding + initialization)" }
240495
<p>Right now I'm studying Java, and as a part of understanding arrays, I've implemented a Tic-Tac-Toe game based on two-dimensional array.</p> <p>Any suggestions/comments are much appreciated!</p> <p>Source code will be below, also available in <a href="https://github.com/burtsdenis/tictactoe" rel="noreferrer">GitHub repo</a>.</p> <p><strong>Main.java</strong></p> <pre><code>package TicTacToe; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int x = -1; int y = -1; System.out.print("Enter name for player №" + Player.playersCount + ": "); Player player1 = new Player(reader.readLine(), "X"); System.out.print("Enter name for player №" + Player.playersCount + ": "); Player player2 = new Player(reader.readLine(), "O"); TicTacToe game1 = new TicTacToe(3); game1.initializeGame(player1, player2); while (true) { try { if (x &lt; 0) { System.out.print("Enter x: "); x = Integer.parseInt(reader.readLine()); } if (y &lt; 0) { System.out.print("Enter y: "); y = Integer.parseInt(reader.readLine()); } } catch (NumberFormatException e) { System.out.println("Your input is incorrect, value must Integer!"); continue; } if (!game1.checkInput(x, y)) continue; if (!game1.turnAllowed(x, y)) { x = -1; y = -1; continue; } TicTacToe.turnNumber++; if (TicTacToe.turnNumber % 2 != 0) { if (game1.makeATurn(x, y, player1)) { System.out.println(player1.name + " wins!"); break; } } else { if (game1.makeATurn(x, y, player2)) { System.out.println(player2.name + " wins!"); break; } } x = -1; y = -1; } } } </code></pre> <p><strong>TicTacToe.java</strong></p> <pre><code>package TicTacToe; import org.jetbrains.annotations.NotNull; public class TicTacToe { static int turnNumber = 0; String[][] gamingBoard; public TicTacToe(int n) { gamingBoard = new String[n][n]; } void initializeGame(Player player1, Player player2) { for (int i = 0; i &lt; gamingBoard.length; i++) { for (int j = 0; j &lt; gamingBoard.length; j++) { gamingBoard[i][j] = "-"; } } printGameBoard(); } void printGameBoard() { for (int i = 0; i &lt; gamingBoard.length; i++) { for (int j = 0; j &lt; gamingBoard.length; j++) { System.out.print(gamingBoard[i][j]); } System.out.println(); } } boolean turnAllowed(int x, int y) { if (gamingBoard[x][y].equals("-")) { return true; } else { System.out.println("Choose another field!"); return false; } } boolean checkInput(int x, int y) { try { if (x &lt;= gamingBoard.length - 1 &amp;&amp; y &lt;= gamingBoard.length - 1) { return true; } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: " + e); } System.out.println("Your input is incorrect, values must be between 0 and 2"); return false; } boolean makeATurn(int x, int y, @NotNull Player player) { gamingBoard[x][y] = player.playingMark; printGameBoard(); boolean winner = false; for (int i = 0; i &lt; gamingBoard[i].length; i++) { if (!gamingBoard[x][i].equals(player.playingMark)) break; if (i == gamingBoard.length - 1) { winner = true; } } for (int i = 0; i &lt; gamingBoard.length; i++) { if (!gamingBoard[i][y].equals(player.playingMark)) break; if (i == gamingBoard.length - 1) { winner = true; } } if (x == y) { for (int i = 0; i &lt; gamingBoard.length; i++) { if (!gamingBoard[i][i].equals(player.playingMark)) break; if (i == gamingBoard.length - 1) { winner = true; } } } if (x + y == gamingBoard.length - 1) { for (int i = 0; i &lt; gamingBoard.length; i++) { if (!gamingBoard[i][(gamingBoard.length - 1) - i].equals(player.playingMark)) break; if (i == gamingBoard.length - 1) { winner = true; } } } return winner; } } </code></pre> <p><strong>Player.java</strong></p> <pre><code>package TicTacToe; public class Player { String name; String playingMark; static int playersCount = 0; public Player(String name, String playingMark) { playersCount++; this.name = name; this.playingMark = playingMark; } } </code></pre> <p>Thank you!</p>
[]
[ { "body": "<h3>Naming &amp; Readability</h3>\n\n<p>Choosen naming mostly conveys purpose (expressive) and follows conventions (camelCase).</p>\n\n<h3>Design &amp; Structure</h3>\n\n<p>Very good design for a learner:</p>\n\n<ul>\n<li><code>TicTacToe</code> represents a <em>game instance</em> currently playing\n\n<ul>\n<li>having a <code>board</code> (composition) recording current <em>board state</em></li>\n<li>initializes game (<em>registering</em> 2 players, <em>resetting</em> board)</li>\n<li>checks for allowed moves (target field on board and not occupied)</li>\n<li>executes a player's turn and <em>evaluates</em> if turning player is a winner (horizontal, vertical, if indicated both diagonals in a row)</li>\n</ul></li>\n<li><code>Player</code> represents one player (of minimum required 2), including his mark</li>\n</ul>\n\n<p>Improvements:</p>\n\n<ul>\n<li>apply <strong>information hiding</strong>: public getters and setters allow access and modification of private member variables (take advantage of <em>Lombok</em>)</li>\n<li>UI invades gaming-logic! What about a separate <code>TicTacToeUI</code> class that is responsible for input (player name, moves) and output (render board, show winner), probably validation (check input). This concept is called <strong>Separation of Concerns</strong> (similarly also applied as <strong>MVC</strong>).\nBeneficial for a later extension, e.g from text-based input (TUI) towards graphical (GUI) or web-based using a REST interface.</li>\n<li><strong>Encapsulate round-based iteration</strong> inside the game class. So <code>main</code> is just responsible for initiating and starting the game (additionally stopping, if an exit-handler may be implemented allowing a long game to be aborted). That is what the <strong>Single Responsibility Principal</strong> (SRP) suggests.</li>\n<li>split long methods like <code>makeATurn</code>: one <code>moveTo(player, x,y)</code> another <code>boolean hasWon(player, x, y)</code> which calls <code>evaluateHorizontal</code>, etc. (SRP) in order to check the rows separately.</li>\n</ul>\n\n<h3>Stability &amp; Technical Improvement</h3>\n\n<ul>\n<li><code>ArrayIndexOutOfBoundsException</code> is not thrown in <code>checkInput</code>. Although it does not check for negative index values (which have a special meaning for the game-loop!)</li>\n<li><strong>magic numbers</strong> like <code>-1</code> should be defined as <em>constant</em> to express purpose in their name</li>\n<li>although a class-variable like <code>static int playerCount</code> is possible (Beware: counts players of <em>all game instances</em>!), what's the purpose?</li>\n<li><code>turnNumber</code> should not be static, but initialized within constructor</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:14:14.507", "Id": "471809", "Score": "0", "body": "Thank you so much for detailed answer!\nI'll continue to improve my code following your recommendations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:18:30.333", "Id": "471812", "Score": "1", "body": "_Continue_ marks a favourable attitude! I will also improve my answer, if I have refinements to add." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:35:11.647", "Id": "240508", "ParentId": "240500", "Score": "4" } } ]
{ "AcceptedAnswerId": "240508", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T12:59:40.077", "Id": "240500", "Score": "6", "Tags": [ "java", "tic-tac-toe" ], "Title": "TicTacToe implementation in Java" }
240500
<p>I have a dark theme toggle switch for my React component that works well, but I know the code could use some work. First I am checking to see what the users' preferences are for light/dark. Then I am setting in local storage what the user has chosen as a preference and then also checking for that value. I'm still learning and would like some feedback.</p> <p>My requirements:</p> <ol> <li><p>Needs to check the users' system preference for light/dark</p></li> <li><p>Needs to persistently keep users light/dark preference throughout the site</p></li> <li><p>Add class dark to the body tag in order to active all the CSS changes</p></li> </ol> <pre><code>import React, { Component } from "react"; class LightDarkToggle extends React.Component { componentDidMount() { let bodyClassList = document.body.classList; let themeSwitch = document.getElementById('switch-style'); //Here we are checking the USERS' device settings for dark theme if(window.matchMedia('(prefers-color-scheme: dark)').matches) { bodyClassList.add('dark'); themeSwitch.checked = true; } else if(window.matchMedia('(prefers-color-scheme: light)').matches) { bodyClassList.remove('dark'); themeSwitch.checked = false; } //Persisting USERS' theme preference by checking the local storage we set if(window.localStorage.getItem('theme') === 'dark') { bodyClassList.add('dark'); themeSwitch.checked = true; } else if(window.localStorage.getItem('theme') === 'light') { bodyClassList.remove('dark'); themeSwitch.checked = false; } } handleClick() { document.body.classList.toggle('dark'); if(document.getElementById('switch-style').checked === true){ window.localStorage.setItem('theme', 'dark'); } else if (document.getElementById('switch-style').checked === false){ window.localStorage.setItem('theme', 'light'); } } render() { return ( &lt;div className="toggle-mode"&gt; &lt;div className="icon"&gt; &lt;i className="fa fa-sun-o" aria-hidden="true"&gt;&lt;/i&gt; &lt;/div&gt; &lt;div className="toggle-switch"&gt; &lt;label className="switch"&gt; &lt;input type="checkbox" id="switch-style" onClick={this.handleClick} /&gt; &lt;div className="slider round" id="lightDarkToggle"&gt;&lt;/div&gt; &lt;/label&gt; &lt;/div&gt; &lt;div className="icon"&gt; &lt;i className="fa fa-moon-o" aria-hidden="true"&gt;&lt;/i&gt; &lt;/div&gt; &lt;/div&gt; ); } } export default LightDarkToggle; <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Here are some suggestions:</p>\n<h3><code>handleClick</code> method</h3>\n<p>Intead of calling <code>document.getElementById</code> and checking for <code>.checked</code> twice, you can store it's value into a constant like this:</p>\n<pre><code>const isDarkMode = document.getElementById(&quot;switch-style&quot;).checked;\n</code></pre>\n<p>then just do <code>window.localStorage.setItem(&quot;theme&quot;, isDarkMode ? &quot;dark&quot; : &quot;light&quot;);</code></p>\n<p>After these changes, the method will look like this:</p>\n<pre><code>handleClick() {\n document.body.classList.toggle(&quot;dark&quot;);\n const isDarkMode = document.getElementById(&quot;switch-style&quot;).checked;\n window.localStorage.setItem(&quot;theme&quot;, isDarkMode ? &quot;dark&quot; : &quot;light&quot;);\n}\n</code></pre>\n<h3><code>componentDidMount</code> method</h3>\n<p>This code can be simplified</p>\n<pre><code>if (window.localStorage.getItem(&quot;theme&quot;) === &quot;dark&quot;) {\n bodyClassList.add(&quot;dark&quot;);\n themeSwitch.checked = true;\n} else if (window.localStorage.getItem(&quot;theme&quot;) === &quot;light&quot;) {\n bodyClassList.remove(&quot;dark&quot;);\n themeSwitch.checked = false;\n}\n</code></pre>\n<p>You could make use of <code>toggle</code> method's second parameter, which is a boolean value that forces the class to be added or removed, regardless of whether or not it already existed.</p>\n<p>So that code could be changed to</p>\n<pre><code>const mustUseDarkMode = window.localStorage.getItem(&quot;theme&quot;) === &quot;dark&quot;; \nbodyClassList.toggle(&quot;dark&quot;, mustUseDarkMode);\nthemeSwitch.checked = mustUseDarkMode;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T07:11:34.313", "Id": "240544", "ParentId": "240507", "Score": "1" } } ]
{ "AcceptedAnswerId": "240544", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:27:45.810", "Id": "240507", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "A light/dark theme toggle react component" }
240507
<p>I have written this code for <code>bellman-ford</code> algorithm. Please review and suggest improvements: This code takes input graph as an adjacency matrix, and stores it the same way with additional info as a graph object. It then finds the shortest path to all vertices from the vertex at location [0][0] in the adjacency matrix. I still haven't been able to figure out an efficient way to detect negative weight cycle and am open for suggestions.</p> <pre><code>struct Node { long id; Node() { } explicit Node(long node_id) : id(node_id) { } bool operator==(const Node&amp; node) { return this-&gt;id == node.id; } }; class Graph { struct Edge { Node start; Node end; long length; explicit Edge(Node n1, Node n2, long len = 0) : start(n1), end(n2), length(len) { } bool operator==(const Edge&amp; node) { return ((this-&gt;start.id == node.start.id) &amp;&amp; (this-&gt;end.id == node.end.id)); } }; std::vector&lt;std::vector&lt;int&gt;&gt; matrix; std::list&lt;Node&gt; node_list; std::list&lt;Edge&gt; edge_list; unsigned long count; void createGraph() { std::cout &lt;&lt; "Enter the number of Nodes: "; std::cin &gt;&gt; count; for (int i = 0; i &lt; count; i++) { std::vector&lt;int&gt; v; node_list.push_back(Node(i + 1)); for (int j = 0; j &lt; count; j++) { long temp; std::cin &gt;&gt; temp; v.push_back(temp); } matrix.push_back(v); } } void createGraph(const int** adj_matrix) { for (unsigned long long i = 0; i &lt; *(&amp;adj_matrix + 1) - adj_matrix; i++) { std::vector&lt;int&gt; vec; node_list.push_back(Node(i + 1)); for (unsigned long long j = 0; j &lt; *(&amp;adj_matrix + 1) - adj_matrix; j++) { int temp = 0; std::cin &gt;&gt; temp; vec.push_back(temp); } matrix.push_back(vec); } } void createGraph(const std::vector&lt;std::vector&lt;int&gt;&gt;&amp; graph) { int i = 0; for (const auto&amp; node : graph) { node_list.push_back(Node(i + 1)); i++; std::vector&lt;int&gt; vec; for (const auto&amp; neighbour : node) { vec.push_back(neighbour); } matrix.push_back(vec); } } void addEdges() { for (int i = 0; i &lt; matrix.size(); i++) { for (int j = 0; j &lt; matrix[i].size(); j++) { if (matrix[i][j]) { Node start(i + 1); Node end(j + 1); edge_list.push_back(Edge(start, end, matrix[i][j])); } } } } public: Graph() { createGraph(); addEdges(); } explicit Graph(const int** adj_mat) { createGraph(adj_mat); count = matrix.size(); addEdges(); } explicit Graph(const std::vector&lt;std::vector&lt;int&gt;&gt;&amp; graph) { createGraph(graph); count = matrix.size(); addEdges(); } inline std::list&lt;Node&gt; getNodes() { return node_list; } long edgeLength(const Node&amp; node1, const Node&amp; node2) { for (const auto&amp; edge : edge_list) { if (edge.start.id == node1.id &amp;&amp; edge.end.id == node2.id) { return edge.length; } } return 0; } bool edgeExists(const Node&amp; node1, const Node&amp; node2) { if (std::find(edge_list.begin(), edge_list.end(), Edge(node1, node2)) == edge_list.end()) { return false; } return true; } void printGraph() { for (const auto&amp; row : matrix) { for (const auto&amp; elem : row) { std::cout &lt;&lt; elem &lt;&lt; " "; } std::cout &lt;&lt; "\n"; } } }; std::vector&lt;std::pair&lt;Node, long&gt;&gt; bellman_ford(Graph gr) { std::list&lt;Node&gt; v_list = gr.getNodes(); std::vector&lt;long&gt; node_distance(v_list.size()); std::fill(node_distance.begin() + 1, node_distance.end(), std::numeric_limits&lt;long&gt;::max()); for (int i = 0; i &lt; v_list.size() - 1; i++) { for (auto&amp; u : v_list) { for (auto&amp; v : v_list) { if (gr.edgeExists(u, v)) { if (node_distance[v.id - 1] == std::numeric_limits&lt;long&gt;::max()) { node_distance[v.id - 1] = node_distance[u.id - 1] + gr.edgeLength(u, v); } else if (node_distance[v.id - 1] &gt; node_distance[u.id - 1] + gr.edgeLength(u, v)) { node_distance[v.id - 1] = node_distance[u.id - 1] + gr.edgeLength(u, v); } } } } } std::vector&lt;std::pair&lt;Node, long&gt;&gt; shortest_distance(v_list.size()); auto list_it = v_list.begin(); auto dist_it = node_distance.begin(); for (auto&amp; pair : shortest_distance) { pair.first.id = list_it-&gt;id; pair.second = *dist_it; std::advance(list_it, 1); std::advance(dist_it, 1); } return shortest_distance; } </code></pre>
[]
[ { "body": "<h2>Const operators</h2>\n\n<pre><code>bool operator==(const Node&amp; node) {\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>bool operator==(const Node&amp; node) const {\n</code></pre>\n\n<p>Likewise for <code>long edgeLength(const Node&amp; node1, const Node&amp; node2)</code>, <code>edgeExists</code>, <code>printGraph</code>, etc.</p>\n\n<h2>Construction</h2>\n\n<p>This function:</p>\n\n<pre><code>void createGraph() {\n std::cout &lt;&lt; \"Enter the number of Nodes: \";\n std::cin &gt;&gt; count;\n for (int i = 0; i &lt; count; i++) {\n std::vector&lt;int&gt; v;\n node_list.push_back(Node(i + 1));\n for (int j = 0; j &lt; count; j++) {\n long temp;\n std::cin &gt;&gt; temp;\n v.push_back(temp);\n }\n matrix.push_back(v);\n }\n}\n</code></pre>\n\n<p>is mostly code that belongs in a constructor. The constructor in this case would accept an <code>istream&amp;</code> and would not <code>cout</code>; that could be done by the caller. The advantage of this approach is that</p>\n\n<ol>\n<li>it is more flexible - you could deserialize from a file, for example;</li>\n<li>it is more decoupled.</li>\n</ol>\n\n<p>I realize that <code>createGraph</code> is a private which is called by the existing constructor, which is fine; but I would stop short of baking in <code>cout</code>/<code>cin</code>.</p>\n\n<h2>Pointer madness</h2>\n\n<p>This:</p>\n\n<pre><code>*(&amp;adj_matrix + 1)\n</code></pre>\n\n<p>will not do what you want. Have you tried executing this method? Based on the <a href=\"https://www.geeksforgeeks.org/how-to-find-size-of-array-in-cc-without-using-sizeof-operator/\" rel=\"nofollow noreferrer\">link you gave me</a>, it seems you were attempting to do a hack that requires that you have a reference to an array with defined size, but you do not - you only have bare pointers. </p>\n\n<p>Just pass in integral matrix dimensions.</p>\n\n<h2>Boolean expressions</h2>\n\n<pre><code> if (std::find(edge_list.begin(), edge_list.end(), Edge(node1, node2)) == edge_list.end()) {\n return false;\n }\n return true;\n</code></pre>\n\n<p>can be</p>\n\n<pre><code> return std::find(edge_list.begin(), edge_list.end(), Edge(node1, node2)) != edge_list.end();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:56:22.790", "Id": "471803", "Score": "0", "body": "Thanks for the answer. Please take a look at https://www.geeksforgeeks.org/how-to-find-size-of-array-in-cc-without-using-sizeof-operator/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:58:10.630", "Id": "471804", "Score": "0", "body": "adding const after paranthesis? Is that different from adding one behind paranthesis? I have never seen this syntax. How is it used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:59:47.380", "Id": "471806", "Score": "0", "body": "Re. the pointer-hack sizing - that only works if you have a reference to the sized array, which you do not. You have a pointer which - in your method's scope - has no idea how big that array is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:01:50.533", "Id": "471807", "Score": "0", "body": "By `sized array`, did you mean `std::array`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:07:49.917", "Id": "471808", "Score": "0", "body": "Whatever you're passing to the `Graph()` constructor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:17:42.767", "Id": "471810", "Score": "0", "body": "re. \"const after parentheses\", it means that the method promises not to modify any member variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:20:56.337", "Id": "471813", "Score": "0", "body": "But then doesn't inclusion of const in parameter field take care of that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:24:57.303", "Id": "471814", "Score": "0", "body": "Yeah right got it. https://stackoverflow.com/questions/751681/meaning-of-const-last-in-a-function-declaration-of-a-class" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T13:35:11.387", "Id": "471876", "Score": "0", "body": "I have no idea why this has been down-voted. A comment would have helped." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:54:16.693", "Id": "240511", "ParentId": "240509", "Score": "0" } }, { "body": "<p><strong>Node struct</strong></p>\n\n<ol>\n<li>Node attribute id is public so it can be changed after node has been created. Is it a supported scenario? id should be private attribute.</li>\n<li>Operator overload for == should be const. Equality check can't change object state.</li>\n</ol>\n\n<p><strong>Graph class</strong></p>\n\n<ol start=\"3\">\n<li><p>Node lifetime management: More than one copy of same node is in memory. Graph is keeping list of node and then edge is keeping separate copy as start and end node. One possibility is let Graph manage node lifetime and edges can work with reference/pointers. There are other models possible to avoid multiple copies of nodes in memory.</p></li>\n<li><p>Start and end of edge are public members. Either make them private or if you want to support case where edge can change endpoint post creation, provide start/end node setters and update adjacency accordingly. Cleaner solution will to make edge immutable with respect to end nodes.</p></li>\n<li><p>Edge == operator should be marked const</p></li>\n<li><p>Graph construction: There can be two approaches for graph construction. First, incremental mode. Create an empty graph and the go through sequence of addnode and addedge (In many cases only addedge might be sufficient) to reach desired adjacency. Second, bulk mode. Nodes and edges are read from some structured stream desired adjacency is created. In this case graph constructor (or actually loader, because it is loading existing graph from stream into memory) should take structured stream as input. Doing cin/out based I/O in construction is not good design.</p></li>\n<li><p>get_nodes is returning copy of list of nodes. It will be memory heavy operation. Any graph algorithm or traversal will call get_nodes multiple times, every time creating copy of all nodes s not good idea. get_nodes should get const reference of node list managed by graph. get_nodes should be marked const.</p></li>\n<li><p>edgeExist is iterating over all edges and trying to match start/end node. Better way will be iterate over source node adjacency and check for edge. Give edge also an id to make edge lookup faster. Edge lookup map will be handy as adjacency queries are very common in graph algorithms. One possibility is to keep edge id in adjacency structure(something like >)</p></li>\n<li><p>const auto&amp; in loops in BellmanFord for loops for nodes</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T12:59:54.707", "Id": "472278", "Score": "1", "body": "Thanks a lot for one of the most detailed and to the point answers . Will you please elaborate more on what other models you had in mind with reference to point #3" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:48:17.567", "Id": "240520", "ParentId": "240509", "Score": "3" } } ]
{ "AcceptedAnswerId": "240520", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T15:36:30.043", "Id": "240509", "Score": "4", "Tags": [ "c++", "graph", "pathfinding" ], "Title": "Bellman Ford algorithm using vector" }
240509
<p><code>findPairs</code> produces the Integer pairs so that the numbers from 1 to N and the pair of numbers have a sum less than 50 and have more than 3 common divisors.</p> <p>Could the complexity of this code be improved?</p> <pre><code>public class foo { static void findPairs(int N) { for (int i = 1; i &lt;= N; i++) { for (int j = 1; j &lt;= N; j++) { if (commDiv(i, j) &gt; 3 &amp;&amp; i + j &lt; 50) System.out.println(i + " , " + j); } } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int commDiv(int a, int b) { int n = gcd(a, b); int result = 0; for (int i = 1; i &lt;= Math.sqrt(n); i++) { if (n % i == 0) { if (n / i == i) result += 1; else result += 2; } } return result; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:43:43.557", "Id": "471815", "Score": "0", "body": "Class names like `foo` have a tendency to be marked as off-topic. We review working code from real projects on code review. Also, what does this code do. The title should indicate a very high level of what the code does, and there could possibly be a paragraph of text about what the code does as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T19:58:21.980", "Id": "471828", "Score": "0", "body": "@pacmaninbw I suspect, since in this case the class name is completely irrelevant, the name does not matter at all. Often with Java solutions for programming challenges, they're called Solution or some other name that nobody really cares about. Feel free to point it out in review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T19:59:08.800", "Id": "471829", "Score": "0", "body": "Although, having said that, this question is phrased like it's looking for alternative implementations instead of a review. But that's a phrasing problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T04:49:35.287", "Id": "471976", "Score": "0", "body": "Put an explicit statement in the code what it is to accomplish, including what is and isn't a *trivial* common divisor (a=b=30? a=12, b=24 *and* a=24, b=12?) . Take *produce pairs* literally instead of filtering. Don't consider pairs known not to be admissible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T05:06:06.130", "Id": "471977", "Score": "0", "body": "Sorry @greybeard. Can you explain \" Take produce pairs literally instead of filtering\" for me? I haven't got it. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T05:37:26.517", "Id": "471978", "Score": "0", "body": "Iterate eligible factors, produce their products." } ]
[ { "body": "<p>I have some suggestions.</p>\n\n<h2>Methods naming</h2>\n\n<p>Both methods <code>commDiv</code> &amp; <code>gcd</code> names don’t have any patterns. I suggest you rename them to something easier to guests like :</p>\n\n<ul>\n<li><code>findGreatestCommonDivisor</code> </li>\n<li><code>findCommonDivisor</code></li>\n</ul>\n\n<p>I suggest that you rename the method <code>findPairs</code> to <code>printPairs</code>.</p>\n\n<h2>Code conventions</h2>\n\n<ul>\n<li>A class name always starts with an uppercase.</li>\n<li>A parameter always starts with an lowercase. <code>(Foo#findPairs)</code></li>\n</ul>\n\n<h2>Code style</h2>\n\n<p>I suggest that you add the braces to the <code>if</code> and <code>else</code> blocks, since it can cause confusion and break the condition if you forget to put them when you add code to the block.</p>\n\n<h2>Flattening the <a href=\"https://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">arrow code</a></h2>\n\n<p>In the <code>commDiv</code> method, you can remove a level of indentation by inverting the first <code>if</code> condition.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 1; i &lt;= sqrt; i++) {\n if (n % i != 0) {\n continue;\n }\n //[...]\n}\n</code></pre>\n\n<h2>Code optimization</h2>\n\n<h3><code>commDiv</code> method</h3>\n\n<p>Move the <code>java.lang.Math#sqrt</code> of the <code>for</code> section, since it will be called before EACH iteration. \n<strong>Before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 1; i &lt;= Math.sqrt(n); i++) {\n //[...]\n}\n</code></pre>\n\n<p><strong>After</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>double sqrt = Math.sqrt(n);\nfor (int i = 1; i &lt;= sqrt; i++) {\n //[...]\n}\n</code></pre>\n\n<h2>Refactored code</h2>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Foo {\n\n static void findPairs(int n) {\n for (int i = 1; i &lt;= n; i++) {\n for (int j = 1; j &lt;= n; j++) {\n if (findCommonDivisor(i, j) &gt; 3 &amp;&amp; i + j &lt; 50) {\n System.out.println(i + \" , \" + j);\n }\n }\n }\n }\n\n static int findGreatestCommonDivisor(int a, int b) {\n if (a == 0) {\n return b;\n }\n\n return findGreatestCommonDivisor(b % a, a);\n }\n\n static int findCommonDivisor(int a, int b) {\n int n = findGreatestCommonDivisor(a, b);\n\n int result = 0;\n double sqrt = Math.sqrt(n);\n for (int i = 1; i &lt;= sqrt; i++) {\n if (n % i != 0) {\n continue;\n }\n\n if (n / i == i) {\n result += 1;\n } else {\n result += 2;\n }\n }\n return result;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T23:00:30.333", "Id": "240530", "ParentId": "240514", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T16:31:45.277", "Id": "240514", "Score": "-1", "Tags": [ "java", "algorithm", "programming-challenge" ], "Title": "Integer pairs with more than 3 common divisors" }
240514
<p>Can this logic not be simplified more, the code works, but it has become too much of a spaghetti. The requirements are that there should always be one connection if possible in <code>available</code> state, but I need to take all the <code>available</code> states down and re-create them. these paths I have to cover:</p> <ol> <li>if both vifs down, call create</li> <li>if both vifs available, take them down and up one-by-one</li> <li>if one down and one available, bring first up the down one, then take down and bring up the available one</li> <li>if only one down, get it up, then create the second one</li> <li>if only one up, create the second one, then delete and re-create the first one</li> </ol> <pre><code>var vifsMap = make(map[string][]*directconnect.VirtualInterface) var vifsStateAvailable, vifsStateDown []*directconnect.VirtualInterface for _, item := range convertToDirectconnect(lagPair, amz.dcLags) { vis, err := amz.dcRead.DescribeVirtualInterfaces(&amp;directconnect.DescribeVirtualInterfacesInput{ConnectionId: item.LagId}) if err != nil { return err } for _, vi := range vis.VirtualInterfaces { if *vi.OwnerAccount == cfg.RemoteAccountID { if aws.StringValue(vi.VirtualInterfaceState) == directconnect.VirtualInterfaceStateAvailable { vifsStateAvailable = append(vifsStateAvailable, vi) } else if aws.StringValue(vi.VirtualInterfaceState) == directconnect.VirtualInterfaceStateDown { vifsStateDown = append(vifsStateDown, vi) } } } } vifsMap["available"] = vifsStateAvailable vifsMap["down"] = vifsStateDown if len(vifsStateDown) &gt; 1 { fmt.Println("contains 2 down elements") } else if len(vifsStateAvailable) &gt; 1 { fmt.Println("contains 2 up elements") } else if len(vifsStateDown) == 1 &amp;&amp; len(vifsStateAvailable) == 1 { fmt.Println("contains 1 vif down and 1 up") } else if len(vifsStateAvailable) == 1 &amp;&amp; len(vifsStateDown) == 1 { fmt.Println("contains 1 vif up and 1 down") } else if len(vifsStateDown) == 1 &amp;&amp; len(vifsStateAvailable) == 0 { fmt.Println("contains 1 down only") } else if len(vifsStateAvailable) == 1 &amp;&amp; len(vifsStateDown) == 0 { fmt.Println("contains 1 up only") } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:22:38.180", "Id": "240517", "Score": "1", "Tags": [ "go", "hash-map" ], "Title": "Simplifying decision tree when working with map which has two keys and value as a slice" }
240517
<p>I'm not a very experience python programmer. But I want to make my code as fast and efficient as possible as well as write it clean and therefore got the advice to share it here. So I'm having the following code, which works well but isn't very fast as I have dirs bigger than 4TB and I'm executing that code in my network. So I'm looking for advice, to read out all data in one path instead of doing redundant second scanning of dirs and files. Any advice would be appreciated! I'm also thinking of how to implement multiprocessing but I think that wouldn't help much as a lot is IO.</p> <pre><code>def get_size_and_fcount_pathlib(scan_path): """Gets the total size of given dir and counts how many folders and files are in the given path directory and return a file count, folder count and all types as a sum""" root_directory = Path(scan_path) total_size = 0 all_types_count = 0 file_count = 0 folder_count = 0 for f in root_directory.glob('**/*'): if f.is_file(): file_count += 1 total_size += f.stat().st_size if not str(f.name).startswith("."): all_types_count += 1 if f.is_dir(): folder_count += 1 size_gb = ", ".join(map(str, (round(total_size/1000/1000/1000, 2), 'GB'))).replace(', ', '') print('Amount of all types searched: {}'.format(all_types_count)) print('Amount of files searched: {}'.format(file_count)) print('Amount of folders searched: {}'.format(folder_count)) print('Directory size in GB: {}'.format(size_gb)) file_count_collection = [size_gb, all_types_count, file_count, folder_count] return file_count_collection </code></pre>
[]
[ { "body": "<h1>Naming things</h1>\n\n<p>Be consistent in the way you name things. This applies to the words chosen, whether you abbreviate things or not, whether you separate multiple words or not. There are some names you are using that are not consistent. For example:</p>\n\n<pre><code>def get_size_and_fcount_pathlib(scan_path):\n</code></pre>\n\n<p>You start with fully spelled out words separated by underscores, and then suddenly there is <code>fcount</code>, two words without separators and with one word being abbreviated. I would start by writing this out consistently as:</p>\n\n<pre><code>def get_size_and_file_count_pathlib(scan_path):\n</code></pre>\n\n<p>If you want to reduce the size of the name, I would rather omit redundant parts of it. Is <code>pathlib</code> really adding anything to this? If <code>get_size_and_file_count()</code> gives you enough context to deduce what the function does, I would go for that.</p>\n\n<p>Another issue is with this variable:</p>\n\n<pre><code>file_count_collection = [size_gb, all_types_count, file_count, folder_count]\n</code></pre>\n\n<p>It says it is a file count collection, but it also contains the total size. I would change this to <code>size_and_file_count_collection</code>, to make it clear it also contains the size, and this also better matches the name of the function. Again, if you want to make it shorter, I would then drop <code>_collection</code> from the name, since <code>size_and_file_count</code> already implies it is more than one bit of information.</p>\n\n<p>Arguably, <code>size_and_file_count</code> is also not completely descriptive since it also includes directory count and a count of all types of filesystem entities.\nThere might be an even better name for this, perhaps <code>directory_statistics</code>?</p>\n\n<h1>Use a <code>class</code> to represent structured data</h1>\n\n<p>The <code>file_count_collection</code> is just a list. Unless you read the code of this function, it is not obvious in which order you stored the size and counts in this list. It is better to create a <code>class</code> that represents this collection of data, where each piece will get its own name, like so:</p>\n\n<pre><code>class size_and_file_count:\n def __init__(self, size_gb, all_types_count, file_count, folder_count):\n self.size_gb = size_gb\n self.all_types_count = all_types_count\n self.file_count = file_count\n self.folder_count = folder_count\n</code></pre>\n\n<p>Then, in <code>get_size_and_file_count()</code>, you can replace the last two lines with:</p>\n\n<pre><code>return size_and_file_count(size_gb, all_types_count, file_count, folder_count)\n</code></pre>\n\n<p>And in the code that calls that function, instead of writing:</p>\n\n<pre><code>result = get_size_and_file_count(\"...\")\nfile_count = result[2]\n</code></pre>\n\n<p>You can now write:</p>\n\n<pre><code>result = get_size_and_file_count(\"...\")\nfile_count = result.file_count\n</code></pre>\n\n<h1>Don't convert values too early</h1>\n\n<p>You are calculating the total size, and then converting it to a value in gigabytes (with only 2 decimals), and only storing that final result. What if I want to get the size of a directory that contains less than 10 megabytes of data? Your function will tell me it is 0.00 gigabytes big, which is not helpful. It is better to store the size in bytes, and only convert to gigabytes when printing the result, like so:</p>\n\n<pre><code>print('Directory size in GB: {:.2f} GB'.format(total_size / 1.0e9))\n</code></pre>\n\n<p>And of course also store the total size in bytes in the returned collection.</p>\n\n<h1>Separate obtaining results from printing results</h1>\n\n<p>Your function does two things at once: it calculates the results and it prints them. It is best to separate the two issues, and have <code>get_size_and_file_count()</code> only calculate the results and <code>return</code> them, and then have a seperate function that takes a <code>size_and_file_count</code> variables as a parameter and prints the values to the screen.</p>\n\n<p>If you have made a <code>class size_and_file_count</code>, you could make the function that prints the results a member function of that class.</p>\n\n<h1>What is <code>all_types_count</code>?</h1>\n\n<p>There are many different types of filesystem entries besides regular files and directories; there are fifos, sockets, symlinks, character devices and so on.\nI would expect a variable named <code>all_types_count</code> to count all of them. However, in your code you actually disregard all things that are neither regular file nor directory, and instead <code>all_types_count</code> just counts those regular files whose name does not start with <code>.</code>. So actually your <code>all_types_count</code> is just a <code>non_hidden_files_count</code>. Either this was your intention, in which case you should rename the variable, or you actually wanted to count all filesystem items, in which case your count is wrong.</p>\n\n<h1>Optimizing the code</h1>\n\n<p>If you want to make the code as fast as possible, there are several ways to do that. First, I would start by replacing the call to <code>glob()</code> with <code>os.walk()</code>. Since you want all files and directories anyway, the glob function is likely incurring an unnecessary overhead of comparing each item it finds against the glob pattern you gave. Also, <code>os.walk()</code> already splits the results for each directory in a list of file names and list of directory names, making your life a bit easier. It would look like:</p>\n\n<pre><code>for root, dirs, files in os.walk(root_directory):\n folder_count += len(dirs)\n for f in files:\n if Path(root, f).is_file():\n ...\n</code></pre>\n\n<p>If you want more speed, then there are two other ways to consider, that can even be combined. First, write the function in C, and make a Python wrapper function around the C code. Second, you could try to paralellize the code, for example by scanning multiple directories in parallel. However, the latter is a lot of work, and there is a good chance it will not be faster at all, since you might actually not be CPU bound but I/O bound, and even if you are CPU bound, then the overhead of spawning multiple threads or tasks and synchronizing them might be more than the performance gain from the actual parallel execution of the code.</p>\n\n<p>When you are interested in optimizing the code, start with <a href=\"https://stackoverflow.com/questions/1593019/is-there-any-simple-way-to-benchmark-python-script\">benchmarking</a> it, and then see if the suggestions actually help with performance. Also, before trying to parallelize the code, actually check if your Python code is actually using 100% CPU when scanning directories. If not, it's not worth going that route.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T10:52:56.833", "Id": "471859", "Score": "0", "body": "Thanks for everything. My currently adapted solution below." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T18:45:10.240", "Id": "240523", "ParentId": "240518", "Score": "2" } }, { "body": "<p>I'm speechless Sliepen, thanks for your well-crafted answer. This amount of support makes me love the community of programming even more.</p>\n\n<p><strong>My current state of things:</strong></p>\n\n<p><strong>About my namings:</strong>\nI used the name <code>fcount</code> as I wanted to have it stand for files and folders as otherwise, the name would be too long. That's why I made the exception to shorten it. I'm still continuing with your more experienced solution for this.\nI wrote <code>pathlib</code> into the function name because I have the same function above it with <code>os.walk</code> as this was my first way to try. But <code>os.walk</code> seem to have problems scanning my network drive as it always returned 0 bytes. Therefore I've chosen <code>pathlib</code>. Hope that makes sense.</p>\n\n<p><strong>About my classes:</strong> I'm starting to feel comfortable programming python but as soon as I start to use classes my whole code starts to fall apart and seems to have to be more complex. I know that's just a beginner problem, but as I usually can't solve the issues appearing, I'm careful with that route. I've now rewritten it into a class but facing a few problems now.\nI started to try to structure it as you did by writing the file search for-loop into the <code>__init__</code> function but python was then saying it cant return a value from <code>__init__</code> so I created a new method named <code>def get_directory_statistics(self, scan_path):</code>. \nI'm not sure where to input my <code>scan_path</code>, into the <code>__init__</code>or the first method <code>def get_directory_statistics(self, scan_path):</code>.\nYour advice to summarize two lines into one, sadly didn't work for me either <code>return size_and_file_count(size_gb, all_types_count, file_count, folder_count)</code>. I couldn't get it to work. It's always saying <code>size_and_file_count</code> is not defined or other Errors.</p>\n\n<p>Optimizing the code: I outlined above why I sadly can't use os.walk for this. So this won't work for me. And C seems at the moment, not like an option as the only programming language I am familiar with is python and I guess it would be a more complex task to program a wrapper and the code itself in <code>C</code>. I think most of it will be I/O bound, yes.</p>\n\n<p>Again I learned a lot from your answer!</p>\n\n<p><strong>Below you'll find my solution after going over all your notes but it's still not fully working.</strong> </p>\n\n<pre><code>class get_size_and_file_count:\n \"\"\"Gets the total size of a given dir and counts how many folders and files are in the given\n path directory and return a file count, folder count and all non hidden files as a sum\"\"\"\n def __init__(self, total_size = 0, non_hidden_files_count = 0, file_count = 0, folder_count = 0):\n self.total_size = total_size\n self.non_hidden_files_count = non_hidden_files_count\n self.file_count = file_count\n self.folder_count = folder_count\n\n def get_directory_statistics(self, scan_path):\n self.root_directory = Path(scan_path)\n for f in self.root_directory.glob('**/*'):\n if f.is_file():\n self.file_count += 1\n self.total_size += f.stat().st_size\n if not f.name.startswith(\".\"):\n self.non_hidden_files_count += 1\n if f.is_dir():\n self.folder_count += 1\n\n directory_statistics = [self.total_size, self.non_hidden_files_count, self.file_count, self.folder_count]\n return directory_statistics\n\n def print_directory_statistics(self):\n print('Directory path to search: {}'.format(self.root_directory))\n print('Directory size in GB: {:.2f}GB'.format(self.total_size / 1.0e9))\n print('Amount of non hidden files: {}'.format(self.non_hidden_files_count))\n print('Amount of files searched: {}'.format(self.file_count))\n print('Amount of folders searched: {}'.format(self.folder_count))\n\n\nresult = get_size_and_file_count()\nstart_process = result.get_directory_statistics(\"...\")\nprint_result = start_process.print_directory_statistics()\nprint(file_count)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:59:42.823", "Id": "471897", "Score": "1", "body": "Hi! It would be best if you create a new code review question for your revised code, so it can be reviewed just like your original code. Just post a link here in the comments to the new review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:55:42.053", "Id": "471904", "Score": "0", "body": "If you want to follow up, this topic got a new code review [link](https://codereview.stackexchange.com/questions/240574/run-directory-scan-as-class)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T10:51:51.180", "Id": "240551", "ParentId": "240518", "Score": "0" } } ]
{ "AcceptedAnswerId": "240523", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:23:30.723", "Id": "240518", "Score": "2", "Tags": [ "python", "search" ], "Title": "Run dir scan as fast and efficient as possible / clean code" }
240518
<p>I've created an application to predict emotions. But I think the application is being over fitted. And I cannot figure out how to solve the overfitting. I'm using a small data set of 107 images spread across 6 emotions.</p> <p>Train.py</p> <pre><code>#Adding Seed so that random initialization is consistent from numpy.random import seed seed(1) tf.set_random_seed(2) batch_size = 3 #Prepare input data classes = ['Anger','Disgust','Fear','Happy','Neutral','Sad','Surprise'] num_classes = len(classes) # 20% of the data will automatically be used for validation validation_size = 0.2 img_size = 128 num_channels = 3 train_path='C:\\Users\\Jack\\source\\repos\\Emotion Prediction\\Emotion Prediction\\training_images' # We shall load all the training and validation images and labels into memory using openCV and use that during training data = dataset.read_train_sets(train_path, img_size, classes, validation_size=validation_size) print("Complete reading input data. Will Now print a snippet of it") print("Number of files in Training-set:\t\t{}".format(len(data.train.labels))) print("Number of files in Validation-set:\t{}".format(len(data.valid.labels))) session = tf.Session() x = tf.placeholder(tf.float32, shape=[None, img_size,img_size,num_channels], name='x') ## labels y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true') y_true_cls = tf.argmax(y_true, dimension=1) ##Network graph params filter_size_conv1 = 3 num_filters_conv1 = 32 filter_size_conv2 = 3 num_filters_conv2 = 32 filter_size_conv3 = 3 num_filters_conv3 = 64 fc_layer_size = 128 def create_weights(shape): return tf.Variable(tf.truncated_normal(shape, stddev=0.05)) def create_biases(size): return tf.Variable(tf.constant(0.05, shape=[size])) def create_convolutional_layer(input, num_input_channels, conv_filter_size, num_filters): ## We shall define the weights that will be trained using create_weights function. weights = create_weights(shape=[conv_filter_size, conv_filter_size, num_input_channels, num_filters]) ## We create biases using the create_biases function. These are also trained. biases = create_biases(num_filters) ## Creating the convolutional layer layer = tf.nn.conv2d(input=input, filter=weights, strides=[1, 1, 1, 1], padding='SAME') layer += biases #gets input and weights. strides = filter moves 1 step in both x and y directions (width and height) ## We shall be using max-pooling. layer = tf.nn.max_pool(value=layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], #middle values define shape of max pooling in x and y directions, same with strides as this while down-sample and halve the input size padding='SAME') ## Output of pooling is fed to Relu which is the activation function for us. layer = tf.nn.relu(layer) return layer def create_flatten_layer(layer): #We know that the shape of the layer will be [batch_size img_size img_size num_channels] # But let's get it from the previous layer. layer_shape = layer.get_shape() ## Number of features will be img_height * img_width* num_channels. But we shall calculate it in place of hard-coding it. num_features = layer_shape[1:4].num_elements() ## Now, we Flatten the layer so we shall have to reshape to num_features layer = tf.reshape(layer, [-1, num_features]) return layer def create_fc_layer(input, num_inputs, num_outputs, use_relu=True): #Let's define trainable weights and biases. weights = create_weights(shape=[num_inputs, num_outputs]) biases = create_biases(num_outputs) # Fully connected layer takes input x and produces wx+b.Since, these are matrices, we use matmul function in Tensorflow layer = tf.matmul(input, weights) + biases #all_weights=[] #w=layer.get_weights() #all_weights.append(w) if use_relu: layer = tf.nn.relu(layer) return layer layer_conv1 = create_convolutional_layer(input=x, num_input_channels=num_channels, conv_filter_size=filter_size_conv1, num_filters=num_filters_conv1) layer_conv2 = create_convolutional_layer(input=layer_conv1, num_input_channels=num_filters_conv1, conv_filter_size=filter_size_conv2, num_filters=num_filters_conv2) layer_conv3= create_convolutional_layer(input=layer_conv2, num_input_channels=num_filters_conv2, conv_filter_size=filter_size_conv3, num_filters=num_filters_conv3) layer_flat = create_flatten_layer(layer_conv3) layer_fc1 = create_fc_layer(input=layer_flat, num_inputs=layer_flat.get_shape()[1:4].num_elements(), num_outputs=fc_layer_size, use_relu=True) layer_fc2 = create_fc_layer(input=layer_fc1, num_inputs=fc_layer_size, num_outputs=num_classes, use_relu=False) y_pred = tf.nn.softmax(layer_fc2,name='y_pred') y_pred_cls = tf.argmax(y_pred, dimension=1) session.run(tf.global_variables_initializer()) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2, labels=y_true) cost = tf.reduce_mean(cross_entropy) #takes in softmax of matrix multiplication and compares it to the training target via cross-entropy optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost) correct_prediction = tf.equal(y_pred_cls, y_true_cls) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) session.run(tf.global_variables_initializer()) def show_progress(epoch, feed_dict_train, feed_dict_validate, val_loss): acc = session.run(accuracy, feed_dict=feed_dict_train) val_acc = session.run(accuracy, feed_dict=feed_dict_validate) msg = "Training Epoch {0} --- Training Accuracy: {1:&gt;6.1%}, Validation Accuracy: {2:&gt;6.1%}, Validation Loss: {3:.3f}" print(msg.format(epoch + 1, acc, val_acc, val_loss)) total_iterations = 0 saver = tf.train.Saver() def train(num_iteration): global total_iterations for i in range(total_iterations, total_iterations + num_iteration): x_batch, y_true_batch, _, cls_batch = data.train.next_batch(batch_size) x_valid_batch, y_valid_batch, _, valid_cls_batch = data.valid.next_batch(batch_size) feed_dict_tr = {x: x_batch, y_true: y_true_batch} feed_dict_val = {x: x_valid_batch, y_true: y_valid_batch} session.run(optimizer, feed_dict=feed_dict_tr) if i % int(data.train.num_examples/batch_size) == 0: val_loss = session.run(cost, feed_dict=feed_dict_val) epoch = int(i / int(data.train.num_examples/batch_size)) show_progress(epoch, feed_dict_tr, feed_dict_val, val_loss) saver.save(session, './emotions-model') total_iterations += num_iteration train(num_iteration=3000) </code></pre> <p>Dataset.py</p> <pre><code>def load_train(train_path, image_size, classes): images = [] labels = [] img_names = [] cls = [] print('Going to read training images') for fields in classes: index = classes.index(fields) print('Now going to read {} files (Index: {})'.format(fields, index)) path = os.path.join(train_path, fields, '*g') files = glob.glob(path) for fl in files: image = cv2.imread(fl) imag e = cv2.resize(image, (image_size, image_size),0,0, cv2.INTER_LINEAR) image = image.astype(np.float32) image = np.multiply(image, 1.0 / 255.0) images.append(image) label = np.zeros(len(classes)) label[index] = 1.0 labels.append(label) flbase = os.path.basename(fl) img_names.append(flbase) cls.append(fields) images = np.array(images) labels = np.array(labels) img_names = np.array(img_names) cls = np.array(cls) return images, labels, img_names, cls class DataSet(object): def __init__(self, images, labels, img_names, cls): self._num_examples = images.shape[0] self._images = images self._labels = labels self._img_names = img_names self._cls = cls self._epochs_done = 0 self._index_in_epoch = 0 @property def images(self): return self._images @property def labels(self): return self._labels @property def img_names(self): return self._img_names @property def cls(self): return self._cls @property def num_examples(self): return self._num_examples @property def epochs_done(self): return self._epochs_done def next_batch(self, batch_size): """Return the next `batch_size` examples from this data set.""" start = self._index_in_epoch self._index_in_epoch += batch_size if self._index_in_epoch &gt; self._num_examples: # After each epoch we update this self._epochs_done += 1 start = 0 self._index_in_epoch = batch_size assert batch_size &lt;= self._num_examples end = self._index_in_epoch return self._images[start:end], self._labels[start:end], self._img_names[start:end], self._cls[start:end] def read_train_sets(train_path, image_size, classes, validation_size): class DataSets(object): pass data_sets = DataSets() images, labels, img_names, cls = load_train(train_path, image_size, classes) images, labels, img_names, cls = shuffle(images, labels, img_names, cls) if isinstance(validation_size, float): validation_size = int(validation_size * images.shape[0]) validation_images = images[:validation_size] validation_labels = labels[:validation_size] validation_img_names = img_names[:validation_size] validation_cls = cls[:validation_size] train_images = images[validation_size:] train_labels = labels[validation_size:] train_img_names = img_names[validation_size:] train_cls = cls[validation_size:] data_sets.train = DataSet(train_images, train_labels, train_img_names, train_cls) data_sets.valid = DataSet(validation_images, validation_labels, validation_img_names, validation_cls) return data_sets </code></pre> <p>Log</p> <pre><code>Training Epoch 1 --- Training Accuracy: 66.7%, Validation Accuracy: 33.3%, Validation Loss: 1.748 Training Epoch 2 --- Training Accuracy: 33.3%, Validation Accuracy: 0.0%, Validation Loss: 1.646 Training Epoch 3 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.817 Training Epoch 4 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.625 Training Epoch 5 --- Training Accuracy: 33.3%, Validation Accuracy: 0.0%, Validation Loss: 1.912 Training Epoch 6 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.750 Training Epoch 7 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.307 Training Epoch 8 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.583 Training Epoch 9 --- Training Accuracy: 33.3%, Validation Accuracy: 0.0%, Validation Loss: 1.462 Training Epoch 10 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.722 Training Epoch 11 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.644 Training Epoch 12 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.390 Training Epoch 13 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.851 Training Epoch 14 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.318 Training Epoch 15 --- Training Accuracy: 33.3%, Validation Accuracy: 33.3%, Validation Loss: 1.612 Training Epoch 16 --- Training Accuracy: 66.7%, Validation Accuracy: 33.3%, Validation Loss: 1.054 Training Epoch 17 --- Training Accuracy: 66.7%, Validation Accuracy: 66.7%, Validation Loss: 1.386 Training Epoch 18 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 2.472 Training Epoch 19 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 1.062 Training Epoch 20 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.774 Training Epoch 21 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 1.122 Training Epoch 22 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 2.418 Training Epoch 23 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 1.389 Training Epoch 24 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 2.487 Training Epoch 25 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 4.330 Training Epoch 26 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 0.823 Training Epoch 27 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 2.173 Training Epoch 28 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 1.558 Training Epoch 29 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 3.549 Training Epoch 30 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 2.107 Training Epoch 31 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 4.092 Training Epoch 32 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 6.280 Training Epoch 33 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 2.862 Training Epoch 34 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 3.318 Training Epoch 35 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 0.827 Training Epoch 36 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 3.734 Training Epoch 37 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 2.328 Training Epoch 38 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 5.210 Training Epoch 39 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 6.896 Training Epoch 40 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 4.436 Training Epoch 41 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 4.195 Training Epoch 42 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.137 Training Epoch 43 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 4.350 Training Epoch 44 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 2.736 Training Epoch 45 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 6.058 Training Epoch 46 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 7.786 Training Epoch 47 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 5.402 Training Epoch 48 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 4.846 Training Epoch 49 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.314 Training Epoch 50 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 4.814 Training Epoch 51 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 3.047 Training Epoch 52 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 6.672 Training Epoch 53 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 8.441 Training Epoch 54 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 6.159 Training Epoch 55 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 5.220 Training Epoch 56 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.452 Training Epoch 57 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 5.171 Training Epoch 58 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 3.304 Training Epoch 59 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 7.131 Training Epoch 60 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 8.937 Training Epoch 61 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 6.786 Training Epoch 62 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 5.584 Training Epoch 63 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.554 Training Epoch 64 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 5.472 Training Epoch 65 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 3.526 Training Epoch 66 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 7.537 Training Epoch 67 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 9.353 Training Epoch 68 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 7.322 Training Epoch 69 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 5.857 Training Epoch 70 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.651 Training Epoch 71 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 5.719 Training Epoch 72 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 3.716 Training Epoch 73 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 7.873 Training Epoch 74 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 9.711 Training Epoch 75 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 7.728 Training Epoch 76 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 6.105 Training Epoch 77 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.723 Training Epoch 78 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 5.940 Training Epoch 79 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 3.877 Training Epoch 80 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 8.170 Training Epoch 81 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 10.021 Training Epoch 82 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 8.164 Training Epoch 83 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 6.326 Training Epoch 84 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.792 Training Epoch 85 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 6.139 Training Epoch 86 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 4.036 Training Epoch 87 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 8.436 Training Epoch 88 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 10.302 Training Epoch 89 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 8.543 Training Epoch 90 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 6.520 Training Epoch 91 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.853 Training Epoch 92 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 6.312 Training Epoch 93 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 4.167 Training Epoch 94 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 8.675 Training Epoch 95 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 10.554 Training Epoch 96 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 8.883 Training Epoch 97 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 6.700 Training Epoch 98 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 1.906 Training Epoch 99 --- Training Accuracy: 100.0%, Validation Accuracy: 66.7%, Validation Loss: 6.469 Training Epoch 100 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 4.293 Training Epoch 101 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 8.899 Training Epoch 102 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 10.787 Training Epoch 103 --- Training Accuracy: 100.0%, Validation Accuracy: 0.0%, Validation Loss: 9.221 Training Epoch 104 --- Training Accuracy: 100.0%, Validation Accuracy: 33.3%, Validation Loss: 6.876 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T17:10:16.690", "Id": "471906", "Score": "0", "body": "Welcome to code review where we review code that is working as expected so that we can provide suggestions on how that code can be improved. We are not able to debug code or add features to code. Unfortunately this question indicates that the code is not working as expected, and therefore is off-topic. Please check our guidelines at https://codereview.stackexchange.com/help/asking. I don't know if there is an AI related stackexchange Q&A site, but that would be the place to ask this question if there is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:33:18.003", "Id": "471934", "Score": "1", "body": "Considering the low validation accuracy, I do not consider this code to be working the way it should. This basically means it's too early for a review of it. Please take a look at the [help/on-topic]." } ]
[ { "body": "<p>Would you please check <code>read_train_set</code> function and make sure 20% of validation data consist of all seven classes? It's preferred to have all classes balanced in the training and testing data set. One way to do it is to split the data per class. Adding a dropout layer in CNN might help reduce over-fitting. The model might be able to detect 'happy' from 'sad' better than detect 'surprise' from 'fear'. A more detailed validation accuracy analysis will show some insight.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T06:19:03.053", "Id": "240542", "ParentId": "240519", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T17:38:51.533", "Id": "240519", "Score": "1", "Tags": [ "python", "machine-learning", "opencv", "tensorflow" ], "Title": "Tensorflow Python ML to Detect Emotion" }
240519
<blockquote> <p><em>1.11 Arranging the derivative of a function<br> The derivative of any function f (x) at x0 can be estimated according to the following formula:</em></p> <p><a href="https://i.stack.imgur.com/cImtN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cImtN.png" alt="enter image description here"></a></p> <p><em>Write a program that prints three columns of numbers: x, f (x) and the derivative f '(x) for some simple functions, e.g. sin (x) or arctan(x).</em></p> </blockquote> <pre><code>public static class Derrivative { public static double Compute(Func&lt;double, double&gt; f, double x0, double h) { return (f(x0+h) - f(x0-h)) / (2*h); } } class Program { static void Main(string[] args) { const int N = 10; Console.WriteLine("Derivative of sin(x)"); Func&lt;double, double&gt; function = Math.Sin; for (int i = 0; i &lt; N; i++) { Console.WriteLine($"{i}\t{function(i)}\t{Derrivative.Compute(function, i, 0.5)}"); } Console.WriteLine(); Console.WriteLine("Derivative of arctan(x)"); function = Math.Atan; for (int i = 0; i &lt; N; i++) { Console.WriteLine($"{i}\t{function(i)}\t{Derrivative.Compute(function, i, 0.5)}"); } Console.ReadLine(); } } </code></pre> <p>Kindly, review this source code.</p>
[]
[ { "body": "<p>Separate the for loop to a function <code>printFunction(f, N)</code></p>\n\n<p>Since you are using a known formula I suggest you use the names in the formula. Meaning i->x\nfunction->f. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T12:39:00.420", "Id": "240558", "ParentId": "240521", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T18:10:41.787", "Id": "240521", "Score": "2", "Tags": [ "c#", "mathematics" ], "Title": "Compute the derivative of a function" }
240521
<p>I'm trying to reduce nested JSON data using Haskell and Aeson without creating data/record types.<br> The following code works, but seems ugly and unreadable.<br> Any advice on cleaning this up would be great. </p> <p>Thank you</p> <pre><code>import GHC.Exts import Data.Maybe (fromJust) import Data.Text (Text) import Data.Aeson import qualified Data.HashMap.Strict as M testVal :: Value testVal = Object $ fromList [ ("items", Array $ fromList [ (Object $ fromList [ ("entity", (Object $ fromList [ ("uuid", String "needed-value1")]))]), (Object $ fromList [ ("entity", (Object $ fromList [ ("uuid", String "needed-value2")]))]) ])] getItems :: Value -&gt; Value getItems (Object o) = fromJust $ M.lookup "items" o getEntities :: Value -&gt; Value getEntities (Array a) = Array $ fmap (\(Object o) -&gt; fromJust $ M.lookup "entity" o) a getUuids :: Value -&gt; Value getUuids (Array a) = Array $ fmap (\(Object o) -&gt; fromJust $ M.lookup "uuid" o) a getTexts :: Value -&gt; [Text] getTexts (Array a) = toList $ fmap (\(String s) -&gt; s) a someFunc :: IO () someFunc = do let items = getItems testVal entities = getEntities items uuids = getUuids entities texts = getTexts uuids print texts </code></pre> <p>output:</p> <pre><code>["needed-value1","needed-value2"] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T10:46:11.810", "Id": "471858", "Score": "1", "body": "You should really use an algebraic data type to implement your JSON interface. Then you can automatically derive `FromJSON` instances. This will make your code way cleaner.\nCould you also provide a sample JSON string that you want to parse?" } ]
[ { "body": "<p>You should really use an algebraic data type to implement your JSON interface. You can even automatically derive <code>FromJSON</code> instances with <code>DeriveGeneric</code> GHC extension, e.g.</p>\n\n<pre><code>{-# LANGUAGE DeriveGeneric #-}\n{-# LANGUAGE OverloadedStrings #-}\n\nimport GHC.Generics\nimport Data.Aeson\nimport Data.ByteString.Lazy (ByteString)\n\ndata Query = Query { items :: [Entity] }\n deriving (Show, Generic)\n\ninstance FromJSON Query -- automatically derived instance by DeriveGeneric\n\ndata Entity = Entity { uuid :: String }\n deriving (Show)\n\ninstance FromJSON Entity where\n parseJSON = withObject \"Entity\" $ \\v -&gt; do\n -- as your json data is additionally nested with an entity object\n -- extract the entity object first\n obj &lt;- v .: \"entity\"\n -- then extract the uuid field from the entity object\n uid &lt;- obj .: \"uuid\"\n return $ Entity uid\n\ntestVal :: ByteString\ntestVal = \"{\\\"items\\\": [{\\\"entity\\\": {\\\"uuid\\\": \\\"needed-value1\\\"}}, {\\\"entity\\\": {\\\"uuid\\\": \\\"needed-value2\\\"}}]}\"\n\nmain :: IO ()\nmain = do\n let mayQuery = decode testVal\n case mayQuery of\n Just query -&gt; print $ map uuid $ items query\n Nothing -&gt; putStrLn \"JSON parsing error\"\n</code></pre>\n\n<p>I transformed your sample <code>Value</code> into a JSON string, to make the parsing clearer.</p>\n\n<p>The <code>FromJSON</code> instance for <code>Query</code> is automatically derived, if you want to write it by hand, you can do this in analogy to the <code>FromJSON</code> instance of <code>Entity</code>.</p>\n\n<p>This way of parsing your JSON data is very scalable, as you can easily add new fields to your data types, without complicating your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T11:09:08.413", "Id": "240553", "ParentId": "240528", "Score": "2" } }, { "body": "<p>You should strongly consider @Erich's advice and define datatypes but it is possible to write quick and dirty queris without them.</p>\n\n<pre><code>{-# LANGUAGE OverloadedStrings #-} \n{-# LANGUAGE QuasiQuotes #-}\n\nimport Data.Text (Text)\nimport Data.Aeson (Value, Result(..), decode, withObject, (.:))\nimport Data.Aeson.Types (parse)\nimport Data.Aeson.QQ.Simple\nimport Control.Monad ((&gt;=&gt;))\n\n\ntestVal :: Value\ntestVal = [aesonQQ|\n {\"items\": [\n {\"entity\": {\"uuid\": \"needed-value1\"}},\n {\"entity\": {\"uuid\": \"needed-value2\"}}\n ]}\n|]\n\ngetUuids :: Value -&gt; Result [Text]\ngetUuids = parse $ withObject \"\"\n $ (.: \"items\") &gt;=&gt; mapM ((.: \"entity\") &gt;=&gt; (.: \"uuid\"))\n\n\nmain :: IO ()\nmain = do\n print $ getUuids testVal\n print $ getUuids &lt;$&gt; decode \"{}\"\n print $ getUuids &lt;$&gt; decode \"{\"\n</code></pre>\n\n<p>Another option is to use <a href=\"https://hackage.haskell.org/package/lens-aeson\" rel=\"nofollow noreferrer\">lens-aeson</a> package:</p>\n\n<pre><code>import Control.Lens\nimport Data.Aeson.Lens (values, key, _String)\n\n-- [...]\n\nmain :: IO ()\nmain = print\n $ testVal ^.. key \"items\" . values . key \"entity\" . key \"uuid\" . _String\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:59:50.140", "Id": "240575", "ParentId": "240528", "Score": "1" } } ]
{ "AcceptedAnswerId": "240575", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T21:57:53.837", "Id": "240528", "Score": "3", "Tags": [ "haskell", "json" ], "Title": "Parsing nested JSON with Haskell and Aeson" }
240528
<p>I've been writing code for some time but never had the need (or opportunity) to write C/C++ code. Did a small project to learn some C++ and would appreciate feedback on code, testing, project structure and building.</p> <h2>Project Layout</h2> <pre><code>. ├── CMakeLists.txt ├── src │   ├── personnummer.cpp │   └── personnummer.hpp └── test ├── catch.hpp └── unittest.cpp </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 3.0) project(cpp-personnummer) set(CMAKE_CXX_STANDARD 11) set(SOURCE_FILES src/personnummer.cpp) add_library(Personnummer ${SOURCE_FILES}) target_link_libraries(Personnummer -lpthread) add_executable(unittest test/unittest.cpp) target_link_libraries(unittest Personnummer) </code></pre> <p><strong>src/personnummer.hpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;ctime&gt; #include &lt;iostream&gt; #include &lt;vector&gt; namespace Personnummer { int stoi_or_fallback(const std::string &amp;maybe_digit, int fallback); bool valid_date(int year, int month, int day); int checksum(std::tm date, int number); void collect_digits(std::vector&lt;int&gt; &amp;digits, int num); void collect_digits_pad_zero(std::vector&lt;int&gt; &amp;digits, int num, int min_len); struct Personnummer { std::tm date; int number; int control; char divider[1]; bool is_valid_date() { return valid_date(date.tm_year, date.tm_mon, date.tm_mday); }; bool is_valid_luhn() { return checksum(date, number) == control; }; bool valid() { return is_valid_date() &amp;&amp; is_valid_luhn(); }; }; bool from_string(const std::string &amp;pnr, Personnummer &amp;personnummer); } // namespace Personnummer </code></pre> <p><strong>src/personnummer.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include "personnummer.hpp" #include &lt;regex&gt; namespace Personnummer { bool from_string(const std::string &amp;pnr, Personnummer &amp;personnummer) { std::regex pnr_regex( "^(\\d{2})?(\\d{2})(\\d{2})(\\d{2})([-|+]?)?(\\d{3})(\\d?)$"); std::smatch matches; int century, year; if (std::regex_search(pnr, matches, pnr_regex)) { century = stoi_or_fallback(matches.str(1), 19); year = stoi_or_fallback(matches.str(2), 0); personnummer.date.tm_year = century * 100 + year; personnummer.date.tm_mon = stoi_or_fallback(matches.str(3), 0); personnummer.date.tm_mday = stoi_or_fallback(matches.str(4), 0); personnummer.number = stoi_or_fallback(matches.str(6), 0); personnummer.control = stoi_or_fallback(matches.str(7), 0); personnummer.divider[0] = *matches.str(5).c_str(); } else { return false; } return true; } int stoi_or_fallback(const std::string &amp;maybe_digit, int fallback) { try { return std::stoi(maybe_digit); } catch (...) { return fallback; } } bool valid_date(int year, int month, int day) { if (month &lt; 1 || month &gt; 12) return false; if (day &lt; 1 || day &gt; 31) return false; if (day &gt; 30) { switch (month) { case 2: case 4: case 6: case 9: case 11: return false; } } if (month == 2 &amp;&amp; day &gt; 28) { bool is_leap_year = year % 400 == 0 || (year % 100 != 0 &amp;&amp; year % 4 == 0); if (day != 29 || !is_leap_year) { return false; } } return true; } int checksum(std::tm date, int number) { std::vector&lt;int&gt; digits; collect_digits_pad_zero(digits, date.tm_year % 100, 2); collect_digits_pad_zero(digits, date.tm_mon, 2); collect_digits_pad_zero(digits, date.tm_mday, 2); collect_digits_pad_zero(digits, number, 3); int sum = 0; for (int i = 0; i &lt; digits.size(); i++) { int temp = digits.at(i); if (i % 2 == 0) { temp *= 2; if (temp &gt; 9) temp -= 9; } sum += temp; } return 10 - (sum % 10); } void collect_digits(std::vector&lt;int&gt; &amp;digits, int num) { if (num &gt; 9) collect_digits(digits, num / 10); digits.push_back(num % 10); } void collect_digits_pad_zero(std::vector&lt;int&gt; &amp;digits, int num, int min_len) { // New vector for this section. std::vector&lt;int&gt; section_digits; // Collect the digits from given number. collect_digits(section_digits, num); // Add the potential padded zeroes. int missing_digits = min_len - section_digits.size(); for (int i = 0; i &lt; missing_digits; i++) { section_digits.insert(section_digits.begin(), 0); } // Add the padded section to final vector. digits.insert(digits.end(), section_digits.begin(), section_digits.end()); } } // namespace Personnummer </code></pre> <p><strong>test/unittest.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#define CATCH_CONFIG_MAIN #include "../src/personnummer.hpp" #include "catch.hpp" TEST_CASE("Valid date", "[date]") { std::vector&lt;std::vector&lt;int&gt;&gt; valid_dates = { {1990, 1, 1}, {1990, 1, 31}, {1990, 2, 28}, {2016, 2, 29}, // 2016 is leap year {2020, 4, 30}, }; std::vector&lt;std::vector&lt;int&gt;&gt; invalid_dates = { {1990, 13, 1}, {1990, 1, 32}, {2017, 2, 29}, // 2017 is not leap year {2020, 4, 31}, }; for (int i = 0; i &lt; valid_dates.size(); i++) { std::vector&lt;int&gt; test_case = valid_dates[i]; std::stringstream case_title; case_title &lt;&lt; "Testinv VALID: Y=" &lt;&lt; test_case[0] &lt;&lt; ", M=" &lt;&lt; test_case[1] &lt;&lt; ", D=" &lt;&lt; test_case[2]; SECTION(case_title.str()) { REQUIRE( Personnummer::valid_date(test_case[0], test_case[1], test_case[2])); } } for (int i = 0; i &lt; invalid_dates.size(); i++) { std::vector&lt;int&gt; test_case = invalid_dates[i]; std::stringstream case_title; case_title &lt;&lt; "Testinv INVALID: Y=" &lt;&lt; test_case[0] &lt;&lt; ", M=" &lt;&lt; test_case[1] &lt;&lt; ", D=" &lt;&lt; test_case[2]; SECTION(case_title.str()) { REQUIRE( !Personnummer::valid_date(test_case[0], test_case[1], test_case[2])); } } } TEST_CASE("Valid personal number", "[pnr]") { Personnummer::Personnummer p; std::vector&lt;std::string&gt; valid = { "6403273813", "510818-9167", "19900101-0017", "19130401+2931", "196408233234", "0001010107", "000101-0107", }; std::vector&lt;std::string&gt; invalid = { "640327-381", "6403273814", "640327-3814", }; for (int i = 0; i &lt; valid.size(); i++) { std::stringstream case_title; case_title &lt;&lt; "Testing VALID: " &lt;&lt; valid[i]; SECTION(case_title.str()) { REQUIRE(Personnummer::from_string(valid[i], p)); REQUIRE(p.valid()); } } for (int i = 0; i &lt; invalid.size(); i++) { std::stringstream case_title; case_title &lt;&lt; "Testing INVALID: " &lt;&lt; invalid[i]; SECTION(case_title.str()) { REQUIRE(Personnummer::from_string(invalid[i], p)); REQUIRE(!p.valid()); } } } </code></pre> <p><strong>test/catch.hpp</strong></p> <p>Downloaded from <a href="https://github.com/catchorg/Catch2" rel="nofollow noreferrer">GitHub Repository</a></p> <hr> <p>General feedback and reviews are very welcome but these are the main questions I had writing this:</p> <ul> <li>Does the code itself look OK? (It's formatted with <code>clang-format --style=llvm</code>)</li> <li>Are there any issues (big or small) that I've missed (bugs, memory leaks etc).</li> <li>How far off C++ pragma is it? <ul> <li>What would be a more C++ way of things?</li> </ul></li> <li>Is the way I split the code in files vs. headers a good/preferred way?</li> <li>Are the unit tests written in a good way (structure, location, naming, table driven)?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T23:09:19.403", "Id": "471836", "Score": "0", "body": "@BCdotWEB Thanks! I'll look into that for some of the questions. My bullets were ment to be more like guidance to areas of interest and not to be seen as something I wanted one single person to look at and respond to all of them. The main hope here was to get some feedback on the code and I think a lot of the bullets are related to that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T06:32:14.707", "Id": "471849", "Score": "0", "body": "@tinstaafl Well, I know what my code does so my questions are more related to the quality of the code. I also think it's of high importance to write good code to structure it right and use best practices. But after revisiting the Help Center I can see how I was off-topic so the question is now edited to include more relevant questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T07:52:02.603", "Id": "471854", "Score": "0", "body": "@BCdotWEB Sorry, forgot to edit that when removing the bullets. Updated now, hope this is more in line with the guidelines." } ]
[ { "body": "<p>Here are some suggestions for how you might improve your code.</p>\n\n<h2>Use the required <code>#include</code>s</h2>\n\n<p>The code uses <code>std::string</code> which means that it should <code>#include &lt;string&gt;</code>. It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n\n<h2>Know your tools</h2>\n\n<p>The CMake file starts with these lines:</p>\n\n<pre><code>cmake_minimum_required(VERSION 3.0)\nproject(cpp-personnummer)\nset(CMAKE_CXX_STANDARD 11)\n</code></pre>\n\n<p>However, that's a problem because the <code>CMAKE_CXX_STANDARD</code> wasn't intruduced until CMake version 3.1. I'd recommend changing the <code>cmake_minimum_required</code> to 3.1.</p>\n\n<h2>Don't link with unnecesary libraries</h2>\n\n<p>The CMake file currently contains this line:</p>\n\n<pre><code>target_link_libraries(Personnummer -lpthread)\n</code></pre>\n\n<p>First, the correct way to do this in CMake would be like this instead:</p>\n\n<pre><code>find_package(Threads)\ntarget_link_libraries(Personnummer ${CMAKE_THREAD_LIBS_INIT})\n</code></pre>\n\n<p>Second, and most importantly, it doesn't need to be done at all since nothing in there requires threads.</p>\n\n<h2>Use standard classes where appropriate</h2>\n\n<p>Much of the date handling from the <code>Personnummer</code> class could be done more simply by using the <code>std::chrono::year_month_day</code> class. For example, <code>valid_date</code> could be eliminated entirely in favor of <a href=\"https://en.cppreference.com/w/cpp/chrono/year_month_day/ok\" rel=\"nofollow noreferrer\">year_month_day.ok()</a> if your compiler supports C++20.</p>\n\n<h2>Use CMake's test facility</h2>\n\n<p>CMake has test facilities built in. I'd add the option to either build tests or not and in the top level <code>CMakeLists.txt</code> add this:</p>\n\n<pre><code>option(WITH_TEST \"Build the test suite\" OFF)\nif (WITH_TEST)\n enable_testing()\n add_subdirectory(test)\nendif()\n</code></pre>\n\n<p>Now if you invoke CMake with <code>cmake -DWITH_TEST=1 ..</code> testing will be enabled. If you then do <code>make</code> and then <code>make test</code>, you will invoke your test(s). Note here that I've written <code>add_subdirectory</code>. See the next suggestion for more on that.</p>\n\n<h2>Use multiple <code>CMakeLists.txt</code> files</h2>\n\n<p>Instead of a single <code>CMakeLists.txt</code> file, it's easier to maintain if you create one per directory. So the top level would look like this:</p>\n\n<pre><code>cmake_minimum_required(VERSION 3.1)\nproject(Personnummer)\nset(CMAKE_CXX_STANDARD 11)\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic\")\noption(WITH_TEST \"Build the test suite\" OFF)\nadd_subdirectory(src)\n\nif (WITH_TEST)\n enable_testing()\n add_subdirectory(test)\nendif()\n</code></pre>\n\n<p>Now the one in <code>src</code> looks like this:</p>\n\n<pre><code>cmake_minimum_required(VERSION 3.1)\nadd_library(Personnummer \"personnummer.cpp\")\n</code></pre>\n\n<p>And the one in <code>test</code> looks like this:</p>\n\n<pre><code>cmake_minimum_required(VERSION 3.1)\ninclude_directories(${CMAKE_HOME_DIRECTORY}/src)\nadd_executable(unittest \"unittest.cpp\")\nadd_test(PersonnummerTest unittest)\ntarget_link_libraries(unittest Personnummer)\n</code></pre>\n\n<p>Note that I've added the <code>include_directories</code> to point to the <code>src</code> directory. More on that in the next suggestion.</p>\n\n<h2>Don't hardcode project directory structures</h2>\n\n<p>In the current test program we have this line:</p>\n\n<pre><code>#include \"../src/personnummer.hpp\"\n</code></pre>\n\n<p>This buries a project configuration detail inside source code. I recommend keeping those kinds of details out of the individual source files and instead point the tools (compiler, linker, etc.) to the appropriate directory instead. That's why the <code>include_directories</code> was added to the <code>CMakeLists.txt</code> file for the <code>test</code> directory. This way, if you decided to rename the <code>src</code> directory or move it elsewhere, the change could easily be made in just the CMake files instead of having to hunt through every source code file. When there only a few, as with this small project, it might not seem like it makes much difference, but when you start working with large projects with thousands of files, following this advice will save you a great deal of time and frustration.</p>\n\n<h2>Prefer iteration to recursion</h2>\n\n<p>The current definition of <code>collect_digits</code> is this recursive solution:</p>\n\n<pre><code>void collect_digits(std::vector&lt;int&gt; &amp;digits, int num) {\n if (num &gt; 9)\n collect_digits(digits, num / 10);\n\n digits.push_back(num % 10);\n}\n</code></pre>\n\n<p>It's not faulty, but it isn't as efficient as it could be. Generally, recursion is less efficient than iteration. The reason is that pushing the the return address and both arguments onto the stack takes a bit more time and memory than simply doing this:</p>\n\n<pre><code>void collect_digits(std::vector&lt;int&gt; &amp;digits, int num) {\n while ( ; num &gt; 9; num /= 10) {\n digits.push_back(num % 10);\n }\n digits.push_back(num);\n}\n</code></pre>\n\n<p>Better though, see the next suggestion.</p>\n\n<h2>Rethink the interface</h2>\n\n<p>There are a number of specialized functions such as <code>collect_digits_pad_zero</code> that probably don't need to be part of the interface, or maybe shouldn't exist at all. For example, <code>checksum</code> could be much simplified and wouldn't require either <code>collect_digits_pad_zero</code> or <code>collect_digits</code>. Here's how I'd write it:</p>\n\n<pre><code>int luhn(std::string::iterator begin, std::string::iterator end) {\n int sum{0};\n for (bool even{true}; begin != end; ++begin, even ^= true) {\n int digit = *begin - '0';\n if (even) {\n if ((digit *= 2) &gt; 9) {\n digit -= 9;\n }\n } \n if ((sum += digit) &gt; 9) {\n sum -= 10;\n }\n }\n return sum;\n}\n\nint Personnummer::checksum() const {\n using namespace std;\n stringstream ss;\n ss.fill('0');\n ss &lt;&lt; setw(2)\n &lt;&lt; date.tm_year % 100\n &lt;&lt; setw(2)\n &lt;&lt; date.tm_mon\n &lt;&lt; setw(2)\n &lt;&lt; date.tm_mday\n &lt;&lt; setw(3) &lt;&lt; number;\n auto str = ss.str();\n return 10 - luhn(str.begin(), str.end());\n}\n</code></pre>\n\n<p>Now we have two compact and useful functions. Note also that <code>checksum</code> is a member function rather than a standalone function.</p>\n\n<h2>Use <code>const</code> where appropriate</h2>\n\n<p>The functions <code>is_valid_luhn</code> and <code>valid</code> and <code>is_valid_date</code> are all non-modifying functions. That is, none of them modify the underlying <code>Personnummer</code> object, so all of them should be declared <code>const</code> as with the <code>checksum</code> function above.</p>\n\n<h2>Prefer <code>class</code> to <code>struct</code></h2>\n\n<p>If there is not a compelling that <code>Personnummer</code> must have all of its data and functions public, it should be a class instead of a struct, and <code>from_string</code> should be a member function.</p>\n\n<h2>Don't create pointless arrays</h2>\n\n<p>The <code>Personnummer</code> object definition currently includes this:</p>\n\n<pre><code>char divider[1];\n</code></pre>\n\n<p>That should just be this:</p>\n\n<pre><code>char divider;\n</code></pre>\n\n<h2>Use \"range <code>for</code>\" to simplify your code</h2>\n\n<p>The test code currently has these kinds of loops:</p>\n\n<pre><code>for (int i = 0; i &lt; valid.size(); i++) {\n std::stringstream case_title;\n case_title &lt;&lt; \"Testing VALID: \" &lt;&lt; valid[i];\n\n SECTION(case_title.str()) {\n REQUIRE(p.from_string(valid[i]));\n REQUIRE(p.valid());\n }\n}\n</code></pre>\n\n<p>First, you can use a range <code>for</code> to simplify, and second, there's no need for a <code>std::stringstream</code> here:</p>\n\n<pre><code>for (const auto&amp; test_string : valid) {\n SECTION({\"Testing VALID\" + test_string}) {\n REQUIRE(p.from_string(test_string));\n REQUIRE(p.valid());\n }\n}\n</code></pre>\n\n<p>This also assumes that the <code>from_string</code> function has been made a member function, as mentioned earlier.</p>\n\n<h2>Use classes to simplify your code</h2>\n\n<p>The test cases for \"Valid date\" use <code>std::vector&lt;std::vector&lt;int&gt;&gt;</code> as the collection of test cases. I'd suggest using a class there instead:</p>\n\n<pre><code>struct FakeDate {\n int year, month, day;\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const FakeDate&amp; fd) {\n return out &lt;&lt; \"Y=\" &lt;&lt; fd.year &lt;&lt; \", M=\" &lt;&lt; fd.month &lt;&lt; \", D=\" &lt;&lt; fd.day;\n }\n};\n</code></pre>\n\n<p>Now the collections can be <code>std::vector&lt;FakeDate&gt;</code>. Using the same range <code>for</code> as in the previous suggestion, we have:</p>\n\n<pre><code>for (const auto&amp; test_case : valid_dates) {\n std::stringstream case_title;\n case_title &lt;&lt; \"Testing VALID: \" &lt;&lt; test_case;\n\n SECTION(case_title.str()) {\n REQUIRE(\n Personnummer::valid_date(test_case.year, test_case.month, test_case.day));\n }\n}\n</code></pre>\n\n<h2>Be careful with signed vs. unsigned</h2>\n\n<p>The current <code>valid_date</code> code takes <code>int</code>s for the month, day and year. Is it intended that negative values for the year do not make the date invalid? If not, I'd suggest either checking for negative values or using only unsigned integers for each.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T22:04:30.157", "Id": "471962", "Score": "0", "body": "Thank you so much, this was really the things I wanted to know more about! It felt bad writing my own date validator but I'm stuck with C++14 (macOS) so no `chrono` for me. Besides that, I adapted most of your suggestions. If you're interested the updated result can be found [here](https://github.com/bombsimon/cpp-personnummer). Again, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T22:10:44.567", "Id": "471964", "Score": "0", "body": "I’m happy you found it useful. That’s why we’re here!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T14:13:40.723", "Id": "240563", "ParentId": "240529", "Score": "4" } } ]
{ "AcceptedAnswerId": "240563", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T22:08:48.780", "Id": "240529", "Score": "3", "Tags": [ "c++", "c++11", "cmake" ], "Title": "Validating Swedish social security numbers (Luhn algorithm and dates)" }
240529
<p>I started a simple OOP GUI project with tkinter in Python since I've been studying the basics for a while, but I'm not sure if my code is properly structured and following the programming conventions. I haven't finished it yet but the sooner I learn the good practices the better. My goal is to make a mini game. For now it only has a main window and a character selection window with some widgets in it. (For didactic purposes, I want it to be done with an OOP approach).</p> <pre><code>import tkinter as tk from itertools import product # Creating main page class MainApplication(tk.Frame): def __init__(self, master, *args, **kwargs): tk.Frame.__init__(self, master, *args, **kwargs) self.master = master # produce the set of coordinates of the buttons main_positions = product(range(2), range(5)) # Creating main page widgets frame = tk.Frame(root, bg="#34495e") frame.grid() lb = tk.Label(frame, width=111, height=4, bg="#2c3e50", text="Champions", fg="white", font=50, justify=tk.CENTER) lb.grid(row=0, column=0, columnspan=5, pady=(0, 50), sticky="snew") # Creating multiple buttons for i, item in enumerate(main_positions): button_main = tk.Button(frame, width=16, height=8, bg="#2c3e50", relief=tk.RIDGE, fg="white", justify=tk.CENTER, text=f"Champion {item[1] + 1}", command=ChampionWindow.champions_window) button_main.grid(row=item[0] + 1, column=item[1], pady=(0, 50)) button = tk.Button(frame, width=30, height=3, bg="#2c3e50", relief=tk.RIDGE, text="Done", fg="white", font=20, command=root.destroy) button.grid(row=3, columnspan=5, pady=(0, 150)) # Creating champion select window class ChampionWindow(tk.Frame): def __init__(self, master, *args, **kwargs): tk.Frame.__init__(self, master, *args, **kwargs) self.master = master @staticmethod def champions_window(): ch_window = tk.Tk() ch_window.title("Champion Select") ch_window.resizable(False, False) ch_window.configure(background="#192a56") champion_position = product(range(30), range(5)) def scroll(ch_event): ch_canvas.configure(scrollregion=ch_canvas.bbox("all")) def select_champion(): pass ch_canvas = tk.Canvas(ch_window, bg="blue", width=470, height=500) ch_frame = tk.Frame(ch_canvas, bg="#273c75") vscrollbar = tk.Scrollbar(ch_window, orient="vertical", command=ch_canvas.yview) ch_canvas.configure(yscrollcommand=vscrollbar.set) ch_canvas.grid(sticky="snew") vscrollbar.grid(row=0, column=3, sticky="sn") ch_canvas.create_window((0, 0), window=ch_frame, anchor="nw") ch_frame.bind("&lt;Configure&gt;", scroll) # Creating multiple buttons for x, itm in enumerate(champion_position): btn = tk.Button(ch_frame, width=12, height=6, bg="#2c3e50", relief=tk.RIDGE, fg="white", justify=tk.CENTER, command=select_champion) btn["text"] = f"Pick champ {x+1}" btn.grid(row=itm[0], column=itm[1]) if __name__ == "__main__": root = tk.Tk() MainApplication(root) root.configure(background="#273c75") root.geometry("1000x570+450+200") root.resizable(False, False) root.title("Champion") root.mainloop() </code></pre> <p><strong>Images:</strong></p> <p><a href="https://i.stack.imgur.com/xpjaC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xpjaC.png" alt="Main Window"></a> <br> <strong>- The buttons open the character selection window</strong> </p> <p><a href="https://i.stack.imgur.com/S5F38.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S5F38.png" alt="Character Selection Window (with scrollbar)"></a> <br>- In the future the buttons will pick the selected character that will be represented by an image with PIL library.</p>
[]
[ { "body": "<h2>Don't create more than one instance of Tk</h2>\n\n<p>You should only ever create exactly one instance of <code>Tk. If you need to make more windows, use</code>Toplevel`.</p>\n\n<h2>You aren't using inheritance properly</h2>\n\n<p>This code is wrong:</p>\n\n<pre><code>class MainApplication(tk.Frame):\n def __init__(self, master, *args, **kwargs):\n tk.Frame.__init__(self, master, *args, **kwargs)\n ...\n # Creating main page widgets\n frame = tk.Frame(root, bg=\"#34495e\")\n ...\n lb = tk.Label(frame, ...)\n</code></pre>\n\n<p>First, you inherit from <code>tk.Frame</code>. This is good, in that when done properly you can treat <code>MainApplication</code> as if it were a standalone widget. However, the first thing you do after creating this frame is to create <em>another</em> frame as a child of root. That makes no sense since the object is itself already a frame. It completely negates any advantage of inheriting from <code>tk.Frame</code>.</p>\n\n<p>The proper way to do this is to <em>not</em> create the \"main page widgets\" frame. Just remove that, and then put all widgets created by <code>MainApplication</code> inside <code>self</code>. The basic structure should look like this:</p>\n\n<pre><code>class MainApplication(tk.Frame):\n def __init__(self, master, *args, **kwargs):\n tk.Frame.__init__(self, master, *args, **kwargs):\n\n lb = tk.Label(self, ...)\n ...\n button_main = tk.Button(self, ...)\n ...\n button = tk.Button(self, ...)\n ...\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n app = MainApplication(root)\n # app is a frame, so add it to root. Since it's the \n # only widget in root, pack is the simplest method \n # to add it to the root window\n app.pack(fill=\"both\", expand=True)\n</code></pre>\n\n<p>With that, everything in <code>MainApplication</code> is encapsulated inside the <code>MainApplication</code> frame, Nothing is leaking out into other widgets.</p>\n\n<h2>Don't inherit from Frame if it's not a frame</h2>\n\n<p>Your <code>ChampionWindow</code> inherits from <code>Frame</code>, but I can't see any reason to do so based on the way you coded it. You never use an instance of <code>ChampionsWindow</code> anywhere so there's no point in inheriting from anything.</p>\n\n<p>Since the only purpose of <code>ChampionWindow</code> appears to be to hold a static method which creates a new window, I recommend inheriting from <code>Toplevel</code> and moving all code from the static method into a normal method called from <code>__init__</code>. </p>\n\n<h2>Don't remove control from the user</h2>\n\n<p>This is more of a personal preference, but I don't see any reason to remove the user's ability to resize the window with <code>root.resizable(False, False)</code>. Usually, when I see that, it's a sign you didn't take the time to make your UI responsive. That seems to be the case here - the UI doesn't respond properly to resizing. Instead of just removing that ability, I recommend doing a few things to make the UI respond properly to resizing. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:02:19.387", "Id": "471898", "Score": "0", "body": "Thank you very much for your review, it helped me a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:08:49.960", "Id": "240565", "ParentId": "240531", "Score": "3" } }, { "body": "<p>Sadly, I am not familiar with <code>tkinter</code> but have used <code>QT</code> a bit and some concepts are similar. You will be interested in reading more about the layout managers for resizable windows and controls - see <a href=\"http://zetcode.com/tkinter/layout/\" rel=\"nofollow noreferrer\">Layout management in Tkinter</a>. You are not exploiting their full potential.</p>\n\n<p>I would always allow resize and never expect that the screen dimensions will always remain the same. And it takes very little to spoil your layout - just changing font could have a dramatic effect. <strong>Grid layouts</strong> exist for a reason, so use them.</p>\n\n<p><strong>Hardcoded</strong> colors like <code>#273c75</code> should be defined as variables at the top op your code, possibly in a dedicated module if you end up with multiple files. But a configuration file would be nice. Because it is the kind of things that users will want to customize. Some people have poor sight and prefer high contrast, and the colors are not rendered the same on every screen.</p>\n\n<p>So <code>#34495e</code> could be named <code>BLUE_GRAY</code> or something along these lines (use meaningful and descriptive names). I have no idea what <code>#34495e</code> looks like otherwise.</p>\n\n<p>Same remark for <code>fg=\"white\"</code>: don't use hardcoded colors.\nEverything that is related to the <strong>customization</strong> of controls like padding, font size etc should be defined in a dedicated section or separate file. But I still prefer a configuration file of some sort.</p>\n\n<p>Same here:</p>\n\n<pre><code>champion_position = product(range(30), range(5))\n</code></pre>\n\n<p>Don't use fixed ranges in code, add some level of abstraction (and flexibility).</p>\n\n<p>In programming it is important to <strong>separate logic from presentation</strong> as much as possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:49:05.360", "Id": "471951", "Score": "0", "body": "Thank you very much for your review, it was really useful! I'll be more careful with the presentation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:46:41.290", "Id": "240583", "ParentId": "240531", "Score": "2" } } ]
{ "AcceptedAnswerId": "240565", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T23:01:15.230", "Id": "240531", "Score": "3", "Tags": [ "python", "object-oriented", "tkinter", "user-interface" ], "Title": "Is my Python tkinter application properly structured?" }
240531
<p>I am using flask with sqlAlchemy to connect with a postgresql database with two tables</p> <p><code>Users table (id, name)</code></p> <p><code>Admissions table (id, userId)</code></p> <p><code>Admissions table</code> with a <code>foreign key (userId)</code> connected to <code>Users(id)</code></p> <p>I want to get <code>Users</code> if <code>user.id</code> is found in <code>admissions</code> <code>userId</code></p> <p>This is what I am doing</p> <pre><code>users = [i for i in Users.query.all() if Admissions.query.filter_by(userid=i.id).first()] </code></pre> <p>Any better way to do this?</p> <p>Thank you</p> <p>Edit: <code>Users</code></p> <pre><code>Table "public.users" Column | Type | Collation | Nullable | Default ----------+-----------------------+-----------+----------+------------------------------------ id | integer | | not null | nextval('users__id_seq'::regclass) sid | character varying(10) | | | name | text | | | username | text | | | password | text | | | admin | boolean | | | false deleted | boolean | | | false Indexes: "users_pkey" PRIMARY KEY, btree (id) Referenced by: TABLE "admissions" CONSTRAINT "admissions_userid_fkey" FOREIGN KEY (userid) REFERENCES users(id) </code></pre> <p><code>Admissions</code></p> <pre><code>Table "public.admissions" Column | Type | Collation | Nullable | Default ------------+--------------------------+-----------+----------+---------------------------------------- id | integer | | not null | nextval('admissions_id_seq'::regclass) examid | integer | | | userid | integer | | | startdate | timestamp with time zone | | | CURRENT_TIMESTAMP submitdate | timestamp with time zone | | | Indexes: "admissions_pkey" PRIMARY KEY, btree (id) Foreign-key constraints: "admissions_userid_fkey" FOREIGN KEY (userid) REFERENCES users(id) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T17:02:45.023", "Id": "471905", "Score": "0", "body": "Could you please add the SQL for the definitions of all 3 tables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:05:52.843", "Id": "471913", "Score": "0", "body": "@pacmaninbw done" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-14T23:05:18.047", "Id": "240532", "Score": "1", "Tags": [ "python", "sql", "postgresql", "flask", "sqlalchemy" ], "Title": "querying users from table if user.id is found in another table" }
240532
<p>I am given the following problem to solve (This text is translated from Russian. So, there may be some translation issues): </p> <blockquote> <p><em>... Another method to draw from the normal distribution is to draw two independent random numbers from the uniform distribution x1, x2 ∈ [0:0, 1:0). Then apply the following transformation:</em></p> <p><span class="math-container">\$n_1 = \sqrt{-2\log{x_1}}\cos{2\pi x_2}\$</span></p> <p><span class="math-container">\$n_2 = \sqrt{-2\log{x_1}}\sin{2\pi x_2}\$</span></p> <p><em>resulting in two randomly independent numbers n<sub>1</sub>, n<sub>2</sub> from a normal distribution with zero expected value and unit variance.</em></p> <p><em>To change the distribution parameters to other parameters, e.g. the expected value for and the variance to, you should multiply the result of the draw by and add, i.e.</em></p> <p><span class="math-container">\$N(\mu, \sigma) = \sigma N(0, 1) + \mu\$</span></p> <p><em>In the equation above, N(μ, σ) is a random variable with normal distribution with expected value μ and variance σ.</em> </p> <p><em>According to the Maxwell distribution, each component (x, y or z) of the velocity vector <strong>v</strong> is a random variable from a normal distribution with zero expected value, and variance</em> <span class="math-container">\$\sqrt{\dfrac{k_B T}{m}}\$</span> <em>where m is the mass of the molecule, T is the temperature in Kelvin, k<sub>B</sub> is Boltzmann constant.</em></p> <p><em>Your task: Draw 10,000 velocity vectors for the N<sub>2</sub> nitrogen molecule at 300K. Calculate the average length of these vectors, and therefore the average value of the speed of the nitrogen molecule, using the formula:</em></p> <p><span class="math-container">\$\bar{v} = \dfrac{1}{N}\sum_{i=1}^N\sqrt{v_{x_i}^2 + v_{y_i}^2 + v_{z_i}^2}\$</span></p> </blockquote> <pre><code>using System; public class CommonDistributions { public static int Uniform(Random random, int n) { return (int)(random.NextDouble() * n); } public static double Uniform(Random random, double lo, double hi) { return lo + random.NextDouble() * (hi - lo); } public static double Gaussian(Random random) { double r, x, y; do { x = Uniform(random, -1.0, 1.0); y = Uniform(random, -1.0, 1.0); r = x * x + y * y; } while (r &gt;= 1 || r == 0); return x * Math.Sqrt(-2 * Math.Log(r) / r); } public static double Gaussian(Random random, double mu, double sigma) { return sigma * Gaussian(random) + mu; } } public class MaxwellBolzman { static double KB = 1.38064852e-23; static double MaxwellVariance(double mass, double temperature) { return Math.Sqrt(KB * temperature / mass); } static double MaxwellComponent(Random random, double mass, double temperature) { double mu = 0.0; double sigma = MaxwellVariance(mass, temperature); return CommonDistributions.Gaussian(random, mu, sigma); } public static double Maxwell(Random random, double mass, double temperature) { double one = MaxwellComponent(random, mass, temperature); double two = MaxwellComponent(random, mass, temperature); double thr = MaxwellComponent(random, mass, temperature); return Math.Sqrt(one * one + two * two + thr * thr); } } public static class MainClass { public static void Main(String[] args) { Random random = new Random(); const int N = 10000; const int T = 300;//300K const double mass = 28.02;//28.02 g/mol double sum = 0.0; for (int i = 1; i &lt; N; i++) { sum = sum + MaxwellBolzman.Maxwell(random, mass, T); } Console.WriteLine($"Maxwell-Boltzman Vector = {sum/N}"); string str = string.Empty; } } </code></pre> <p>Kindly, review the implementation.</p> <p>I am not sure about the values of temperature and the mass of Nitrogen 2. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T02:59:54.290", "Id": "471847", "Score": "2", "body": "You have some very overheated gas! 300K means 300 degrees on Kelvin scale (about 27 centigrades), not 300000." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T11:32:15.610", "Id": "471863", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T11:36:53.680", "Id": "471864", "Score": "0", "body": "@Mast, is it better now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T11:39:05.937", "Id": "471866", "Score": "0", "body": "No. Rule of thumb: the moment answers start coming in, you stop touching the code. Comments? Fine. Answers? No. No more code edits. If you have new code that you'd like reviewed, ask a follow-up question instead (this should all be explained in the link, please comment if anything is left unclear). I'd encourage you to wait at least 24h between asking questions though." } ]
[ { "body": "<ul>\n<li><p>The implementation of <code>Gaussian(Random random)</code> does not match the description. You should add the comment about the <a href=\"https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Polar_form\" rel=\"nofollow noreferrer\">polar form</a>. <em>I</em> know the equivalence. Some reviewers may not.</p></li>\n<li><p>Polar form comes with the price. The loop</p>\n\n<pre><code> do\n {\n x = Uniform(random, -1.0, 1.0);\n y = Uniform(random, -1.0, 1.0);\n r = x * x + y * y;\n }\n while (r &gt;= 1 || r == 0);\n</code></pre>\n\n<p>is potentially infinite. I'd be scared to see it in the production code.</p></li>\n<li><p>The Wiki article warns against the price of the basic form coming from the computation of <span class=\"math-container\">\\$\\sin\\$</span> and <span class=\"math-container\">\\$\\cos\\$</span>. I don't buy it. <code>sincos</code> is cheap. Thou shalt profile.</p></li>\n<li><p>The condition <code>r == 0</code> is pretty much guaranteed to fail, and I wouldn't trust the result of <code>Math.Log(r) / r</code> for really small <code>r</code>. Do not compare floating point values for equality. Chose an <span class=\"math-container\">\\$\\epsilon\\$</span>, and compare for <code>r &lt; eps</code>.</p></li>\n<li><p><code>Maxwell</code> calls <code>MaxwellComponent</code> three times, and each time <code>MaxwellComponent</code> computes the same <code>MaxwellVariance</code>. Seems excessive.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T06:39:28.403", "Id": "240543", "ParentId": "240535", "Score": "3" } } ]
{ "AcceptedAnswerId": "240543", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T01:06:58.087", "Id": "240535", "Score": "2", "Tags": [ "c#", "simulation" ], "Title": "Maxwell's distribution using Box-Muller transform" }
240535
<p>This is my code I wrote completely on my own. Its one of my first real programs that I have written using booleans, functions, and loops if anyone could give me some feedback about how its structured and how it runs when executed. Any feedback or constructive criticism would be greatly appreciated!</p> <pre><code># Imports random function for computer choice import random win_cnt = 0 losses_cnt = 0 # creates game function def game_main(): # Prompts user about game print(user_name + " will face off against the computer!\nIn this duel you and the computer will face off by taking turns battling the first to fall loses! ") print("Remember to use nearby cover and to reload BEFORE you attack!") # Creates variables needed for tracking computer and users health, ammo, and damage. user_potion = 0 com_potion = 0 user_ammo = 0 com_ammo = 0 user_heal = 10 com_heal = 10 user_atk = 10 com_atk = 10 user_HP = 30 com_HP = 30 # Battle loop that loops as long as both players health is above 0 while (user_HP &gt; 0 and com_HP &gt; 0): # Prompts user to choose a move user_move = int(input("What would you like to do? 1) Attack 2) Block 3) Reload 4) Heal? 5) Grab Bandage(potion)")) if user_move &gt; 5: #or str: print("INVALID INPUT! MUST BE 1-5") # Uses random to generate a random integer between 1 and 3 com_move = random.randint(1,5) if com_HP &gt; 50: # Branching if elif else statements that compare users and computers choice and decide outcome # if user attacks and has at least 1 ammo if user_move == 1 and user_ammo &gt; 0: user_ammo -= 1 if random.randint(0,100) &gt; 50: if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: user_HP = user_HP - com_atk com_HP = com_HP - user_atk com_ammo -= 1 print(user_name + " and the enemy both attack! You now have " , user_HP , "HP and " , user_ammo , "ammo! The enemy has" , com_HP , "HP!") else: com_HP = com_HP - user_atk com_ammo -= 1 print("You and the enemy both attack! The enemy misses but you hit him! He now has ", com_HP , "HP and " , " ammo!") elif com_move == 2: print("The enemy blocked your attack! You now have " , user_ammo , " ammo and he still has " , com_HP , "HP!") elif com_move == 3: com_HP = com_HP - user_atk com_ammo += 1 print(user_name + " attacks as the enemy reloads! He now has " , com_HP , "HP!") elif com_move == 4: com_HP = com_HP - user_atk print("The enemy attempts to use a healing potion! But you hit him! He now has " , com_HP , "!") else: com_HP = com_HP - user_atk com_potion += 1 print("The enemy grabs a health potion as you fire! You hit him! He now has " , com_HP , "HP!") else: if com_move == 1 and random.randint(0,100) &gt; 50: user_HP = user_HP - com_atk com_ammo -= 1 print("You missed and the enemy fires! You now have " , user_HP , "HP and " , user_ammo , "ammo!") elif com_move == 2: print("You missed and the enemy took cover! You now have " , user_ammo , "ammo!") elif com_move == 3: print("You missed and the enemy reloads!") elif com_move == 4: com_HP = com_HP + com_heal print("You missed! The enemy uses a healing potion! He now has " , com_HP , "HP!") else: com_potion += 1 print("You missed! The enemy quickly grabs a healing potion! You now have " , user_ammo , " ammo!") # If user attempts to attack with no ammo elif user_move == 1 and user_ammo &lt;= 0: if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: user_HP = user_HP - com_atk com_ammo -= 1 print("You must reload before attacking! The enemy fires! You now have" , user_HP , "HP!") else: com_ammo -= 1 print("You must reload before attacking! The enemy fires but misses!") elif com_move == 2: print("You must reload before attacking! The enemy takes cover!") elif com_move == 3: com_ammo += 1 print("You must reload before attacking! The enemy reloads!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print("You must reload before attacking! The enemy uses a health potion! He now has " , com_HP , "HP!") else: com_potion += 1 print("You must reload before attacking! The enemy grabs a health potion!") # If user blocks if user_move == 2: if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: com_ammo -= 1 print(user_name + " blocked the enemys attack! You still have " , user_HP , "HP!") else: print("The enemy fires as you run for cover! His attack misses!") elif com_move == 2: print(user_name + " and the enemy both block!") elif com_move == 3: com_ammo += 1 print(user_name + " finds cover as the enemy reloads!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print(user_name + " runs for cover as the enemy uses a health potion! He now has " , com_HP , "HP!") else: com_potion += 1 print("You run for cover as the enemy grabs a potion!") # If user reloads if user_move == 3: user_ammo += 1 if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: user_HP = user_HP - com_atk com_ammo -= 1 print(user_name + " reloads as the enemy attacks! You now have " , user_HP, "HP and " , user_ammo , " ammo!") else: print("You reload as the enemy attacks! His attack misses! You know have" , user_ammo , " ammo!") elif com_move == 2: print(user_name + " reloads as the enemy finds cover! You now have " , user_ammo , " ammo!") elif com_move == 3: com_ammo += 1 print(user_name + " and the enemy both reload! You now have " , user_ammo , " ammo!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print("You reload as the enemy uses a health potion! He now has " , com_HP , "HP! You have " , user_ammo , " ammo!") else: com_potion += 1 print("You reload as the enemy grabs a potion! You now have " , user_ammo , " ammo!") # If user uses health potion and has at least one if user_move == 4 and user_potion &gt; 0: user_potion -= 1 if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: com_ammo -= 1 print("You use a health potion as the enemy fires and hits! You have " , user_HP , "HP!") else: user_HP = user_HP + user_heal com_ammo -=1 print("You use a health potion as the enemy fires! They miss and you gain +10HP! You now have " , user_HP , "HP!") elif com_move == 2: user_HP = user_HP + user_heal print("The enemy runs for cover as you quickly drink a healing potion! You gain +10HP! You now have " , user_HP , "HP!") elif com_move == 3: user_HP = user_HP + user_heal com_ammo += 1 print("The enemy reloads as you drink a healing potion! You now have" , user_HP , "HP!") elif com_move == 4: user_HP = user_HP + user_heal com_HP = com_HP + com_heal com_potion -= 1 print("You and the enemy both drink healing potions! You now have " , user_HP , "HP!") else: user_HP = user_HP + user_heal print("You drink a healing potion and gain +10HP! You now have " , user_HP , "HP and" , user_potion , " potions! The enemy grabs a healing potion!") # If user tries to use potion but has none elif user_move == 4 and user_potion &lt;= 0: if com_move == 1 and com_ammo &gt; 0: if random.randint(0,100) &gt; 50: com_ammo -= 1 user_HP = user_HP - com_atk print("You attempt to use a health potion but have none! The enemy fires and hits! You now have " , user_HP , "HP!") else: com_ammo -=1 print("You attempt to use a health potion as the enemy fires! You have no more potions but their attack miss!") elif com_move == 2: print("The enemy runs for cover as you attempt to drink a healing potion! You have no potions!") elif com_move == 3: com_ammo += 1 print("The enemy reloads as you reach for a healing potion! You have none!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print("You are out of potions! The enemy quickly drinks a healing potion!") else: print("You attempt to drink a healing potion but have none! The enemy grabs a healing potion!") if user_move == 5: user_potion += 1 if com_move == 1 and com_ammo &gt; 0: com_ammo -= 1 if random.randint(0,100) &gt; 50: user_HP = user_HP - com_atk print("You grab a potion as the enemy fires! He hits! You now have " , user_HP , "HP and " , user_potion , " potions!") else: print("You grab a potion as the enemy fires! He misses! You now have " , user_potion , " potions!") elif com_move == 2: print("You grab a potion as the enemy runs for cover! You now have " , user_potion , " potions!") elif com_move == 3: com_ammo += 1 print("You grab a healing potion as the enemy reloads!") elif com_move == 4: com_HP = com_HP + com_heal com_potion -= 1 print("You grab a potion a the enemy uses a potion! You now have " , user_potion , " potions and he has " , com_HP , "HP!") else: com_potion += 1 print("You and the enemy both grab a potion! You now have " , user_potion , " potions!") # If user or computers health falls to 0 than game ends and prompts user to play again else: print("GAME OVER!") if com_HP &lt;= 0 and user_HP &lt;= 0: print("You killed eachother...") replay_game() elif com_HP &lt;= 0: win() replay_game() elif user_HP &lt;= 0: losses() replay_game() # Declaration for replay_game function def replay_game(): # Prompts user to play again and saves value in variable game_loop game_loop = input("Would you like to play again? (Y/N)") # If game_loop variable is equal to Y then replay if game_loop == "Y" or "y": game_main() # If game_loop is anything else then exit else: return # Declaration for the win function def win(): # Declares variable win_cnt as global and increments value by +1 global win_cnt win_cnt += 1 print("You won! You have " , win_cnt , " wins and " , losses_cnt , " losses!") # Declaration of the the losses function def losses(): # Declares variable losses_cnt as global and increments its value by +1 global losses_cnt losses_cnt += 1 print("You lost and now have " , losses_cnt , " losses and " , win_cnt , " wins!") # Welcome user and prompt for their name print("Welcome to the duel!") user_name = input("What is your name? ") # Begin game function game_main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:01:54.593", "Id": "471889", "Score": "1", "body": "Hey, welcome to Code Review! I edited your title to include only what your code achieves and not so much what you want out of a review (we all want constructive criticism and feedback here)." } ]
[ { "body": "<p>First of all, there is a syntax error:</p>\n\n<pre><code>if com_HP &gt; 50: # &lt;-- if statement without body leads to indentation error\n# some comment\nif user_move == 1 and user_ammo &gt; 0:\n # some more code\n</code></pre>\n\n<p>Moreover there are a few style issues with your code:</p>\n\n<p><strong>Comments</strong></p>\n\n<p>Always indent your comments on the same level as the code you are referring to, otherwise it is very confusing.</p>\n\n<pre><code># Declaration for replay_game function\ndef replay_game():\n# Prompts user to play again and saves value in variable game_loop \n game_loop = input(\"Would you like to play again? (Y/N)\")\n# If game_loop variable is equal to Y then replay \n if game_loop == \"Y\" or \"y\":\n game_main()\n</code></pre>\n\n<p>Indent your comments like this:</p>\n\n<pre><code># Declaration for replay_game function\ndef replay_game():\n # Prompts user to play again and saves value in variable game_loop \n game_loop = input(\"Would you like to play again? (Y/N)\")\n # If game_loop variable is equal to Y then replay \n if game_loop == \"Y\" or \"y\":\n game_main()\n</code></pre>\n\n<p><strong>Paragraphs</strong></p>\n\n<p>Please use paragraphs between functions, also when there is a comment in between. The official <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">python style guide</a> states:</p>\n\n<blockquote>\n <p>Surround top-level function and class definitions with two blank lines.</p>\n</blockquote>\n\n<p><strong>Avoid top level code</strong></p>\n\n<p>Top level code is executed every time this module is loaded, which is probably not what you want when importing this module from another script. That's why you should surround your top level code with:</p>\n\n<pre><code>if __name__ == '__main__':\n # Welcome user and prompt for their name\n print(\"Welcome to the duel!\")\n user_name = input(\"What is your name? \")\n # Begin game function\n game_main()\n</code></pre>\n\n<p><strong>User input</strong></p>\n\n<p>You don't handle the case of invalid user input, e.g. a user enters a name instead of a number. This can be handled with an extra function to get proper user input.</p>\n\n<pre><code>def get_user_move():\n try: \n user_move = int(input(\"...\"))\n except ValueError:\n print(\"Invalid Input: Not a number!\") \n # validate input\n if user_move &lt; 0 or user_move &gt; 5:\n print(\"Invalid Input: Must be 1-5\")\n # ask the player again\n return get_user_move()\n else:\n return user_move\n</code></pre>\n\n<p><strong>Structure</strong></p>\n\n<p>Structure your game as a <code>class</code> e.g.</p>\n\n<pre><code>class Game:\n def __init__(self, username):\n self.username = username\n self.user_potion = 0\n self.com_potion = 0\n # etc.\n\n def start(self):\n # prompt user to choose a move\n user_move = get_user_move()\n # Uses random to generate a random integer between 1 and 5\n com_move = random.randint(1,5)\n if user_move == 1:\n user_attack(com_move)\n if user_move == 2:\n user_block(com_move)\n # etc.\n\n def user_attack(com_move):\n # handle user attack\n\n # etc. \n</code></pre>\n\n<p>In your main part you can now instantiate your game as an object and run the <code>start</code> method, e.g.</p>\n\n<pre><code>if __name__ == '__main__':\n # Welcome user and prompt for their name\n print(\"Welcome to the duel!\")\n user_name = input(\"What is your name? \")\n game = Game(user_name)\n game.start()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:51:02.233", "Id": "471903", "Score": "0", "body": "Thank you this I exactly the feedback I needed thank you so much for taking the time! I will defiantly work through everything you mentioned and practice implementing them! I will be posting an updated program once I have a cleaner and still working copy!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:53:39.993", "Id": "240568", "ParentId": "240539", "Score": "4" } }, { "body": "<p>Welcome to Code Review. Great first question!</p>\n\n<h2>Things to maintain</h2>\n\n<p>You have some good habits already; keep them up:</p>\n\n<ul>\n<li>Commenting code</li>\n<li>Reasonable variable and function names</li>\n</ul>\n\n<p>There are some other things to improve:</p>\n\n<h2>Whitespace</h2>\n\n<p>Programmers (sometimes snobbishly) think of code as poetry that should be broken up into <a href=\"https://en.wikipedia.org/wiki/Stanza\" rel=\"nofollow noreferrer\">stanzas</a>, basically paragraphs of related statements. This helps break up the code for it to be more legible for humans without having any effect on Python's interpretation of the code. For example, the first few lines of your program could be</p>\n\n<pre><code># Imports random function for computer choice\nimport random\n\n\nwin_cnt = 0\nlosses_cnt = 0\n\n\ndef game_main():\n \"\"\"\n Game function\n \"\"\"\n\n # Prompts user about game \n print(user_name + \" will face off against the computer!\\nIn this duel you and the computer will face off by taking turns battling the first to fall loses! \")\n print(\"Remember to use nearby cover and to reload BEFORE you attack!\")\n\n # Variables needed for tracking computer and users health, ammo, and damage.\n user_potion = 0\n com_potion = 0\n user_ammo = 0\n com_ammo = 0\n user_heal = 10\n com_heal = 10\n user_atk = 10\n com_atk = 10\n user_HP = 30\n com_HP = 30\n\n # Battle loop that loops as long as both players health is above 0 \n # ...\n</code></pre>\n\n<p>Note the use of triple-quotes for a standard function docstring, and standard indentation of comments at the same level as the corresponding code.</p>\n\n<p>Have a read through <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, and/or use pretty much any modern Python IDE that has auto-linting (PyCharm is my usual go-to); you will find many other suggestions there about whitespace in your code.</p>\n\n<h2>String interpolation</h2>\n\n<pre><code>print(user_name + \" will face off against the computer!\\nIn this duel you and the computer will face off by taking turns battling the first to fall loses! \")\n</code></pre>\n\n<p>can be more easily coded as</p>\n\n<pre><code>print(\n f'{user_name} will face off against the computer!\\n'\n 'In this duel you and the computer will face off '\n 'by taking turns battling the first to fall loses! '\n 'Remember to use nearby cover and to reload BEFORE '\n 'you attack!'\n)\n</code></pre>\n\n<p>The <code>f</code> does the interpolation to allow for the <code>{}</code> field insertion, and the consecutive strings use implicit string literal concatenation to keep the line length down.</p>\n\n<h2>Parentheses</h2>\n\n<p>This is not C/Java/C#/etc., so this:</p>\n\n<pre><code>while (user_HP &gt; 0 and com_HP &gt; 0):\n</code></pre>\n\n<p>does not need parentheses.</p>\n\n<h2>Input validation</h2>\n\n<pre><code> user_move = int(input(\"What would you like to do? 1) Attack 2) Block 3) Reload 4) Heal? 5) Grab Bandage(potion)\"))\n if user_move &gt; 5: #or str:\n print(\"INVALID INPUT! MUST BE 1-5\")\n</code></pre>\n\n<p>What if someone inputs 0? Or \"banana\"? You will want to change this to (a) catch a <code>ValueError</code>, and also <code>if not (1 &lt;= input &lt;= 5)</code>.</p>\n\n<p>That aside, you should also consider making an <code>enum.Enum</code> to represent these choices, for many reasons - symbolic references to the numbers will make your code more legible; validation will be easier; etc.</p>\n\n<h2>Random</h2>\n\n<p>This:</p>\n\n<pre><code>random.randint(0,100) &gt; 50\n</code></pre>\n\n<p>technically does not need to have a range of 100. You could use an upper limit of 2, or even</p>\n\n<pre><code>random.choice((True, False))\n</code></pre>\n\n<h2>Functions</h2>\n\n<p><code>game_main</code> is very long. Consider pulling out chunks of it into subroutines - perhaps one for every different possible type of user move.</p>\n\n<h2>No-op return</h2>\n\n<p>This:</p>\n\n<pre><code>else:\n return\n</code></pre>\n\n<p>does not do anything and can be removed.</p>\n\n<h2>Procedure</h2>\n\n<p>I encourage you to work on your code based on the feedback you get, ensure that your code is still working, and then post another question with your new, proposed code once you are satisfied that you have received enough responses on this question. Given that you are a beginner, there are many things that you can do to this code to improve it, and it wouldn't be very feasible to tackle it all at once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:50:34.300", "Id": "471902", "Score": "0", "body": "Thank you this I exactly the feedback I needed, thank you so much for taking the time! I will defiantly work through everything you mentioned and practice implementing them! I will be posting an updated program once I have a cleaner and still working copy!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:13:53.163", "Id": "240572", "ParentId": "240539", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T05:22:52.107", "Id": "240539", "Score": "7", "Tags": [ "python", "beginner", "battle-simulation" ], "Title": "My first battle simulator" }
240539
<p>I just started learning C fundamentals and started to write a List that is limited to integers for the beginning and has dynamic memory allocation according to its content.</p> <p>I've written custom simple assertion functions that revealed, that upon reallocating less memory when shrinking the list, it is still possible to access the removed element - my guess is that there's no need to move the pointer when shrinking its allocation and <code>realloc()</code> does not free the memory? Is it right? Is this code C-ish? Thanks for your reviews!</p> <p><strong>list.h</strong></p> <pre><code>typedef struct { long size; int* elements; } intlist; /** * Creates an empty list */ intlist il_create(); /** * Appends a value to a list and returns its index * * @return index of the item */ long il_push(intlist*, int); /** * Retrieves a value by its index * * @return item of the list */ int il_get(intlist*, long); /** * Removes the last element */ void il_pop(intlist*); </code></pre> <p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include "list.h" void assert(char* msg, long actual, char expression) { static int assert_nr = 0; ++assert_nr; if(!expression) { fprintf(stderr, "[ERROR] Assertion %d failed\n", assert_nr); fprintf(stderr, "[ERROR] Expected: %s\n", msg); fprintf(stderr, "[ERROR] Actual: %ld\n", actual); } } void assertEquals(char *msg, long actual, long expected) { assert(msg, actual, actual == expected); } void assertNotEquals(char *msg, long actual, long expected) { assert(msg, actual, actual != expected); } int main(int argc, char const *argv[]) { // Create an empty list intlist list = il_create(); { // List is initially empty assertEquals("Size is 0", list.size, 0); } { // The item is added to the list int index = il_push(&amp;list, 123); int item = il_get(&amp;list, 0); assertEquals("Size is 1", list.size, 1); assertEquals("First index is 0", index, 0); assertEquals("First element is 123", item, 123); } { // Another item is added to the list int index = il_push(&amp;list, 456); int item2 = il_get(&amp;list, 1); assertEquals("Size is 2", list.size, 2); assertEquals("Second index is 1", index, 1); assertEquals("Second element is 456", item2, 456); } { // Last element is removed and thus last = first il_pop(&amp;list); assertEquals("Size is 1", list.size, 1); int first = il_get(&amp;list, 0); int last = il_get(&amp;list, list.size-1); assertEquals("First item is 123", first, 123); assertEquals("Last element is the first one", last, first); int deleted = il_get(&amp;list, 1); assertNotEquals("Deleted item is not 456", deleted, deleted != 456); } { // Removed element is overwritten when pushing a new one int index = il_push(&amp;list, 789); int item = il_get(&amp;list, index); assertEquals("Index is 1", index, 1); assertEquals("Element is 789", item, 789); } return 0; } intlist il_create() { return (intlist){.size=0}; } long il_push(intlist* list, int value) { int index = list-&gt;size; list-&gt;elements = realloc(list-&gt;elements, ++list-&gt;size * sizeof(int)); *(list-&gt;elements + index) = value; return index; } int il_get(intlist* list, long index) { return *(list-&gt;elements + index); } void il_pop(intlist* list) { list-&gt;size -= 1; *(list-&gt;elements + list-&gt;size) = 0; list-&gt;elements = realloc(list-&gt;elements, list-&gt;size * sizeof(int)); } </code></pre>
[]
[ { "body": "<p>It does. You directly assign <code>list-&gt;elements</code> to the result of <code>realloc</code> which can return <code>NULL</code>, in which case your original array is leaked (but it's okay since you immediately assign a value to a <code>NULL</code>-based array after that, which is UB).</p>\n\n<p>Few more observations.</p>\n\n<ol>\n<li><p>The list itself can only be operated via its public interface that consists of methods that accept list object by pointer. Perhaps it makes sense to return by pointer from constructor, too; then you can make <code>list</code>'s implementation an opaque struct, all its fields will be private.</p></li>\n<li><p>You should define a destructor to release the array, that otherwise (currently) leaks.</p></li>\n<li><p>Your current allocation strategy is inefficient. Reallocating the whole array per each new element raises <code>push</code>'s complexity to O(N), so creating an array of N elements takes O(N²) time. A traditional approach to deal with it is adding <code>capacity</code> to the list object; <code>capacity</code> equals to the size of allocated space and grows exponentially: when list's size reaches capacity, on next element push capacity doubles, thus reducing push complexity to ammortized O(1).</p></li>\n<li><p>Elements are stored in a contiguous array, perhaps a better descriptive name? Traditionally, <code>list</code> is associated with linked lists in C family.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T13:33:14.110", "Id": "471874", "Score": "0", "body": "Thanks a lot for taking the time and effort! But what stands UB for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T13:33:57.327", "Id": "471875", "Score": "0", "body": "And do you have any suggestions on how to test the leaking, so that I am able to write it test-driven?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T21:47:40.963", "Id": "471958", "Score": "0", "body": "Undefined behaviour. Unsure about testing, running a static analysis perhaps?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T08:41:03.017", "Id": "240547", "ParentId": "240545", "Score": "4" } }, { "body": "<p>Some stuff after <a href=\"https://codereview.stackexchange.com/a/240547/29485\">@bipll</a> good answer.</p>\n\n<p><strong>size type</strong></p>\n\n<p>The choice for <code>long</code>, as in member <code>long size;</code>, is arbitrary. Could have been <code>int</code>, <code>char</code> or what ever.</p>\n\n<p>Yet size code is making an array, consider using the <em>unsigned</em> integer type <code>size_t</code>. That is the not too big/not too small type for array sizing and indexing.</p>\n\n<p><strong>const</strong></p>\n\n<p>Functions like <code>il_get()</code> that do not change the list are better with <code>const</code> to 1) indicate no change will occur, 2) helps some lessor compiler to make better code, 3) helps convey to the user that the list is unchanged.</p>\n\n<pre><code>// int il_get(intlist*, long);\nint il_get(const intlist*, long);\n</code></pre>\n\n<p><strong>Named parameters</strong></p>\n\n<p>Often a user of this code is only interested in the .h file. Providing informative names there helps them.</p>\n\n<pre><code>// long il_push(intlist*, int);\nlong il_push(intlist *list, int value);\n</code></pre>\n\n<p><strong>.h include guard</strong></p>\n\n<p>To prevent re-evaluation of .h code: <a href=\"https://en.wikipedia.org/wiki/Include_guard#Use_of_#include_guards\" rel=\"nofollow noreferrer\">include_guards</a></p>\n\n<p><strong>No error checking</strong></p>\n\n<p>List of potential failures. If code should check them or not is up to you.</p>\n\n<pre><code>(Re-)allocation failure. (recommend checking)\nPassing in a null pointer for `intlist*`\n</code></pre>\n\n<p><strong>list.c</strong></p>\n\n<p>I expected the <code>il_...()</code> definitions in their own <code>list.c</code> file, not <code>main.c</code>.</p>\n\n<p><strong>Uniform name space</strong></p>\n\n<p>Consider a common prefix for all external symbols, perhaps <code>il_</code>.</p>\n\n<pre><code>list.h --&gt; il.h\nlist.c --&gt; il.c\n\nintlist --&gt; il_type;\n\nil_...() --&gt; the same ( good usage here)\n</code></pre>\n\n<p><strong>Weak prototype</strong></p>\n\n<p>The declaration of <code>il_create()</code> should include <code>void</code>, else <code>il_create(42)</code> and <code>il_create(\"Hello World\", 867-5309)</code> will pass undetected as an error.</p>\n\n<pre><code>// intlist il_create();\nintlist il_create(void);\n</code></pre>\n\n<p><strong>Include order</strong></p>\n\n<p>OP's include order will fail to detect if <code>\"list.h\"</code> can not stand on its own without <code>&lt;stdio.h&gt;, &lt;stdlib.h&gt;</code></p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include \"list.h\"\n</code></pre>\n\n<p>I recommend the above in all files except <code>list.c</code>, so it can insure no include dependency.</p>\n\n<pre><code>#include \"list.h\"\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T07:04:21.880", "Id": "472113", "Score": "0", "body": "That sure is some important information my book on ANSI C is missing. Thanks for also including best practices!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T07:06:01.493", "Id": "472114", "Score": "0", "body": "Is there any meaningful difference in suggestion 1 and 3 of the **const** part?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T13:44:20.673", "Id": "472170", "Score": "0", "body": "@Jazzschmidt Similar: 1) is an enforcement by the compiler. 2) information to the user. I could have worded different." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T21:55:05.947", "Id": "240651", "ParentId": "240545", "Score": "2" } } ]
{ "AcceptedAnswerId": "240547", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T07:33:29.520", "Id": "240545", "Score": "3", "Tags": [ "c", "array" ], "Title": "Expandable integer List in C" }
240545
<p>I simply made this for practice. But I want to know if it can be used in the realworld or not. Please point out any bad programming practices and how I can change them and look out for them next time. Your advice or tip will be the invaluable rain on my deadly isolated programming land.</p> <pre><code>import os import hashlib from base64 import b64encode, b64decode def convert_to_bytes(value, value_name): if isinstance(value, str): return value.encode('UTF-8') else: raise ValueError('%s must be string or bytes' % value_name) def derive_passhash(password, hash_name='sha512', salt=None, iterations=100000): '''This function returns str type password_hash. hash contains hash_name, iterations, salt, derived_key -&gt; [hash_name] $ [iterations] $$ [salt] $s_k$ [derived_key] ''' if salt is None: salt = os.urandom(32) if not isinstance(salt, bytes): salt = convert_to_bytes(salt, 'salt') if not isinstance(password, bytes): password = convert_to_bytes(password, 'password') if not isinstance(iterations, int): if isinstance(iterations, str) and iterations.isnumeric(): iterations = int(iterations) else: print('iterations must be integer.') raise ValueError # derive passhash try: d_key = hashlib.pbkdf2_hmac(hash_name, password, salt, iterations) del password # maybe it can help to make more secure? except ValueError as error: print('[!] Error cused %s' % error) # log(error) # put hash_name, salt, iterations and derived key together # and encode to base64 format. pre_v = '$'.join((hash_name, str(iterations))).encode('utf-8') end_v = b'$s_k$'.join((salt, d_key)) total_value = b'$$'.join((pre_v, end_v)) user_hash = b64encode(total_value).decode(encoding='utf-8') return user_hash def check_password(user_hash, asserted_pw): if not isinstance(asserted_pw, bytes): asserted_pw = convert_to_bytes(asserted_pw, 'password') user_hash = b64decode(user_hash.encode('utf-8')) h_i, s_k = user_hash.split(b'$$') hash_name, iterations = h_i.decode('utf-8').split('$') salt, key = s_k.split(b'$s_k$') try: asserted_key = hashlib.pbkdf2_hmac(hash_name, asserted_pw, salt, int(iterations)) del asserted_pw except ValueError as error: print('[!] Error cused %s' % error) if key == asserted_key: return True else: return False </code></pre>
[]
[ { "body": "<h2>Typo</h2>\n\n<p><code>Error cused</code> -> <code>Error caused</code></p>\n\n<h2>Memory security</h2>\n\n<pre><code>del password # maybe it can help to make more secure?\n</code></pre>\n\n<p>It's not harmful, but it probably also won't help much. Your theory seems to be that if an outside attacker gains access to your program's memory (which is already instant doom), that calling <code>del</code> will have removed the plaintext password from memory thus reducing the impact of an attack. Have a read through an explanatory article like <a href=\"https://rushter.com/blog/python-garbage-collector/\" rel=\"nofollow noreferrer\">Python Garbage Collector</a>, which says that</p>\n\n<blockquote>\n <p>you can use the <code>del</code> statement that removes a variable and its reference (not the object itself) [...] The <code>del</code> statement removes the references to our objects (i.e., decreases reference count by 1). After Python executes the del statement, our objects are no longer accessible from Python code. However, such objects are still sitting in the memory</p>\n</blockquote>\n\n<p><code>del</code> does <a href=\"https://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-large-object.htm\" rel=\"nofollow noreferrer\">not force garbage collection</a>. To do that, you would in theory need to call <code>gc.collect()</code>.</p>\n\n<p>The <em>most</em> that <code>del</code> would immediately do is mitigate an attack on access to the <code>locals</code> dictionary. Again, if such an attack is possible, you have much bigger problems on your hands.</p>\n\n<h2>Boolean expressions</h2>\n\n<pre><code>if key == asserted_key:\n return True\nelse:\n return False\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return key == asserted_key\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T15:31:15.637", "Id": "240567", "ParentId": "240546", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T08:05:05.853", "Id": "240546", "Score": "3", "Tags": [ "python", "beginner" ], "Title": "python password hashing" }
240546
<p>I am looking for some review on the code I am about to provide below.</p> <p>I'd like to improve my coding in general and happy to hear any comments from the community.</p> <p>The goal of this code is simply load <code>dataGridView1</code> with some data from MySQL and Refresh it with a click of a button.</p> <p>I have not yet tried using automatic refresh. But will look into it soon or later.</p> <p><strong>Code:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; using System.Configuration; namespace Final_Version { public partial class Form19 : Form { public Form19() { InitializeComponent(); } private void Form19_Load(object sender, EventArgs e) { RefreshGridHistory(); } string connString = ConfigurationManager.ConnectionStrings["Final_Version.Properties.Settings.technicalConnectionString"].ConnectionString; public void RefreshGridHistory() { // MySQL connection string using (var conn = new MySqlConnection(connString)) { //Seelct query using (var mySqlDataAdapter = new MySqlDataAdapter("select r.date_requested, u.username, r.product_code, r.customer_code " + " from verify v join request r on v.request_id = r.id join users u on r.user_id = u.id join" + " users u2 on v.user_id = u2.id where v.status = 'Verified' or v.status = 'Rejected';", conn)) { using (var dataSet = new DataSet()) { DataSet DS = new DataSet(); mySqlDataAdapter.Fill(DS); //Assign headers to Data Grid View dataGridView1.DataSource = DS.Tables[0]; dataGridView1.Columns[0].HeaderText = "Date Requested"; dataGridView1.Columns[1].HeaderText = "User Requested"; dataGridView1.Columns[2].HeaderText = "Product Code"; dataGridView1.Columns[3].HeaderText = "Customer Code"; } } } } private void button1_Click(object sender, EventArgs e) { RefreshGridHistory(); } } } </code></pre>
[]
[ { "body": "<p><strong>Single responsibility</strong></p>\n\n<p>Move the query logic to different class, let's call it DAL for example. In this implementation you are returning DataTable. Returning a list of some class instead will make sure changes in the DB query/ schema will not affect the GUI but only the DAL class. </p>\n\n<p><strong>LINQ</strong></p>\n\n<p>You can write the sql query using linq and then if you have syntax errors they will be cache during completion</p>\n\n<p><strong>Grid</strong></p>\n\n<p>I wonder why you set the columns headers multiple times?</p>\n\n<p>Think about this scenario: when the form loads, If the query return 0 results or there is a connection problem, how the grid will look like? </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T13:04:07.540", "Id": "471872", "Score": "0", "body": "Hi, thanks for the review! I will look into LINQ and also regarding the Grid - what do you mean I set the columns multiple times? I set it once?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T14:36:07.357", "Id": "471885", "Score": "0", "body": "Sorry, I meant the columns headers" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T12:31:28.813", "Id": "240557", "ParentId": "240550", "Score": "2" } }, { "body": "<h2>A couple remarks</h2>\n\n<ul>\n<li>You don't need a dataset here, just a datatable. Datasets come into play when you have multiple tables with relationships. </li>\n<li>I would rather set the headers and the overall layout for the <code>datagridview</code> <strong>early</strong>, for example right after <code>InitializeComponent()</code> </li>\n<li>But in fact I would not even do this in code. I would simply customize the control in the form layout window, and set all properties that can defined before runtime.</li>\n<li>Good <strong>naming conventions</strong> are important - <code>Form19</code> is not a good, descriptive name. Nor is <code>dataGridView1</code> or <code>button1</code>. These are default names.</li>\n<li>This code may not be complete, but this form has several imports that are unneeded: Drawing, Threading,... don't add more than what is strictly needed, that only clutters the code for nothing. Yes, using LINQ would be a good idea, if not here it will be useful at other places.</li>\n<li>The <strong>scope</strong> of some variables can be moved up to form level, for example <code>DS</code>, because in another procedure you might want to check the number of rows retrieved</li>\n</ul>\n\n<hr>\n\n<p>I don't understand why you have:</p>\n\n<pre><code>using (var dataSet = new DataSet())\n{\n DataSet DS = new DataSet();\n mySqlDataAdapter.Fill(DS);\n\n //Assign headers to Data Grid View\n ...\n}\n</code></pre>\n\n<p>What you effectively use is variable <code>DS</code>, not <code>dataSet</code> (by the way <code>dataSet</code> is a terrible name for a dataset...be careful with <strong>reserved keywords</strong>)</p>\n\n<hr>\n\n<p>The string concatenation for the SQL is ugly. LINQ is an option. Another option for multi-line string literals is a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim\" rel=\"nofollow noreferrer\">verbatim string</a> using the <code>@</code> symbol so you can define a variable for your SQL like this:</p>\n\n<pre><code>string sql = @\"SELECT r.date_requested, u.username, r.product_code, r.customer_code \nFROM verify v JOIN request r ON v.request_id = r.id JOIN users u ON r.user_id = u.id JOIN \nusers u2 on v.user_id = u2.id\nWHERE v.status = 'Verified' OR v.status = 'Rejected';\";\n</code></pre>\n\n<p>Even in this day and age of large monitors, I think it is reasonable to limit column width to around 80 - your code extends to column 163. It is not convenient for the human eye to scan/scroll long lines of text.</p>\n\n<hr>\n\n<p>Final point: comments. You have some comments in your code but they are not helpful:</p>\n\n<pre><code>// MySQL connection string\nusing (var conn = new MySqlConnection(connString))\n\n//Seelct query\nusing (var mySqlDataAdapter...\n</code></pre>\n\n<p>It is quite obvious what these lines do, I have not learned or remembered anything noteworthy from your comments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T07:06:37.587", "Id": "471986", "Score": "0", "body": "Thanks for the review! I will get this on board!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:04:42.417", "Id": "471995", "Score": "0", "body": "Hi, is LINQ only for SQL Server? Because I am using MySQL" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T14:36:00.410", "Id": "472043", "Score": "0", "body": "No, in fact LINQ can even be used without a database, an iterator of some sort will do, could be a collection or another data structure [Language Integrated Query (LINQ)](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:16:06.130", "Id": "240573", "ParentId": "240550", "Score": "2" } } ]
{ "AcceptedAnswerId": "240573", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T10:29:47.490", "Id": "240550", "Score": "2", "Tags": [ "c#" ], "Title": "Loading and Refreshing DataGrid in WinForms using C# .Net Framework" }
240550
<p><a href="https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/</a></p> <p>please review for performance, the adjacency list is the problematic part for me.</p> <blockquote> <p>Given a sorted dictionary (array of words) of an alien language, find order of characters in the language. Examples:</p> <p>Input: words[] = {"baa", "abcd", "abca", "cab", "cad"} Output: Order of characters is 'b', 'd', 'a', 'c' Note that words are sorted and in the given language "baa" comes before "abcd", therefore 'b' is before 'a' in output. Similarly we can find other orders.</p> <p>Input: words[] = {"caa", "aaa", "aab"} Output: Order of characters is 'c', 'a', 'b'</p> </blockquote> <pre><code>using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace GraphsQuestions.Properties { /// &lt;summary&gt; /// https://www.geeksforgeeks.org/given-sorted-dictionary-find-precedence-characters/ /// &lt;/summary&gt; [TestClass] public class AlienDictionaryTest { [TestMethod] public void ExampleTest1() { string[] words = {"baa", "abcd", "abca", "cab", "cad"}; int numOfChars = 4; var expected = new List&lt;char&gt;{'b', 'd', 'a', 'c'}; Solution solution = new Solution(numOfChars, words); List&lt;char&gt; res = solution.Sort(); CollectionAssert.AreEqual(expected,res ); } [TestMethod] public void ExampleTest2() { string[] words = { "caa", "aaa", "aab" }; int numOfChars = 3; var expected = new List&lt;char&gt; { 'c','a','b' }; Solution solution = new Solution(numOfChars, words); List&lt;char&gt; res = solution.Sort(); CollectionAssert.AreEqual(expected, res); } } public class Solution { private Graph _graph; public Solution(int numOfChars, string[] words) { _graph = new Graph(numOfChars); for (int i = 0; i &lt; words.Length-1; i++) { string word1 = words[i]; string word2 = words[i + 1]; for (int j = 0; j &lt; Math.Min(word1.Length, word2.Length); j++) { if (word1[j] != word2[j]) { _graph.AddEdge(word1[j] - 'a', word2[j] - 'a'); break; } } } } public List&lt;char&gt; Sort() { return _graph.TopologicalSort(); } } public class Graph { private List&lt;List&lt;int&gt;&gt; _adjList; // for each letter we create a vertex public Graph(int numOfchars) { _adjList = new List&lt;List&lt;int&gt;&gt;(); for (int i = 0; i &lt; numOfchars; i++) { _adjList.Add(new List&lt;int&gt;()); } } /// &lt;summary&gt; /// run through the entire adj list /// and run DFS from each node to their neighbors /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public List&lt;char&gt; TopologicalSort() { var stack = new Stack&lt;int&gt;(); bool[] visited = new bool[_adjList.Count]; for (int i = 0; i &lt; _adjList.Count; i++) { if (!visited[i]) { DFS(i, visited, stack); } } var res = new List&lt;char&gt;(); while (stack.Count &gt; 0) { res.Add((char)(stack.Pop() +'a')); } return res; } /// &lt;summary&gt; /// mark the current node as visited and recurs to the adj nodes /// &lt;/summary&gt; /// &lt;param name="index"&gt;&lt;/param&gt; /// &lt;param name="visited"&gt;&lt;/param&gt; /// &lt;param name="stack"&gt;&lt;/param&gt; private void DFS(int index, bool[] visited, Stack&lt;int&gt; stack) { visited[index] = true; foreach (var node in _adjList[index]) { if (!visited[node]) { DFS(node, visited, stack); } } stack.Push(index); } /// &lt;summary&gt; /// add an edge between char1 to char2 /// this will mark the adj between them /// &lt;/summary&gt; /// &lt;param name="char1"&gt;&lt;/param&gt; /// &lt;param name="char2"&gt;&lt;/param&gt; public void AddEdge(int char1, int char2) { _adjList[char1].Add(char2); } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T11:45:35.760", "Id": "240554", "Score": "1", "Tags": [ "c#", "programming-challenge", "depth-first-search", "topological-sorting" ], "Title": "GeeksForGeeks: Alien dictionary C#" }
240554
<p>I have written a little Paint-Program in HTML. You can also save and load your wonderful paintings. My code works, but my heart says that my code is not so beautiful. I dont use JS/HTML/CSS very often and thats why I dont know how to write clean JS-Code, but I want to know that. Javascript seems to provide a thousand ways to express your ideas sometimes. I dont know that from Java (I usually write Java Code). How would you improve the code? I am very interested!</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>/** * user can choose color by hisself **/ // global color variable let currentColor = "black"; function createColorTable(colorStringArray) { let colorTable = document.getElementById("colorTable"); for (i = 0; i &lt; colorStringArray.length; i++) { let colorRow = document.createElement("tr"); let colorBox = document.createElement("td"); colorBox.value = colorStringArray[i]; colorBox.style.backgroundColor = colorStringArray[i]; colorBox.onclick = function () { window.currentColor = colorBox.style.backgroundColor; }; colorRow.appendChild(colorBox); colorTable.appendChild(colorBox); } } let colors = [ 'black', 'brown', 'red', 'grey', 'lightgrey', 'blue', 'lightblue', 'yellow', 'green', 'lightgreen' ]; createColorTable(colors); /** * function for drawing table **/ function drawPaintingArea(height, width) { let paintingArea = document.getElementById("paintingArea"); // clear table for redrawing paintingArea.innerHTML = ""; for (i = 0; i &lt; width; i++) { let row = document.createElement("tr"); for (j = 0; j &lt; height; j++) { let column = document.createElement("td"); column.style.backgroundColor = "white"; column.setAttribute("onclick", "tableClickHandler(this)"); row.appendChild(column); } paintingArea.appendChild(row); } } function tableClickHandler(box) { if (box.style.backgroundColor == "white") box.style.backgroundColor = window.currentColor; else box.style.backgroundColor = "white"; } drawPaintingArea(20, 20); /** * draw table by button click **/ let heightTextField = document.getElementById("height"); let widthTextField = document.getElementById("width"); let drawingButton = document.getElementById("drawingButton"); drawingButton.onclick = function() { drawPaintingArea(heightTextField.value, widthTextField.value); }; /** * saving and loading (via buttons) **/ let saveButton = document.getElementById("saveButton"); saveButton.onclick = function() { let paintintArea = document.getElementById("paintingArea"); download("save.txt", paintingArea.innerHTML); } function download(filename, text) { var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } document.getElementById('fileInput').addEventListener('change', readFileAsString) function readFileAsString() { var files = this.files; if (files.length === 0) { console.log('No file is selected'); return; } var reader = new FileReader(); reader.onload = function(event) { let paintintArea = document.getElementById("paintingArea"); paintingArea.innerHTML = event.target.result; }; reader.readAsText(files[0]); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { border: 1px solid black; border-collapse: collapse; } td { height: 20px; width: 20px; } </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Malprogramm Web&lt;/title&gt; &lt;link rel="stylesheet" href="design.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Web Painting Program&lt;/h1&gt; &lt;div&gt; &lt;input id=height value="20" /&gt; Height &lt;br /&gt;&lt;br /&gt; &lt;input id=width value="20" /&gt; Width &lt;br /&gt;&lt;br /&gt; &lt;button id=drawingButton&gt;Draw Field&lt;/button&gt;&lt;/br&gt;&lt;/br&gt; &lt;/div&gt; &lt;h2&gt;Choose Color&lt;/h2&gt; &lt;table id=colorTable&gt; &lt;/table&gt; &lt;br /&gt;&lt;br /&gt; &lt;table border id=paintingArea&gt; &lt;/table&gt; &lt;br /&gt;&lt;br /&gt; &lt;button id=saveButton&gt;Save to file&lt;/button&gt;&lt;br /&gt;&lt;br /&gt; Load: &lt;input type='file' id=fileInput /&gt; &lt;script type="text/javascript" src="main.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T13:58:25.653", "Id": "471878", "Score": "0", "body": "Tip: Java and JavaScript are not related." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T14:00:21.967", "Id": "471879", "Score": "0", "body": "Yes, but I also did not say that :D" } ]
[ { "body": "<p>Some possible improvements:</p>\n\n<p>Inputs are self-closing, as are <code>&lt;br&gt;</code>s. No need for <code>/&gt;</code>. (even in the snippet, you can see how the syntax highlighting is off due to this)</p>\n\n<p>When you want to vertically separate elements from each other, <em>usually</em> it's more elegant to put containers (like <code>&lt;div&gt;</code>s, block-level elements) around the elements than to use <code>&lt;br&gt;</code>. You <em>can</em> use <code>&lt;br&gt;</code>s, but I wouldn't recommend it in most cases.</p>\n\n<p>Tables should usually be used only for <em>tabular</em> data. It's not forbidden, but if you're not trying to display tabular data, I don't think it's exactly semantically appropriate, even if it makes writing the styles easier.</p>\n\n<p>You're mixing <code>let</code> and <code>var</code>, and you're never using <code>const</code>. If you're writing modern Javascript, you should never be using <code>var</code> (it has too many gotchas, like function scope instead of block scope, and automatically creating properties on the global object), and <em>preferably</em>, you should almost always use <code>const</code>, not <code>let</code>. Variables declared with <code>let</code> may be reassigned, so when you use them, you're sending a <em>warning</em> to readers of the code that you may reassign the variable name in the future. If you use <code>const</code> instead, a variable name will not be reassignable, resulting in less cognitive overhead required.</p>\n\n<p>You have</p>\n\n<pre><code>for (i = 0; i &lt; colorStringArray.length; i++) {\n // reference colorStringArray[i] here\n</code></pre>\n\n<p>You have this same pattern in a few other places in the code. There are two issues with all of these:</p>\n\n<ul>\n<li>You're implicitly creating a global <code>i</code> variable because you didn't declare it first. This is not only inelegant, but it'll throw an error in strict mode. (Consider enabling strict mode, it'll help you catch bugs earlier)</li>\n<li>You're having to manually manage the indicies while iterating over the array. This is a bit verbose, has no abstraction benefits, and can occasionally result in off-by-one errors (it's more common than you think). Consider using <code>for..of</code> instead:</li>\n</ul>\n\n<pre><code>for (const color of colorStringArray) {\n // reference color here\n}\n</code></pre>\n\n<p>You have</p>\n\n<pre><code>let colorBox = document.createElement(\"td\");\ncolorBox.value = colorStringArray[i];\n</code></pre>\n\n<p>but <code>&lt;td&gt;</code>s should not have <code>.value</code>s - only input-like elements should have <code>.value</code>s. You can just remove that line.</p>\n\n<p>With</p>\n\n<pre><code>colorBox.onclick = function() {\n window.currentColor = colorBox.style.backgroundColor;\n};\n</code></pre>\n\n<p>It's not an issue here, but I think it's a good idea to get into the habit of using <code>addEventListener</code> instead of <code>on</code> properties. The problem with <code>on</code> properties is that when there are scripts doing separate things, if they want to listen for the same event on an element and they both use <code>on</code> syntax, only the latest listener will actually run:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>button.onclick = () =&gt; console.log('click 1');\nbutton.onclick = () =&gt; console.log('click 2');</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button id=\"button\"&gt;click&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>It's an easy source of bugs. Consider getting into the habit of using <code>addEventListener</code> instead, which can attach <em>any number</em> of listeners.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>button.addEventListener('click', () =&gt; console.log('click 1'));\nbutton.addEventListener('click', () =&gt; console.log('click 2'));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button id=\"button\"&gt;click&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You should also never use inline handlers, like with:</p>\n\n<pre><code>column.setAttribute(\"onclick\", \"tableClickHandler(this)\");\n</code></pre>\n\n<p>Inline handlers have too many problems. Not only will <code>setAttribute</code> remove any previous attribute handler, inline handlers also <a href=\"https://stackoverflow.com/a/59539045\">have a demented scope chain</a>, require global pollution, and have quote escaping issues. Use <code>addEventListener</code> instead.</p>\n\n<p>You have</p>\n\n<pre><code>colorRow.appendChild(colorBox);\ncolorTable.appendChild(colorBox);\n</code></pre>\n\n<p>You're appending the <code>colorBox</code> <code>&lt;td&gt;</code> to the row, then removing it from the row and attaching it to the table instead, and the row never gets used again. You probably wanted to create just a <em>single</em> row which all the <code>&lt;td&gt;</code>s get appended to.</p>\n\n<p>If you wish to dynamically create elements concisely, a possible shortcut is to use <code>appendChild</code>'s return value, which is the element that was appended. For example, your <code>createColorTable</code> can be turned into:</p>\n\n<pre><code>function createColorTable(colorStringArray) {\n const colorTable = document.getElementById(\"colorTable\");\n const colorRow = colorTable.appendChild(document.createElement(\"tr\"));\n for (const color of colorStringArray) {\n const colorBox = colorRow.appendChild(document.createElement(\"td\"));\n colorBox.style.backgroundColor = color;\n colorBox.addEventListener('click', () =&gt; {\n currentColor = color;\n });\n }\n}\n</code></pre>\n\n<p>This is somewhat opinion-based, but you might consider using classes instead of IDs - any element with an ID automatically creates a global variable with the same name, which can result in strange bugs occasionally.</p>\n\n<p>You might consider making an indicator of which color the user has currently selected, like Paint does, so they know what color's going to be painted without them having to remember it themselves.</p>\n\n<p>You may consider using the conditional operator, it's perfectly suited for cases like your <code>tableClickHandler</code> function when you'd like to create an expression conditionally, then use it:</p>\n\n<pre><code>function tableClickHandler(box) {\n box.style.backgroundColor = box.style.backgroundColor === \"white\"\n ? window.currentColor\n : 'white';\n}\n</code></pre>\n\n<p>(remember to <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">use strict equality</a> with <code>===</code>, good to avoid <code>==</code> loose equality)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T14:17:58.203", "Id": "240564", "ParentId": "240559", "Score": "3" } } ]
{ "AcceptedAnswerId": "240564", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T13:02:53.140", "Id": "240559", "Score": "3", "Tags": [ "javascript", "beginner", "html" ], "Title": "Paint Program in HTML" }
240559
<p>After a few weeks of searching and learning ajax, pagination php, product filter, I created ajax php product filter with pagination. </p> <p><strong>1. index.php</strong> </p> <pre><code>&lt;?php require_once('../../../private/initialize.php'); ?&gt; &lt;?php include(SHARED_PATH . '/staff_header.php'); ?&gt; &lt;!-- Filtering --&gt; &lt;section id="filtering"&gt; &lt;h3&gt;Product Filter with Pagination&lt;/h3&gt; &lt;div class="content-box-lg"&gt; &lt;div class="container-fluid"&gt; &lt;div class="row"&gt; &lt;!-- Left Panel--&gt; &lt;div class="col-lg-3"&gt; &lt;h5&gt;Category&lt;/h5&gt; &lt;ul class="list-group"&gt; &lt;?php $sql = "SELECT DISTINCT(category) FROM photographs "; $sql .= "ORDER BY category ASC"; $photos = Photograph::find_by_sql($sql); foreach($photos as $row) { ?&gt; &lt;li class="list-group-item"&gt; &lt;div class="form-check"&gt; &lt;label class="form-check-label"&gt; &lt;input type="checkbox" class="common_selector category" value="&lt;?php echo h($row-&gt;category); ?&gt;" &gt; &amp;nbsp; &lt;?php echo h($row-&gt;category); ?&gt; &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;br&gt; &lt;h5 class="text-info"&gt;Color&lt;/h5&gt; &lt;ul class="list-group"&gt; &lt;?php $sql = "SELECT DISTINCT(color) FROM photographs "; $sql .= "ORDER BY color ASC"; $photos = Photograph::find_by_sql($sql); foreach($photos as $row) { ?&gt; &lt;li class="list-group-item"&gt; &lt;div class="form-check"&gt; &lt;label class="form-check-label"&gt; &lt;input type="checkbox" class="common_selector color" value="&lt;?php echo h($row-&gt;color); ?&gt;" &gt; &amp;nbsp; &lt;?php echo h($row-&gt;color); ?&gt; &lt;/label&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!-- Center - load data--&gt; &lt;div class="col-lg-9"&gt; &lt;!-- Text Change --&gt; &lt;h5 class="text-center" id="textChange"&gt;All products&lt;/h5&gt; &lt;hr&gt; &lt;div class="row filter_data"&gt; &lt;!-- load data --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;style&gt; #loading { text-align: center; background: url('loader.gif') no-repeat center; height: 150px; z-index: 999; } &lt;/style&gt; &lt;?php include(SHARED_PATH . '/staff_footer_filter.php'); ?&gt; </code></pre> <p><strong>2. fetch_data.php</strong> </p> <pre><code>&lt;?php require_once('../../../private/initialize.php'); ?&gt; &lt;?php //fetch_data.php $per_page = 8; $current_page = !empty($_POST['page']) ? (int)$_POST['page'] : '1'; $offset = ($current_page - 1) * $per_page; if(isset($_POST["action"])) { $sql1 = "SELECT COUNT(*) "; $sql1 .= "FROM photographs "; $sql1 .= "WHERE category !='' "; if(isset($_POST["category"])) { $category = implode("','", $_POST['category']); $sql1 .= "AND category IN('".$category."') "; } if(isset($_POST["color"])) { $color = implode("','", $_POST['color']); $sql1 .= "AND color IN('".$color."')"; } $result = Photograph::find_by_sql77($sql1); $row = $result-&gt;fetch_array(); $result-&gt;free(); $total_count = $row[0]; $sql = "SELECT * "; $sql .= "FROM photographs "; $sql .= "WHERE category !='' "; if(isset($_POST["category"])) { $category_filter = implode("','", $_POST['category']); $sql .= "AND category IN('".$category_filter."') "; } if(isset($_POST["color"])) { $color_filter = implode("','", $_POST["color"]); $sql .= "AND color IN('".$color_filter."') "; } $sql .= "LIMIT {$per_page} "; $sql .= "OFFSET {$offset}"; $photos = Photograph::find_by_sql($sql); if($total_count &gt; 0) { foreach($photos as $photo) { ?&gt; &lt;!--https://stackoverflow.com/questions/41794746/col-xs-not-working-in-bootstrap-4--&gt; &lt;div class="col-md-3 col-sm-6 col-xs-12"&gt; &lt;!-- Item 01 --&gt; &lt;div class="portfolio-item"&gt; &lt;a href="show.php?id=&lt;?php echo h(u($photo-&gt;id)); ?&gt;"&gt; &lt;!-- img-fluid bootstrap 4--&gt; &lt;img src="&lt;?php echo h($photo-&gt;image_path_public()); ?&gt;" class="img-fluid"/&gt; &lt;/a&gt; &lt;div class="portfolio-item-overlay"&gt; &lt;div class="portfolio-item-details text-center"&gt; &lt;!-- Item Category --&gt; &lt;h3&gt; &lt;?php echo h($photo-&gt;category); ?&gt; &lt;/h3&gt; &lt;!-- Item Name --&gt; &lt;p&gt; &lt;?php echo h($photo-&gt;caption); ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } } else { echo '&lt;br&gt;' . 'no data found'; } } ?&gt; &lt;div class="container-fluid"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-12"&gt; &lt;div class="pagination justify-content-center pagination-sm"&gt; &lt;?php $total_pages = ceil($total_count / $per_page); function total_pages($total_count, $per_page) { return ceil($total_count / $per_page); } function previous_page($current_page) { $prev = $current_page - 1; return ($prev &gt; 0) ? $prev : false; } function next_page($total_pages, $current_page) { $next = $current_page + 1; return ($next &lt;= $total_pages) ? $next : false; } if ($total_pages &gt; 1) { if (previous_page($current_page) != false) { echo "&lt;span class='pagination_link page-link' style='cursor:pointer;' id='" . previous_page($current_page) . "'&gt;Poprzedni&lt;/span&gt;"; } for ($i = max( 1, $current_page - 5 ); $i &lt;= min( $current_page + 5, total_pages($total_count, $per_page)); $i++ ) { if ($current_page == $i) { echo "&lt;span class=\"selected page-link\"&gt;{$i}&lt;/span&gt;"; } else { echo "&lt;span class='pagination_link page-link' style='cursor:pointer;' id='" . $i . "'&gt;" . $i . "&lt;/span&gt;"; } } if (next_page($total_pages, $current_page) != false) { echo "&lt;span class='pagination_link page-link' style='cursor:pointer;' id='" . next_page($total_pages, $current_page) . "'&gt;Następny&lt;/span&gt;"; } } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>3. staff_footer_filter.php</strong></p> <pre><code> &lt;!-- Footer --&gt; &lt;footer class="text-center"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-12"&gt; &lt;p&gt; Copyright &amp;copy; &lt;?php echo date('Y'); ?&gt; &lt;span&gt;Mr. Robot&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/footer&gt; &lt;!-- Footer Ends --&gt; &lt;!-- JQuery --&gt; &lt;script src="&lt;?php echo url_for('js/jquery.min.js'); ?&gt;"&gt;&lt;/script&gt; &lt;!-- JQuery-UI --&gt; &lt;script src="&lt;?php echo url_for('js/jquery-ui/jquery-ui.js'); ?&gt;"&gt;&lt;/script&gt; &lt;!-- Popper JS --&gt; &lt;script src="&lt;?php echo url_for('js/popper.min.js'); ?&gt;"&gt;&lt;/script&gt; &lt;!-- Bootstrap JS --&gt; &lt;script src="&lt;?php echo url_for('js/bootstrap4/bootstrap.min.js'); ?&gt;"&gt;&lt;/script&gt; &lt;!-- Custom JS --&gt; &lt;script src="&lt;?php echo url_for('js/script.js'); ?&gt;"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function(){ filter_data(1); function filter_data(page) { $('.filter_data').html('&lt;div id="loading" style="" &gt;&lt;/div&gt;'); var action = 'fetch_data'; var category = get_filter('category'); var color = get_filter('color'); $.ajax({ url:"fetch_data.php", method:"POST", data:{action:action, category:category, color:color, page:page}, success:function(data){ $('.filter_data').html(data); //$('#pagination_link').html(data.pagination_link); } }); } $(document).on('click', '.pagination_link', function(event) // this line binds the handler to your pagination { event.preventDefault(); //this prevents the link being loaded as a new page, the default behaviour var page = $(this).attr("id"); //we get the url of the page to load in by ajax filter_data(page); //--------------------------------------------------// history.pushState(null, null, $(this).attr('id')); historyedited = true; //--------------------------------------------------// return event.preventDefault(); }); window.addEventListener('popstate', e =&gt; { filter_data(e.state.page); console.log('popstate!'); }); history.replaceState({page: null}, 'Default state', './'); function get_filter(class_name) { var filter = []; $('.'+class_name+':checked').each(function(){ filter.push($(this).val()); }); return filter; } $('.common_selector').click(function(){ filter_data(1); $("#textChange").text("Filtered products"); }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php db_disconnect($database); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T09:35:05.907", "Id": "472006", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. If you have new code you want reviewed, please post a new question. They're free today." } ]
[ { "body": "<ul>\n<li><p><code>h()</code> is a poor choice for a function name. It makes no effort to inform the developer about what exact process it executes. We are no longer in the digital age where saving keystroke/characters is a valuable pursuit. This function should be renamed to make its action abundantly clear.</p></li>\n<li><p>You should never call the same function on the same data more than once. You should save the outcome to a variable and access that cached value as many times as needed. This eliminates needless function calls.</p></li>\n<li><p>As a general rule, try to avoid declaring single-use variables. There are some situations that argue against this advice (like when declaring the variable helps to describe a value that is somewhat cryptic), so this is a grey area.</p></li>\n<li><p>Use css styling to manage spacing between elements/text (not <code>&amp;nbsp;</code> and <code>&lt;br&gt;</code>) -- this will keep your script cleaner and easier to fine-tune.</p></li>\n<li><p>You have redundant code building your un-ordered lists. You should also only present photo filtering lists if there are actually list items to go inside of them -- be sure to make this check even if you <em>know</em> that there will be some.</p>\n\n<pre><code>foreach (['category', 'color'] as $listName) {\n $listItems = [];\n foreach (Photograph::find_by_sql(\"SELECT DISTINCT({$listName}) FROM photographs ORDER BY {$listName}\") as $row) {\n $value = h($row-&gt;$listName);\n $listItems[] = '&lt;li class=\"list-group-item\"&gt;\n &lt;div class=\"form-check\"&gt;\n &lt;label class=\"form-check-label\"&gt;\n &lt;input type=\"checkbox\" class=\"common_selector ' . $value . '\" value=\"' . $value . '\"&gt;' . $value . '\n &lt;/label&gt;\n &lt;/div&gt;\n &lt;/li&gt;';\n }\n\n if ($listItems) {\n echo '&lt;h5&gt;' . ucfirst($listName) . '&lt;/h5&gt;';\n echo '&lt;ul class=\"list-group\"&gt;' . implode(\"\\n\", $listItems) . '&lt;/ul&gt;';\n }\n}\n</code></pre></li>\n<li><p>You should endeavor to move your js and css declaration to external files and simply include them where desired.</p></li>\n<li><p>I recommend that declare your php function at the top of your file to keep it out of your markup.</p></li>\n<li><p><code>previous_page()</code> can be rewritten as the following because you are performing a falsey check on the return value anyhow.</p>\n\n<pre><code>function previous_page($current_page) {\n return max(0, $current_page - 1); // return will never be lower than 0\n}\n</code></pre></li>\n<li><p><code>if (previous_page($current_page) != false) {</code> is written more concisely as<br><code>if (previous_page($current_page)) {</code></p></li>\n<li><p><code>style='cursor:pointer;'</code> should be moved from inline declarations to an external stylesheet.</p></li>\n<li><p>I don't like the single-use declarations of:</p>\n\n<pre><code>var action = 'fetch_data';\nvar category = get_filter('category');\nvar color = get_filter('color');\n</code></pre>\n\n<p>Just apply those values directly to the <code>data:</code> declaration.</p></li>\n<li><p>Instead of using <code>data</code> to describe the response html, perhaps use the term <code>response</code> or <code>responseHTML</code> so make the script more intuitive and avoid confusion.</p></li>\n<li><p>If you are going to declare: <code>var page = $(this).attr(\"id\");</code>, (I prefer <code>let</code> over <code>var</code>), then use <code>page</code> everywhere downscript. Asking jquery to refetch <code>$(this).attr(\"id\");</code> is unnecessary work.</p></li>\n<li><p>Disconnecting from your database at the end of your script is unnecessary because php is going to do this for you automatically. There is no benefit to writing it out. </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T06:54:10.683", "Id": "471983", "Score": "0", "body": "Thank you for your response, I added: Update1 h(); u(); find_by_sql and find_by_sql77" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T07:08:00.363", "Id": "471987", "Score": "0", "body": "Your custom functions which act as wrappers for native functions provide no value to your script. Just remove them entirely and call the native functions only. I don't understand why a method would have 77 in it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T07:29:46.363", "Id": "471989", "Score": "0", "body": "\"var page = $(this).attr(\"id\");\" can you explain to me or give me an example because I don't understand that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:07:09.653", "Id": "471997", "Score": "0", "body": "`history.pushState(null, null, page);` is the same thing, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:08:03.683", "Id": "471998", "Score": "0", "body": "77 because it is count, returns only one number, by_sql convert to object - it is row->category, not row['category']." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:12:43.430", "Id": "471999", "Score": "0", "body": "history.pushState -page - now I understand,:)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:12:49.157", "Id": "472000", "Score": "0", "body": "It looks to me that it returns the whole result object. I don't see any relationship between the behavior and the 77 in the method name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:23:12.093", "Id": "472004", "Score": "0", "body": "count with 'find_by_sql' ' Fatal error: Uncaught Error: Call to a member function fetch_array() on array '" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T08:40:19.493", "Id": "472005", "Score": "1", "body": "I don't want to open a chat box, I am spending time with my family now, so I won't be replying further. Change your query, let MySQL do the counting. Use `SELECT COUNT(1) FROM ...`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T10:23:00.910", "Id": "472013", "Score": "0", "body": "OK, I understand." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T02:19:00.373", "Id": "240604", "ParentId": "240560", "Score": "3" } } ]
{ "AcceptedAnswerId": "240604", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T13:15:58.497", "Id": "240560", "Score": "1", "Tags": [ "php", "ajax" ], "Title": "My method of php ajax product filter with pagination" }
240560
<p>This is a URI online judge problem (problem no: 1973). <br>Link : <a href="https://www.urionlinejudge.com.br/judge/en/problems/view/1973" rel="nofollow noreferrer">https://www.urionlinejudge.com.br/judge/en/problems/view/1973</a></p> <blockquote> <p>After buying many adjacent farms at the west region of Santa Catarina, the Star family built a single road which passes by all farms in sequence. The first farm of the sequence was named Star 1, the second Star 2, and so on. However, the brother who lives in Star 1 has got mad and decided to make a Star Trek in order to steal sheep from the proprieties of his siblings. But he is definitely crazy. When passes by the farm Star <strong>i</strong>, he steals only one sheep (if there is any) from that farm and moves on either to Star <strong>i</strong> + 1 or Star <strong>i</strong> - 1, depending on whether the number of sheep in Star <strong>i</strong> was, respectively, odd or even. If there is not the Star to which he wants to go, he halts his trek. The mad brother starts his Star Trek in Star 1, stealing a sheep from his own farm.</p> <p>Input</p> <p>The first input line consists of a single integer <strong>N</strong> (1 ≤ <strong>N</strong> ≤ 10⁶), which represents the number of Stars. The second input line consists of <strong>N</strong> integers, such that the <strong>i</strong>th integer, <strong>Xi</strong> (1 ≤ <strong>Xi</strong> ≤ 10⁶), represents the initial number of sheep in Star <strong>i</strong>.</p> <p>Output</p> <p>Output a line containing two integers, so that the first represents the number of Stars attacked by the mad brother and the second represents the total number of non-stolen sheep.</p> <pre><code>Sample Input Sample Output 8 8 68 1 3 5 7 11 13 17 19 </code></pre> <p> </p> <pre><code>8 7 63 1 3 5 7 11 13 16 19 </code></pre> </blockquote> <p>I have solved the problem with two ways and they also give the desired output, but every time I submitted it it says time limit exceeded.</p> <pre><code>#1st solution: num_star = int(input()) sheep = list(map(int, input().split())) star = set() index = 0 while index != num_star: if sheep[index] == 0: break elif sheep[index] % 2 == 1: star.add(index) sheep[index] -= 1 index += 1 else: star.add(index) sheep[index] -= 1 index -= 1 if index == -1: break print(len(star), sum(sheep)) #2nd solution n = int(input()) x = list(map(int, input().split())) i = 0 farm_visited = 0 while i in range(n): if x[i] == 0: if i &gt;= farm_visited: farm_visited = i+1 break elif (x[i]) % 2 == 1: if i &gt;= farm_visited: farm_visited = i + 1 x[i] -= 1 i += 1 else: if i &gt;= farm_visited: farm_visited = i + 1 x[i] -= 1 i -= 1 print(farm_visited, sum(x)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:24:09.237", "Id": "471900", "Score": "1", "body": "Generally Code Review's interpretation of \"working code\" encompasses \"code that is too slow\", so I do not think that this is off-topic for that reason. It could use some more general description of the performance analysis you've already done, and your specific concerns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T13:00:47.193", "Id": "472025", "Score": "1", "body": "Please change your title to summarize what the code is doing." } ]
[ { "body": "<p><code>set</code> in the first solution, and <code>while i in range(n)</code> in the second one are <em>very</em> expensive.</p>\n\n<p>That said, thou shalt not bruteforce.</p>\n\n<p>The crazy guy moves right as long as he visits the odd-populated farms, leaving a trail of even-populated farms behind. As soon as he hits the even-populated farm, he switches direction, and since now on he faces only the even-populated farms, he goes all the way to the Star 1, and the track stops there.</p>\n\n<p>So, find the leftmost even-populated farm. If there is none, the guy would visit all farms, stealing one ship per farm. If there is, its index is the number of farms visited; on the way there, one ship per farm will be stolen, and on the way back another ship per farm will be stolen (except if initially there was just one ship).</p>\n\n<p>This should be enough to keep you going.</p>\n\n<p>As a side note, <code>break</code> in</p>\n\n<pre><code> if x[i] == 0:\n if i &gt;= farm_visited: farm_visited = i+1\n break\n</code></pre>\n\n<p>is a bug. An empty farm should not stop him:</p>\n\n<blockquote>\n <p>he steals only one sheep (<strong>if there is any</strong>) from that farm <strong>and moves on</strong></p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-10T03:39:34.510", "Id": "474972", "Score": "0", "body": "(The theme has been *Star Trek West of Santa Catarina*, not *Pirate in the Family*.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T17:00:19.870", "Id": "240576", "ParentId": "240570", "Score": "6" } } ]
{ "AcceptedAnswerId": "240576", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:08:02.007", "Id": "240570", "Score": "5", "Tags": [ "python", "python-3.x", "time-limit-exceeded" ], "Title": "What should I do to reduce run time of my code?" }
240570
<p>I've progressed with the directory statistics function and want to proceed by making it a class.</p> <p>Link to the first version of this code: <a href="https://codereview.stackexchange.com/questions/240518/run-dir-scan-as-fast-and-efficient-as-possible-clean-code/240551?noredirect=1#comment471897_240551">Link</a></p> <p><strong>My current state of things:</strong></p> <p><strong>About my namings:</strong> I first used the name <code>fcount</code> as I wanted to have it stand for files and folders as otherwise, the name would be too long. That's why I made the exception to shorten it. I'm still continuing with your more experienced solution for this. I wrote <code>pathlib</code> into the function name because I have the same function above it with <code>os.walk</code> as this was my first way to try. But <code>os.walk</code> seem to have problems scanning my network drive as it always returned 0 bytes. Therefore I've chosen <code>pathlib</code>. Hope that makes sense.</p> <p><strong>About my classes:</strong> I'm starting to feel comfortable programming python but as soon as I start to use classes my whole code starts to fall apart and seems to have to be more complex. I know that's just a beginner problem, but as I usually can't solve the issues appearing, I'm careful with that route. I've now rewritten it into a class but facing a few problems now. I started to try to structure it with the tips from the first CodeReview by writing the file search for-loop into the <code>__init__</code> function but python was then saying it can't return a value from <code>__init__</code> so I created a new method named <code>def get_directory_statistics(self, scan_path):</code>. I'm not sure where to input my <code>scan_path</code>, into the <code>__init__</code>or the first method <code>def get_directory_statistics(self, scan_path):</code>. Your advice to summarize two lines into one, sadly didn't work for me either <code>return size_and_file_count(size_gb, all_types_count, file_count, folder_count)</code>. I couldn't get it to work. It's always saying <code>size_and_file_count</code> is not defined or other Errors.</p> <p>Optimizing the code: I outlined above why I sadly can't use os.walk for this. So this won't work for me. And C seems at the moment, not like an option as the only programming language I am familiar with is python and I guess it would be a more complex task to program a wrapper and the code itself in <code>C</code>. I think most of it will be I/O bound, yes.</p> <p>Again I learned a lot from the first answer here on CodeReview!</p> <p><strong>Below you'll find my solution after going over all the last notes</strong> </p> <pre><code>class get_size_and_file_count: """Gets the total size of a given dir and counts how many folders and files are in the given path directory and return a file count, folder count and all non hidden files as a sum""" def __init__(self, total_size = 0, non_hidden_files_count = 0, file_count = 0, folder_count = 0): self.total_size = total_size self.non_hidden_files_count = non_hidden_files_count self.file_count = file_count self.folder_count = folder_count def get_directory_statistics(self, scan_path): self.root_directory = Path(scan_path) for f in self.root_directory.glob('**/*'): if f.is_file(): self.file_count += 1 self.total_size += f.stat().st_size if not f.name.startswith("."): self.non_hidden_files_count += 1 if f.is_dir(): self.folder_count += 1 directory_statistics = [self.total_size, self.non_hidden_files_count, self.file_count, self.folder_count] return directory_statistics def print_directory_statistics(self): print('Directory path to search: {}'.format(self.root_directory)) print('Directory size in GB: {:.2f}GB'.format(self.total_size / 1.0e9)) print('Amount of non hidden files: {}'.format(self.non_hidden_files_count)) print('Amount of files searched: {}'.format(self.file_count)) print('Amount of folders searched: {}'.format(self.folder_count)) result = get_size_and_file_count() directory_statistics = result.get_directory_statistics("...") # Store directory statistics in var result.print_directory_statistics() # Print directory statistics </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:47:49.550", "Id": "471950", "Score": "0", "body": "It was working and I added the changes that a member suggested, he also suggested to make a new CodeReview out of that. Link to tread 01 at the top of the page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:56:47.187", "Id": "471953", "Score": "3", "body": "Instead of `print_result = ...`, just write `result.print_directory_statistics()`. Indeed, please make sure the code works, then we can review it properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T21:33:22.977", "Id": "471956", "Score": "0", "body": "Thanks for all your feedback, I've adjusted accordingly." } ]
[ { "body": "<p><strong>Style conventions</strong></p>\n\n<p>Following the PEP style guide, <a href=\"https://www.python.org/dev/peps/pep-0008/#class-names\" rel=\"nofollow noreferrer\">class names</a> should be named with CamelCase and <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">documentation strings</a> should be formatted like the following.</p>\n\n<pre><code>class DirectoryStatistics:\n \"\"\"Gets the total size of a given dir and counts how many folders and\n files are in the given path directory. Also offers a printing utility to output\n the diagnosis results.\n \"\"\"\n def __init__(self, ...):\n # etc.\n</code></pre>\n\n<p><strong>Classes</strong></p>\n\n<p>You can't return values from <code>__init__</code> (aka. the class constructor), because it is called when you instantiate an object, thus the return value is the object itself. But you can call methods in your <code>__init__</code> method, that's why you should move the content of your <code>get_directory_statistics</code> method into the <code>__init__</code> method:</p>\n\n<pre><code>class DirectoryStatistics:\n \"\"\"Gets the total size of a given dir and counts how many folders and\n files are in the given path directory. Also offers a printing utility to output\n the diagnosis results.\n \"\"\"\n def __init__(self, file_path):\n self.root_directory = path(file_path)\n self.file_count = 0\n self.total_size = 0\n self.non_hidden_files_count = 0\n self.folder_count = 0\n for f in self.root_directory.glob('**/*'):\n if f.is_file():\n self.file_count += 1\n self.total_size += f.stat().st_size\n if not f.name.startswith(\".\"):\n self.non_hidden_files_count += 1\n if f.is_dir():\n self.folder_count += 1\n</code></pre>\n\n<p>That way, by calling:</p>\n\n<pre><code>statistics = DirectoryStatistics(file_path)\n</code></pre>\n\n<p>you run the directory diagnosis and save the results in your object.\nThen you can pretty-print the results using your <code>print_statistics()</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T21:53:44.850", "Id": "471959", "Score": "0", "body": "Thank you for the hint with the style guide. I've rewritten that part.\nMoving the content of `get_directory_statistics()` into `__init__` isn't working for me as I lose the opportunity to return the values. `statistics` in your case wouldn't return anything as it's an object. I would be able to print the values with `print_directory_statistics`, yes but returning the values for further valuation wouldn't be possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T21:56:00.207", "Id": "471960", "Score": "1", "body": "The diagnosis results are stored in the `statistics` object, you can retrieve them with `statistics.file_count` for example, that was the reason we restructured the code as a class. Instead of accessing your data via `results[1]` you can now refer to them by name, which is way clearer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T22:00:59.593", "Id": "471961", "Score": "0", "body": "I see, that worked. What do you think is more pythonic? Writing a method or putting the code in `__init__`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T22:06:01.710", "Id": "471963", "Score": "1", "body": "Putting the code in `__init__` is definitely the way to go. Otherwise you could instantiate your object and run your `print_directory_results` method without actually running the `get_directory_statistics` method first. This would print only the default values, which is not desirable. An object should never be in an unexpected state, that's why you use the `__init__` method to avoid this." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T21:04:36.877", "Id": "240592", "ParentId": "240574", "Score": "4" } }, { "body": "<h1>Unnecessary Flexibility</h1>\n\n<pre><code>def __init__(self, total_size = 0, non_hidden_files_count = 0, file_count = 0, folder_count = 0):\n</code></pre>\n\n<p>Why do you have the possibility of the caller starting the counters at values other than zero? Is it really needed? Or was it just a fancy way of declaring counter variables all in one line?</p>\n\n<p>Note: PEP-8 would require that these keyword parameters not have spaces around the equal signs.</p>\n\n<h1>Stop writing classes</h1>\n\n<p>See <a href=\"https://youtu.be/o9pEzgHorH0\" rel=\"nofollow noreferrer\">Stop writing classes</a> on YouTube</p>\n\n<p>Your class should be a function if it is created, one method is called, and results are retrieved. So let's get rid of your class:</p>\n\n<p>First of all, you want to return results in a nice package, like a named tuple. We can even add a nice method to this named tuple to print out the results as desired, but it is just decoration. The results are just plain-old-data:</p>\n\n<pre><code>from pathlib import Path\nfrom typing import NamedTuple\n\nclass DirectoryStats(NamedTuple):\n root_directory: Path\n total_size: int\n files: int\n hidden_files: int\n folders: int\n\n def print(self):\n print(f'Directory path to search: {self.root_directory}')\n print(f'Directory size in GB: {self.total_size / 1.0e9:.2f}GB')\n print(f'Amount of non hidden files: {self.files-self.hidden_files}')\n print(f'Amount of files searched: {self.files}')\n print(f'Amount of folders searched: {self.folders}')\n</code></pre>\n\n<p>Here, I'm using the typing module to automatically create the named tuple from type hints in the declaration.</p>\n\n<p>I'm also using <code>f'...'</code> strings to created formatted output without that ugly <code>\"... {} ... \".format(arg)</code> construct which separates the place where the result is created from the thing that the result is generated from. </p>\n\n<p>Now, the scanning is just a simple function:</p>\n\n<pre><code>def get_size_and_file_count(scan_path) -&gt; DirectoryStats:\n \"\"\"\n Your docstring here.\n \"\"\"\n\n files = folders = hidden = total_size = 0\n root = Path(scan_path)\n for f in root.glob('**/*'):\n if f.is_file():\n files += 1\n total_size += f.stat().st_size\n if f.name.startswith(\".\"):\n hidden += 1\n elif f.is_dir():\n folders += 1\n\n return DirectoryStats(root, total_size, files, hidden, folders)\n</code></pre>\n\n<p>Pretty straight forward. The function initializes some counters, walks the <code>scan_path</code>, counts stuff, and then in the return statement, constructs the named tuple we defined above.</p>\n\n<p>I've removed a double negative. Instead of the file name does not start with a period incrementing a not hidden count, I count the hidden files.</p>\n\n<p>Example usage:</p>\n\n<pre><code>if __name__ == '__main__':\n result = directory_statistics('.')\n result.print()\n</code></pre>\n\n<p>Produces on my machine, in my directory:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Directory path to search: .\nDirectory size in GB: 0.00GB\nAmount of non hidden files: 22\nAmount of files searched: 23\nAmount of folders searched: 4\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T22:42:56.880", "Id": "240598", "ParentId": "240574", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T16:54:36.520", "Id": "240574", "Score": "3", "Tags": [ "python", "file-system" ], "Title": "Run directory scan as Class" }
240574
<p>We have been given a college assignment (Yeah even during lockdown!!) to implement an assembler to assemble the reference instructions given <a href="https://github.com/kesarling/SL-V/blob/master/assignment2/reference.txt" rel="nofollow noreferrer">here</a>. The following is my code to implement pass1 of the assembler. Please review it. </p> <pre><code>//imperative keywords std::list&lt;std::string&gt; Mn_imp = { "READ","PRINT","MOVER","MOVEM","ADD","SUB","MULT","DIV" }; //declarative keywords std::list&lt;std::string&gt; Mn_dcl = { "DS","DS" }; //assembler directives std::list&lt;std::string&gt; Mn_drc = { "START","STOP","LTORG","EQU","ORIGIN" }; struct Row { std::string name; long LC_val; Row () { } Row(std::string _name, long LC) : name(_name), LC_val(LC) { } bool operator==(const Row&amp; row) { return ((this-&gt;name == row.name) &amp;&amp; (this-&gt;LC_val == row.LC_val)); } }; long LOCCTR = 0; std::vector&lt;Row&gt; SYMTAB; std::vector&lt;Row&gt; LITTAB; std::vector&lt;int&gt; POOLTAB = { 0 }; std::string getToken(std::string&amp; buffer) { std::string retToken; int i = 0; while (1) { if (i == buffer.size()) { buffer.clear(); break; } else if (buffer[i] == ' ' || buffer[i] == ',') { i++; std::string newString(buffer.begin() + i, buffer.end()); buffer.clear(); buffer = newString; break; } retToken += buffer[i]; i++; } return retToken; } bool getNumber(char* str, long* num_ptr) { bool flag = false; int i = 0; *num_ptr = 0; char ch = ' '; while (ch != '\0') { ch = *(str + i); if (ch &gt;= '0' &amp;&amp; ch &lt;= '9') { *num_ptr = (*num_ptr) * 10 + (long)(ch - 48); flag = true; } i++; } return flag; } short process_imp(std::vector&lt;std::string&gt; statement) { auto isRegister = [](const std::string&amp; token) { return (token == "AREG" || token == "BREG" || token == "CREG" || token == "DREG"); }; //first argument if (!isRegister(statement[1])) { if (std::find(statement[1].begin(), statement[1].end(), '=') != statement[1].end()) { //isLiteral if (std::find(LITTAB.begin() + POOLTAB.back(), LITTAB.end(), Row(statement[1], -1)) == LITTAB.end()) { //check for presence LITTAB.push_back(Row(statement[1], -1)); } } else if (statement[1][0] == 'F') { //isNumber long number = 0; getNumber(const_cast&lt;char*&gt;(statement[1].c_str()), &amp;number); } else { //isVariable bool flag = true; for (const auto&amp; row : SYMTAB) { if (row.name == statement[1]) { flag = false; break; } } if (flag) { SYMTAB.push_back(Row(statement[1], -1)); } } } //second argument if (!isRegister(statement[2])) { if (std::find(statement[2].begin(), statement[2].end(), '=') != statement[2].end()) { //isLiteral if (std::find(LITTAB.begin() + POOLTAB.back(), LITTAB.end(), Row(statement[2], -1)) == LITTAB.end()) { //check for presence LITTAB.push_back(Row(statement[2], -1)); } } else if (statement[2][0] == 'F') { //isNumber long number = 0; getNumber(const_cast&lt;char*&gt;(statement[2].c_str()), &amp;number); } else { //isVariable for (auto&amp; row : SYMTAB) { if (row.name == statement[2]) { return 0; } } SYMTAB.push_back(Row(statement[2], -1)); } } return 0; } short process_drc(std::vector&lt;std::string&gt; statement) { if (statement.front() == std::string("START")) { if (statement.size() &gt; 1) { getNumber(const_cast&lt;char*&gt;(statement[1].c_str()), &amp;LOCCTR); } } else if (statement.front() == std::string("LTORG")) { int i; for (i = POOLTAB.back(); i &lt; LITTAB.size(); i++) { if (LITTAB[i].LC_val == -1) { LITTAB[i].LC_val = LOCCTR++; } } POOLTAB.push_back(i); } else if (statement.front() == std::string("EQU")) { for (auto&amp; row : SYMTAB) { if (row.name == statement[0]) { for (auto&amp; _row : SYMTAB) { if (_row.name == statement[2]) { row.LC_val = _row.LC_val; return 0; } } } } } else if (statement.front() == std::string("ORIGIN")) { //still to be implemented } else if (statement.front() == "STOP") { for (int i = POOLTAB.back(); i &lt; LITTAB.size(); i++) { LITTAB[i].LC_val = LOCCTR++; } return 1; } return 0; } short process_dcl(std::vector&lt;std::string&gt; statement) { for (auto&amp; row : SYMTAB) { if (row.name == statement[0]) { row.LC_val = LOCCTR; if (std::find(statement[2].begin(), statement[2].end(), '=') != statement[2].end()) { //isLiteral if (std::find(LITTAB.begin() + POOLTAB.back(), LITTAB.end(), Row(statement[2], -1)) == LITTAB.end()) { //check for presence LITTAB.push_back(Row(statement[2], -1)); } } LOCCTR++; return 0; } } SYMTAB.push_back(Row(statement[0], LOCCTR++)); if (std::find(statement[2].begin(), statement[2].end(), '=') != statement[2].end()) { //isLiteral if (std::find(LITTAB.begin() + POOLTAB.back(), LITTAB.end(), Row(statement[2], -1)) == LITTAB.end()) { //check for presence LITTAB.push_back(Row(statement[2], -1)); } } return 0; } int process_line(std::string line) { auto find = [](std::list&lt;std::string&gt; list, std::string str) { //could have used std::find() for (const auto&amp; var : list) { if (std::string(var) == str) { return true; } } return false; }; int retVal = 0; std::vector&lt;std::string&gt; token_vec; while (line != "") { token_vec.push_back(getToken(line)); } //start processing the tokenised array auto token = token_vec.begin(); std::string tok = token_vec.front(); //pop the label if (tok[tok.size() - 1] == ':') { SYMTAB.push_back(Row(tok, LOCCTR)); token_vec.erase(token_vec.begin()); tok = token_vec.front(); } //find the type of statement unsigned short type = 0; if (std::find(Mn_imp.begin(), Mn_imp.end(), tok) != Mn_imp.end()) { type = 1; } else if (std::find(Mn_drc.begin(), Mn_drc.end(), tok) != Mn_drc.end()) { type = 2; } else { type = 3; } switch (type) { case 1: //imperative statement retVal = process_imp(token_vec); LOCCTR++; break; case 2: //assembler directive retVal = process_drc(token_vec); break; case 3: //declarative statement retVal = process_dcl(token_vec); break; //default: (not needed) } return retVal; } int main(int argc, const char** argv) { std::vector&lt;std::string&gt; code; std::ifstream infile; infile.open(argv[1]); while (!infile.eof()) { std::string str; std::getline(infile, str); code.push_back(str); } infile.close(); //Now we have the code in a string vector //check for a proper end if (code.back() != "STOP") { std::cerr &lt;&lt; "Where do I stop?? Perhaps you forgot to put an end (STOP) statement?\n"; return -1; } //if code is proper then begin pass1 for (int i = 0; ; i++) { auto line = code[i]; short success = process_line(line); if (success == -1) { std::cerr &lt;&lt; "Something wrong at line number " &lt;&lt; i + 1 &lt;&lt; std::endl; break; } else if (success == 0) { //silence is golden :P } else if (success == 1) { for (const auto&amp; i : SYMTAB) { std::cout &lt;&lt; i.name &lt;&lt; " " &lt;&lt; i.LC_val &lt;&lt; std::endl; } for (const auto&amp; i : LITTAB) { std::cout &lt;&lt; i.name &lt;&lt; " " &lt;&lt; i.LC_val &lt;&lt; std::endl; } break; } } return 0; } </code></pre> <p>P.S. This is my first time implementing something this hard. Please bear with the code </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T17:53:51.017", "Id": "471910", "Score": "1", "body": "Umm, will you please state what I am supposed to improve in the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:41:55.353", "Id": "471935", "Score": "4", "body": "I don't know who voted this down, I believe they also voted to close the question. The problem is that rather than following the line the information at the link should be here in the question, at least the opcodes should be and perhaps all of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T05:58:50.167", "Id": "471980", "Score": "3", "body": "Site standard is to have the title highlight what the code is to accomplish. I doubt the goal of assignment or coding is for the resulting assembler to be *lousy*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T06:05:06.813", "Id": "471981", "Score": "3", "body": "(Did you try and follow [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T11:49:12.120", "Id": "472021", "Score": "1", "body": "@greybeard, thanks for the link and heads up. I will definitely work on my question asking skills :). And oh yeah, I didn't want the assembler to be lousy, I just thought it was " } ]
[ { "body": "<h2>Const initializers</h2>\n\n<p>In your constructor:</p>\n\n<pre><code>Row(std::string _name, long LC)\n</code></pre>\n\n<p><code>_name</code> would be better-represented by a <code>const std::string &amp;_name</code>.</p>\n\n<p>Similarly,</p>\n\n<pre><code>process_imp(std::vector&lt;std::string&gt; statement)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>process_imp(const std::vector&lt;std::string&gt; &amp;statement)\n</code></pre>\n\n<h2><code>getNumber</code></h2>\n\n<p>This has a C twang. C++ is able to do all of this for you.</p>\n\n<p>First of all, if you wanted to keep it mostly as-is, do not use the ASCII code 48 directly; simply write <code>'0'</code>. That said,</p>\n\n<ul>\n<li>You should use something like <code>atoi</code>, though <code>atoi</code> itself does not support error detection, so this is ruled out. <code>atol</code> has similar issues.</li>\n<li><code>sscanf</code> would work but is a C-ism.</li>\n<li><code>istringstream</code> would do what you want.</li>\n</ul>\n\n<h2>string comparison</h2>\n\n<pre><code>statement.front() == std::string(\"LTORG\")\n</code></pre>\n\n<p>does not need to construct a string on the right-hand side; simply compare the string literal, and the left-hand side's overloaded <code>==</code> will do the right thing.</p>\n\n<h2>enums</h2>\n\n<pre><code>//find the type of statement\nunsigned short type = 0;\n</code></pre>\n\n<p>should be using an <code>enum</code> to capture the different possible types.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:12:47.310", "Id": "240580", "ParentId": "240578", "Score": "4" } } ]
{ "AcceptedAnswerId": "240580", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T17:48:52.390", "Id": "240578", "Score": "2", "Tags": [ "c++", "assembly" ], "Title": "An assembler to assemble a hypothetical instruction set" }
240578
<p><strong>Prim's Algorithm</strong></p> <p>This is an implementation of Prim's algorithm in Python. From <a href="https://en.wikipedia.org/wiki/Prim%27s_algorithm" rel="nofollow noreferrer">Wikipedia</a>:</p> <blockquote> <ol> <li>Initialize a tree with a single vertex, chosen arbitrarily from the graph.</li> <li>Grow the tree by one edge: of the edges that connect the tree to vertices not yet in the tree, find the minimum-weight edge, and transfer it to the tree. </li> <li>Repeat step 2 (until all vertices are in the tree).</li> </ol> </blockquote> <p><strong>My code</strong></p> <p>I have included the all the relevant sections for completeness but I want advice on the Prim's function inside the Graph class but feel free to comment on any part of the code!</p> <p>I feel like the Prim's function can be improved as I have lots of conditionals that are similar but I don't know how to make it more Pythonic.</p> <p>Any critique is welcome.</p> <pre><code>class Vertex: def __init__(self, name): self.name = name def __str__(self): return f"Vertex {self.name}" class Edge: def __init__(self, start, end, weight,directed): self.start = start self.end = end self.weight = weight self.directed = directed def __str__(self): return f"{self.start.name}{self.end.name}" class Graph: def __init__(self, v, e): self.vertices = v self.edges = e def add_vertex(self, v): """ Add vertex of type Vertex. """ self.vertices.append(v) def total_weight(self): """ Return total weight of all edges in graph.""" return sum(e.weight for e in self.edges) def vertex_from_name(self, name): """ Return vertex object given vertex name. """ return next((v for v in self.vertices if v.name == name), None) def add_edge(self, start, end, weight,directed=False): """ Add an edge connecting two vertices. Arguments can either be vertex name or vertex object. """ if isinstance(start, str): start = self.vertex_from_name(start) if isinstance(end, str): end = self.vertex_from_name(end) self.edges.append(Edge(start, end, weight,directed)) def add_edges(self,edges): for edge in edges: self.add_edge(edge[0],edge[1],edge[2]) def edge_on_vertex(self, v): """ Return edges connected to given vertex v.""" return (e for e in self.edges if v in {e.start, e.end}) def connected_vertices(self, v): """ Return the vertices connected to argument v.""" if isinstance(v, str): v = self.vertex_from_name(v) yield from (e.start for e in self.edges if e.end == v) yield from (e.end for e in self.edges if e.start == v) #Code to be reviewed def Prims(self, **kwargs): """ Return MST using Prim's algorithm. Optional argument is start vertex, defaults to first vertex. """ self.start = kwargs.get('start', self.vertices[0]) self.tree = Graph([], []) self.tree.vertices.append(self.start) while len(self.tree.vertices) != len(self.vertices): self.connected = set([e for vert in self.tree.vertices for e in self.edge_on_vertex(vert)]) self.connected = sorted(list(self.connected), key=lambda x: x.weight) for edge in self.connected: if (edge.start not in self.tree.vertices) or (edge.end not in self.tree.vertices): if edge.start in self.tree.vertices: self.tree.add_vertex(edge.end) else: self.tree.add_vertex(edge.start) self.tree.edges.append(edge) break return self.tree if __name__ == "__main__": v = [Vertex(x) for x in 'ABCDEF'] g = Graph(v, []) g.add_edges(( ("A", "B", 9), ("A", "C", 12), ("A", "D", 9), ("A", "E", 11), ("A", "F", 8), ("B", "C", 10), ("B", "F", 15), ("C", "D", 8), ("D", "E", 14), ("E", "F", 12), )) print([str(e) for e in g.Prims().edges]) </code></pre> <p><strong>Code seem familiar?</strong> This is a followup to <a href="https://codereview.stackexchange.com/questions/240343/graphs-and-kruskals-algorithm-python-oop/240352">my earlier question</a> about Kruskal's algorithm using the same module.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:57:22.057", "Id": "471927", "Score": "2", "body": "I see that you've called out a specific section of code to be reviewed. Keep in mind that CR policy encourages review of any part of the code." } ]
[ { "body": "<h2>Be consistent</h2>\n\n<ul>\n<li><p>You named all your method functions with lowercase letters and separated the words with underscores... So maybe <code>Prims</code> should be named <code>prims</code> or <code>prim_algorithm</code>;</p></li>\n<li><p>In lists (argument lists, function calls, lists, etc) you always include a space after a comma (as you should), so do it always (I'm talking about <code>Edge.__init__</code>, <code>Graph.add_egde</code> and <code>Graph.add_edges</code>, for e.g.);</p></li>\n<li><p>For the simpler <code>Graph</code> methods, the one-liners, you have three lines: function definition, docstring, return statement; this is perfectly fine for simple functions. So you should also do it for <code>Graph.vertex_from_name</code>, instead of having a blank line between the docstring and the return.</p></li>\n</ul>\n\n<h2><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">Docstring conventions</a></h2>\n\n<p>For <a href=\"https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings\" rel=\"nofollow noreferrer\">multiline docstrings</a>, consider having the final <code>\"\"\"</code> in a separate line, all by itself, and then include a blank line between the multiline docstring and the body of the function.</p>\n\n<h2>Avoid long lines</h2>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Python's style guide</a> suggests your lines don't exceed 81 characters (generally) and the <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">black code formatter</a> goes with 89, because <em>\"it's like highway speed limits, we won't bother you if you overdo it by a few km/h\"</em>. But don't exceed that, no one wants to have to scroll right when reading someone else's code; for example, in your question, I have to scroll right to read some docstrings and some code in your functions.</p>\n\n<h2><code>Prims</code></h2>\n\n<p>As for the <code>Prims</code> function itself, I would reformat the body slightly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def Prims(self, start=None):\n \"\"\" Return MST using Prim's algorithm.\n\n Optional argument `start` gives the start vertex (defaults to first vertex).\n \"\"\"\n\n if start is None:\n start = self.vertices[0]\n self.tree = Graph([start], [])\n\n while len(self.tree.vertices) != len(self.vertices):\n\n self.connected = set([e for vert in self.tree.vertices for e in self.edge_on_vertex(vert)])\n self.connected = sorted(list(self.connected), key=lambda x: x.weight)\n\n for edge in self.connected:\n if (edge.start not in self.tree.vertices) or (edge.end not in self.tree.vertices):\n if edge.start in self.tree.vertices:\n self.tree.add_vertex(edge.end)\n else:\n self.tree.add_vertex(edge.start)\n self.tree.edges.append(edge)\n\n break\n\n return self.tree\n</code></pre>\n\n<ul>\n<li><p>I reformatted the docstring to keep the first line short and to the point. A short first docstring line is very helpful because many IDEs can show it if you hover the function name when using it elsewhere. If the docstring is long and/or contains irrelevant information, you won't be able to read what you needed to recall what your function does.</p></li>\n<li><p>I added an explicit keyword argument, instead of having you guess what you decided the starting vertex argument was named; I also gave it a default value of <code>None</code>, against which I then compare to see if I need to use the default value. If you want that argument to always be called as a keyword argument, you can use this syntax: <code>def prims_algorithm(self, *, start=None):</code>.</p></li>\n<li><p>If <code>Graph</code> takes a list of vertices when creating a <code>Graph</code> instance, why don't you initialize your tree instance already with the starting vertex, instead of appending it right after instantiating the <code>Graph</code>?</p></li>\n<li><p>I added two blank lines by the end of the function to make it easier to spot the <code>return</code> and to make it easier to spot the <code>break</code>; in particular the <code>break</code> statement was fairly hard to find and a quick read didn't reveal it. I like having these important keywords visible!</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:26:17.067", "Id": "240584", "ParentId": "240581", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T18:15:37.293", "Id": "240581", "Score": "4", "Tags": [ "python", "python-3.x", "object-oriented", "graph" ], "Title": "Prim's Algorithm" }
240581
<p>The code below matches a list of features to a large corpus and returns the sub-query match with a score above 80. The challenge is the list of features on the full data-set is > 5,000 and comparing to multiple documents. Therefore is taking too long to work using the <code>fuzzywuzzy</code> package.</p> <p>Per the Spyder profiler, the bottlenecks are at:</p> <pre><code>if(fuzz.ratio(wordtocompare,feature.lower())&gt; match) and _find_and_load_unlocked </code></pre> <p>Would vectorizing the code in its current form help or is there a faster approximate matcher that accounts for matching a sub-query (information extraction) of text compared to a defined list? Has anyone had success using polyleven and port the results back into Python?</p> <pre><code>import pandas as pd from fuzzywuzzy import fuzz import re document = """If you're shopping within the Toyota family, the Highlander offers appreciably more space than the RAV4, both in terms of cargo capacity and its extra row of seats. It also has a deeper, more accessible space than what's in the 4Runner. That said, the Highlander is one of the smallest three-row crossovers available. Apart from the Kia Sorento and maybe the Mazda CX-9, you're going to find more cargo capacity and passenger space in the Highlander's competitors. That's especially true in the third row. The second row slides a bit more to grant extra legroom now, but the third row remains awfully close to the floor, and it won't be long before your growing kids will feel cramped and claustrophobic in the way-back. Full-size teens and adults will be flat-out grumpy. That said, the Highlander's smaller size might be just right for many buyers who appreciate its more manageable dimensions when parking or maneuvering in tight spots. Plus, if you only need that third row for occasional use and just a little more space than what a RAV4 provides, it really won't matter that the Highlander can't match its competitors' jumbo size. We expect pricing for the 2020 Highlander to be announced closer to its on-sale date in December 2019, with the Hybrid arriving in February 2020. Specifically, it should correspond with our first test drive opportunity, likely in November. We do have a pretty comprehensive features breakdown, however, which you can see below. Standard equipment on the Highlander L includes 18-inch alloy wheels, three-zone automatic climate control, accident avoidance tech features (see safety section below), full-speed adaptive cruise control, LED headlights, rear privacy glass, proximity entry and push-button start, an eight-way power driver seat and the 8-inch touchscreen. The LE additions include a power liftgate, blind-spot warning, LED foglamps, and a leather-wrapped steering wheel. The XLE additions include automatic headlights, roof rails, a sunroof, heated front seats, driver power lumbar, a four-way power passenger seat, SofTex vinyl upholstery, second-row sunshades and an auto-dimming rearview mirror. The Limited additions include 20-inch wheels, a handsfree power liftgate, upgraded LED headlights, a cargo cover, driver memory settings, ventilated front seats, leather upholstery, integrated navigation and a JBL sound system upgrade. The Platinum additions include adaptive and self-leveling headlights, automatic wipers, a panoramic sunroof bird's-eye parking camera, a head-up display, a digital rearview mirror camera, perforated leather upholstery, heated second-row seats and a 12.3-inch touchscreen. """ features =["steering","touch screen","LED headlight"] def findcarfeatures(features, document, match=80): result=[] for feature in features: lenfeature = len(feature.split(" ")) word_tokens = nltk.word_tokenize(document) #filterd_word_tokens = [w for w in word_tokens if not w in stop_words] for i in range (len(word_tokens)-lenfeature+1): wordtocompare = "" j=0 for j in range(i, i+lenfeature): if re.search(r'[,!?{}\[\]\"\"\'\']',word_tokens[j]): break wordtocompare = wordtocompare+" "+word_tokens[j].lower() wordtocompare.strip() if not wordtocompare=="": if(fuzz.ratio(wordtocompare,feature.lower())&gt; match): result.append([wordtocompare,feature,i,j]) return result findcarfeatures(features,document) Out[90]: [[' steering', 'steering', 353, 353], [' touchscreen .', 'touch screen', 334, 335], [' touchscreen .', 'touch screen', 474, 475], [' led headlights', 'LED headlight', 313, 314], [' headlights', 'LED headlight', 314, 315], [' headlights', 'LED headlight', 361, 362], [' led headlights', 'LED headlight', 408, 409], [' headlights', 'LED headlight', 409, 410], [' headlights', 'LED headlight', 442, 443]] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:02:21.873", "Id": "471939", "Score": "0", "body": "Have you profiled the code and do you know where your bottlenecks are?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:04:30.497", "Id": "471940", "Score": "0", "body": "@pacmaninbw hi, the if(fuzz.ratio(wordtocompare,feature.lower())> match): portion is where it's taking a long time to process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:08:20.640", "Id": "471944", "Score": "0", "body": "Please add that information to the question body." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T16:49:24.607", "Id": "472058", "Score": "0", "body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 5 → 4" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:25:03.663", "Id": "472572", "Score": "0", "body": "(Just winced - anyone remember [Neuro-Linguistic Programming](https://en.m.wikipedia.org/wiki/Neuro-linguistic_programming)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-20T15:29:14.203", "Id": "472573", "Score": "0", "body": "All questions must have a language tag. Python-3.x is not a language tag but is a version tag. Also tagging this with vectorization is just a lie." } ]
[ { "body": "<h2>Minor perf improvements</h2>\n\n<p>These are unlikely to impact your performance in a material way, but they are performance improvements nonetheless:</p>\n\n<pre><code>re.search(r'[,!?{}\\[\\]\\\"\\\"\\'\\']',word_tokens[j])\n</code></pre>\n\n<p>recompiles the regex every time. <code>re.compile()</code> outside of your loops so that this does not happen.</p>\n\n<p>Repeated concatenation such as this:</p>\n\n<pre><code>wordtocompare = wordtocompare+\" \"+word_tokens[j].lower()\n</code></pre>\n\n<p>can be a problem; strings in Python are immutable, so this is recreating a new string instance every time the concatenation is done. To avoid this, consider using <a href=\"https://docs.python.org/3.8/library/io.html#io.StringIO\" rel=\"nofollow noreferrer\"><code>StringIO</code></a> or <code>join</code> a generator.</p>\n\n<h2>Other improvements</h2>\n\n<pre><code>if not wordtocompare==\"\":\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if word_to_compare != \"\":\n</code></pre>\n\n<p>Also, <code>wordtocompare.strip()</code> is not being assigned to anything so it does not have any effect, currently.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T09:05:19.423", "Id": "473594", "Score": "0", "body": "Comparing `word_to_compare` against an empty string could just be `if word_to_compare`. String concatenation could be done simply by collecting elements into a `list`, then calling `\" \".join(list)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:55:11.263", "Id": "473631", "Score": "1", "body": "Re. comparing: you _could_ do that, but it would not be strictly equivalent (it would also include `None`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T13:56:21.193", "Id": "473632", "Score": "1", "body": "@HansLollo Re. concatenation: sometimes `join` will be worth it. What you do want to do is `join` from a generator. What you _don't_ want to do is `join` from a `list`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T14:07:29.527", "Id": "473636", "Score": "0", "body": "Yes, the comparison would no longer be equivalent. It should only be preferred if the strictness of comparing against an empty string is not needed. What do you mean with `join` from a `list`? Joining a generator is possibly the most efficient, but shouldn't joining a `list` still be more efficient than string concatenation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T14:12:17.930", "Id": "473637", "Score": "1", "body": "Joining will be more efficient than \"naive\" concatenation, but not necessarily more efficient that `StringIO`. That depends on a number of factors, including Python version and input size. See https://github.com/reinderien/py-cat-times" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-28T15:04:24.097", "Id": "473649", "Score": "0", "body": "That is interesting data in the link, thanks for that. However, in all scenarios, `join` seems to do better than `StringIO`? (in the plots from the PDF)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-06T19:49:55.013", "Id": "474577", "Score": "0", "body": "I am reviewing the github.com/reinderien/py-cat-times and hope to decipher the best joining method. I moved the tokenize method outside of the loop which sped it up by in half but considering the amount of text, it's still not scalable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-18T13:35:34.790", "Id": "475903", "Score": "0", "body": "FYI I am using Python 3.77 if that helps." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T16:06:46.847", "Id": "240635", "ParentId": "240585", "Score": "3" } } ]
{ "AcceptedAnswerId": "240635", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T19:52:18.720", "Id": "240585", "Score": "3", "Tags": [ "python", "performance", "algorithm", "natural-language-processing" ], "Title": "Reduce run time of NLP approximate matching code" }
240585
<p>I want to decode a request object before use it in an insert query. </p> <p>Request object containes the following JSON body:</p> <pre><code>{ "device":"887B53", "data":"89582c60", "station":"B0A6", "rssi":"-99.00", "time":"1586121398" } </code></pre> <p>That's the way I solved it:</p> <pre><code>const convert = { bin2dec : s =&gt; parseInt(s, 2).toString(10), bin2hex : s =&gt; parseInt(s, 2).toString(16), dec2bin : s =&gt; parseInt(s, 10).toString(2), dec2hex : s =&gt; parseInt(s, 10).toString(16), hex2bin : s =&gt; parseInt(s, 16).toString(2), hex2dec : s =&gt; parseInt(s, 16).toString(10) }; const binnumber = convert.hex2bin(request.payload.data); const MSB = binnumber.slice(8, 12); const LSB = binnumber.slice(18, 24); const LSB_MSB = convert.bin2dec(MSB.concat(LSB)); const number1 = (LSB_MSB-200)/8 ; const hum = convert.bin2dec(binnumber.slice(24, 32)); const number2 = hum * 0.5 const MSB2 = binnumber.slice(0, 1); const LSB2 = binnumber.slice(8, 12); const LSB_MSB2 = convert.bin2dec(MSB2.concat(LSB2)); const battery = LSB_MSB2*0.05*2.7 ; const device = request.payload.device; const data = request.payload.data; const station = request.payload.station; const rssi = request.payload.rssi; const time = request.payload.time; </code></pre> <p>The converted Data shows as following: </p> <p><a href="https://i.stack.imgur.com/eD22f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eD22f.png" alt="enter image description here"></a></p> <p>It looks really confusing and I'm sure there is a way to solve it cleaner and nicer. Does anywone have a suggestion?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T22:27:51.677", "Id": "471965", "Score": "0", "body": "Code looks quite reasonable to me. You *have* to do some kind of complicated string parsing and number manipulation, there isn't any way around coding that yourself. Only thing I see you can improve on is using destructuring on those last 5 lines instead, `const { device, data, ... } = request.payload`;" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:05:02.437", "Id": "240587", "Score": "2", "Tags": [ "javascript", "node.js", "functional-programming", "converting" ], "Title": "Decoding request object before use it in an Insert query" }
240587
<p>I have worked on this for quite a long while, and this is my 3rd attempt after completely demolishing 3 other 200 liners, and i really need ideas on how to make my code add more functionality or efficiency, or some python coding tricks, i can implement to make it more compact. I'm still a beginning with about a month of learning.</p> <p>this program is meant to run from the <strong>cmd</strong>: <strong>syntax = python "Text-Based Browser.py path" foldername</strong> - which essentially stores a folder to store the websites you visit, in shorter text, so the next time you visit the shortened site, it will be much faster. foldername is stored in Current Working Directory</p> <p>it has the following inputs in cmd: <br>1) <strong>back</strong>: checks the previous page, using stack implementation <br>2) <strong>exit</strong>: exits out the program <br>3) <strong>an Url</strong>: checks if the url is valid, and if it is valid then checks if a connection can be made, if a connection can be made, then it retrieves the html of the website, and then parses for the text based tags, and changes the "a" tags to the color blue using the colorama module, and writes the text in a file in the foldername. If the url is incorrect, prints a prompt</p> <pre class="lang-py prettyprint-override"><code>import sys import os import requests from bs4 import BeautifulSoup import colorama dir_name = '' if len(sys.argv) == 2: dir_name = sys.argv[1] if not os.path.exists(dir_name): os.mkdir(dir_name) path = dir_name + '/' if dir_name else '' colorama.init(autoreset=True) protocol = 'https://' def read_tab(file, directory): with open(directory + file, encoding='utf-8') as f: return f.readlines() def write_tab(file, directory, text_list): tab = file.split(protocol)[-1] tab = '.'.join(tab.split('.')[:-1]) with open(directory + tab, 'w', encoding='utf-8') as f: f.writelines(text_list) return tab def request_page(page): if '.' not in url: raise Exception if protocol not in page: page = protocol + page response = requests.get(page, headers={'user-agent': 'Mozilla/5.0'}, timeout=5) if not response: raise Exception soup = BeautifulSoup(response.content, 'lxml') tag_set = {'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'a', 'ul', 'ol', 'li'} text_list = [] for string in soup.strings: parents = {parent.name for parent in string.parents} if tag_set &amp; parents: txt = '\033[34m' + str(string).strip() if 'a' in parents else str(string).strip() _ = text_list.append(txt + '\n') if len(txt) &gt; 2 and not txt.startswith(('$', '.', '@')) else 0 return text_list history_stack = [] last_page = None while True: content = [] url = input("Text Based Webbrowser\nEnter Url/Action: ").strip() if url == 'back': if len(history_stack) == 0: continue url = history_stack.pop() else: _ = history_stack.append(last_page) if last_page else None if url == 'exit': break # Request URL and write Tab: try: content = request_page(url) except Exception: # Read Tab if error of requesting (this is tab probably): try: content = read_tab(url, path) except Exception: print('Error: Incorrect URL or Tab, enter again') continue else: last_page = url else: last_page = write_tab(url, path, content) finally: _ = [print(line, end='') for line in content] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T14:27:08.207", "Id": "472041", "Score": "1", "body": "Re. _please go easy on me_ - There's no expectation for reviewers to hold back reviews so far as they're on-topic and constructive; but policy requires that they be nice - https://meta.stackexchange.com/questions/240839/the-new-new-be-nice-policy-code-of-conduct-updated-with-your-feedback" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T15:53:20.357", "Id": "472053", "Score": "0", "body": "I'm not accusing you of having caused a misdemeanor - I'm saying that the extent to which reviewers answering this question go easy on you is that they be nice. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T15:56:05.983", "Id": "472054", "Score": "0", "body": "oh that was oblivious of me, sorry for not getting your point. There are quite the rumors, that stackexchange users are merciless with their reviews, it appears it's only a rumor and nothing else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T15:57:18.157", "Id": "472055", "Score": "0", "body": "StackOverflow can be pretty cutting sometimes, particularly for people who are not well-versed in the expected question format. I anecdotally find CodeReview to be more forgiving." } ]
[ { "body": "<h2>Use argparse</h2>\n\n<p><a href=\"https://docs.python.org/3.8/library/argparse.html\" rel=\"nofollow noreferrer\">Argparse</a> will give you cleaner code and a friendlier CLI. It will simplify much of this blob:</p>\n\n<pre><code>dir_name = ''\nif len(sys.argv) == 2:\n dir_name = sys.argv[1]\n if not os.path.exists(dir_name):\n os.mkdir(dir_name)\npath = dir_name + '/' if dir_name else ''\n</code></pre>\n\n<p>Also, for path handling and directory creation consider the use of <code>pathlib.Path</code>.</p>\n\n<h2>write_path</h2>\n\n<p>You're passing an URL into what you've called the <code>file</code> parameter, so that's confusing. Also, it appears that you're manually parsing that URL using <code>split</code> when you're better off using <a href=\"https://docs.python.org/3/library/urllib.parse.html\" rel=\"nofollow noreferrer\"><code>urllib.parse</code></a>.</p>\n\n<h2>Ternary</h2>\n\n<p>This:</p>\n\n<pre><code>_ = text_list.append(txt + '\\n') if len(txt) &gt; 2 and not txt.startswith(('$', '.', '@')) else 0\n</code></pre>\n\n<p>should be expanded out into a plain <code>if</code>:</p>\n\n<pre><code>if len(txt) &gt; 2 and not txt.startswith(('$', '.', '@')):\n text_list.append(txt + '\\n')\n</code></pre>\n\n<p>Similarly, this:</p>\n\n<pre><code> _ = [print(line, end='') for line in content]\n</code></pre>\n\n<p>is doing a comprehension and throwing away the result. Instead,</p>\n\n<pre><code>print(''.join(content))\n</code></pre>\n\n<h2>Error handling</h2>\n\n<pre><code>response = requests.get(page, headers={'user-agent': 'Mozilla/5.0'}, timeout=5)\nif not response:\n raise Exception\n</code></pre>\n\n<p>First, never raise a base <code>Exception</code> - you want to raise something more specific. That said, in this case, replace your <code>if</code> with a <code>response.raise_for_status()</code>.</p>\n\n<p>In a similar case,</p>\n\n<pre><code>if '.' not in url:\n raise Exception\n</code></pre>\n\n<p>should instead be raising something like <code>ValueError(f'Malformed URL {url}')</code>. It's also odd that this is referring to the global <code>url</code> variable instead of the <code>page</code> argument. Finally: to do this kind of validation (not sure why it matters that there's a dot in the URL), you should be using <code>urllib.parse</code>.</p>\n\n<h2>Global code</h2>\n\n<p>Pull everything from <code>history_stack = []</code> onwards into one or more functions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T15:49:08.143", "Id": "240633", "ParentId": "240590", "Score": "2" } } ]
{ "AcceptedAnswerId": "240633", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:20:43.083", "Id": "240590", "Score": "2", "Tags": [ "python", "python-3.x", "file-system", "web-scraping", "beautifulsoup" ], "Title": "A Text-Based Browser using Requests, Beautiful Soup, Sys, OS, and colorama" }
240590
<p>I am trying to encrypt/decrypt file using source code directly. The issue is how to properly do it after reading the file. </p> <pre><code>int crypto_aead_encrypt( unsigned char *c, unsigned long long *clen, const unsigned char *m, unsigned long long mlen, const unsigned char *ad, unsigned long long adlen, const unsigned char *nsec, const unsigned char *npub, const unsigned char *k ) </code></pre> <p>Working code: (plaintext is char *)</p> <pre><code>for (start = 0; start &lt; fileLength; start += 32) { int end = (start + 32); end = end &gt; fileLength ? fileLength : end; strncpy(msg, plaintext + start, end - start); // encrypt crypto_aead_encrypt(ct, &amp;clen, msg, mlen, ad, adlen, NULL, nonce, key); // decryption crypto_aead_decrypt(msg2, &amp;mlen2, NULL, ct, clen, ad, adlen, nonce, key); } </code></pre> <p>This is the function, and the max limit of the message <code>m</code> is 32 bits, which would make encrypting/decrypt very long for large files (ex. 1GB). Is there a way to perform the encrypting as fast as if it were from the library. Neglecting the code above, ex. how does OpenSSL do it when -in is provided? </p> <p>The way I have it is to read the file, save it to an <code>char *</code> and then take 32 bits and enc each one. So I am wondering if there is a proper more correct way to do it.</p> <p>Edit: reference implementation like <a href="https://github.com/ascon/ascon-c/tree/caf2a13b7f4f6487ebb1949df2f70fb098da54a4/crypto_aead/ascon128v12/ref" rel="nofollow noreferrer">ascon</a> or <a href="https://www.isical.ac.in/~lightweight/beetle/resource.html" rel="nofollow noreferrer">photon-beetle</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T22:53:35.473", "Id": "471968", "Score": "0", "body": "**Why** do you first read the entire file, and more importantly, **why** do you only encrypt 32 bits / 4 bytes at a time? That don't make no sense at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T01:48:47.177", "Id": "471974", "Score": "0", "body": "@MaartenBodewes 32 bits cause that's the max the algorithm accepts (max msg size for encrypting/decrypting blocks). And I'm not sure how else to do it without reading the entire file first, I read it and store it then process the stored" } ]
[ { "body": "<p>I think you're confused here. The GCM algorithm has a 96 bit nonce, and fills the rest of the 128 bit block size with a 32 bit counter. So you have 2^32 full blocks at your disposal, or about 64 GiB. That's - uh - slightly more than 32 bits (well, OK, the counter starts at 2, so you'd have 48 bytes less than that, better keep it at 32 GiB or 48 GiB).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T13:17:38.993", "Id": "472029", "Score": "0", "body": "Thanks! how do you suggest to do it then? I mean encrytping the plaintext directlt? I tried that but I kept getting error due to exceeding the limit. For example I am using [photon-beetle](https://www.isical.ac.in/~lightweight/beetle/resource.html) and particularly [this](https://github.com/ascon/ascon-c/blob/caf2a13b7f4f6487ebb1949df2f70fb098da54a4/tests/genkat_aead.c) as a tempalte to do the enc/dec where the max is 32" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T13:51:52.713", "Id": "472035", "Score": "0", "body": "I'm not entirely sure what goes wrong; I'd have to debug the code for that. I can see in the photon code that `size_t Dlen_inblocks = (Dlen_inbytes + RATE_INBYTES - 1) / RATE_INBYTES;` which splits up the input as 4 byte blocks. That's not something you do if the total input can be 32 bits (which makes no sense whatsoever for an AEAD cipher)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T20:15:52.253", "Id": "472080", "Score": "0", "body": "Ah ok, and the other thing that the crypto_aead_encrypt takes in m as a unsigned char so that means after it passes there it's converted to uint8_t (`const uint8_t *Data_in`). In any case, I even tried again sending fill plaintext and the fill length but it's a buffer overflow due to the full plaintext I'm pretty sure \n\n\n**Edit:** I changed the code and was able to get it to work! however, not for large files (ex. 16mb), a stack overflow. I'm currently really stuck on where or how I could fix it though, tried different ways to debug it but no success so far" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T00:13:32.983", "Id": "472099", "Score": "0", "body": "I guess the error shows the place where these kind of questions are more on topic :) Glad you got the initial issue solved. What I wrote was for GCM (which I wrongly assumed was the block cipher), if there is a block of 4 bytes then of course the algorithm may have different limits. You can e.g. split up the file in chunks and encrypt them separately. You'd have to create a MAC over the authentication tags though, otherwise the chunks may be reordere.d by an adversary." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T02:02:34.447", "Id": "240602", "ParentId": "240591", "Score": "2" } }, { "body": "<blockquote>\n <p>So I am wondering if there is a proper more correct way to do it.</p>\n</blockquote>\n\n<p><strong>binary data</strong></p>\n\n<p>An encryption of a file should not assume it is text lacking a <code>'\\0'</code>. As a binary file, data may include <em>null characters</em> which will incorrectly copy using <code>strncpy()</code>.</p>\n\n<pre><code>// strncpy(msg, plaintext + start, end - start);\nmemcpy(msg, plaintext + start, end - start);\n</code></pre>\n\n<p><strong>LARGE files</strong></p>\n\n<p>\"for large files (ex. 1GB)\" --> 1GB is not so large. Rather than limit file size to the <code>int</code> range, use <code>size_t</code>. That is typicality at least 2x the positive range or perhaps billions x. Code is limited in design to <code>size_t</code> given the usage of a single array. Might as well use as much range as possible.</p>\n\n<pre><code>size_t start;\n... \n// int end = (start + 32);\nsize_t end = (start + 32);\n</code></pre>\n\n<p>Better code would use <code>unsigned long long</code> like the <code>int crypto_aead_decrypt(unsigned char* m, unsigned long long* mlen, ...)</code> signature.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-18T14:14:33.557", "Id": "472281", "Score": "0", "body": "Good point about the `int`. It made no sense for 32 bit input, but for larger input e.g. a 2 GiB - 1 max size may be prohibitive. The `strncpy` is interesting as well; I presumed readable text when I saw that, but that might be a somewhat presumptuous :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T21:59:17.800", "Id": "240716", "ParentId": "240591", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-15T20:42:57.047", "Id": "240591", "Score": "4", "Tags": [ "performance", "c", "file", "cryptography", "encryption" ], "Title": "Encrypting file from source AEAD" }
240591
<p>This is a revised copy of the Mail Crypt library based on the recommendations from the last post, as well as reviewing recommendations from the first post that I misunderstood.<br> [Last post] <a href="https://codereview.stackexchange.com/questions/240465/mail-crypt-library-for-encrypted-email">Mail Crypt Library for encrypted email</a><br> [First Post] <a href="https://codereview.stackexchange.com/questions/240310/mail-crypt-cli-encrypted-email-wrapper-for-gmail">Mail Crypt CLI encrypted email wrapper for Gmail</a> </p> <p>Change Log: </p> <ol> <li>Removed try/except block from tag/sig status so end user gets the error. </li> <li>Un-bundled context manager so public and private keys are handled separately. </li> <li>encrypted message return uses join and hex with for loop rather that .hex after every item. </li> <li>decrypt message now unpack each item into there own var rather than as a list. </li> <li>import keys now unpacks into 2 var rather than list. </li> <li>get_emails unpack just what is need into data and rest is pass to underscore. </li> <li>created fetch function in email to replace 3 identical fetch calls in Email. (get_emails, read_encrypted, read) </li> <li>Keys.export_keys renamed to Keys.save_keys to have symmetric nomenclature. </li> <li>Split Keys class into CreateKeys, PublicKeysStore, and PersonalKeys. </li> <li>rsa_key_length is no longer a class constant but now an arg, change_rsa_key_length class method removed. </li> <li>split load my keys into get_public and get_private. </li> <li>removed the private and public key args from MailCrypt so keys must now be passed into encrypt and decrypt function. </li> <li>static method decorator added to decrypt message. </li> <li>update keys method removed from MailCrypt since MailCrypt no longer handles keys. </li> <li>removed constant of aes_session_key_length from MailCrypt, its now an arg passed into encrypt_msg with a defalut of 32. </li> <li>encrypt message is now a static method. </li> <li>Email class split into EmailSMTP and EmailIMAP (Grouped based on which server is used). </li> <li>SMTP port is no longer a constant, can be passed in or default used. </li> <li>removed change smtp port method since port is now an arg. </li> <li>fetch now replaces read in EmailIMAP. </li> <li>PublicKey object now must be passed into EmailSMTP to handle public key look up. </li> </ol> <pre><code>"""Library for send and receiveing encrypted emails.""" import pickle import email import imaplib import smtplib from Crypto.Hash import SHA512 from Crypto.Cipher import PKCS1_OAEP from Crypto.Cipher import AES from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Signature import pss class MailCrypt: """Core compents for encryption/decryption and key generation.""" @staticmethod def encrypt_msg(message, recpient_public_key, private_key, aes_session_key_length=32): """Generates a session key to use with AES to encrypt the message, then encrypts the session key with the recipients public key. Everything is returned in hex format to be better sent over email.""" session_key = get_random_bytes(aes_session_key_length) aes_cipher = AES.new(session_key, AES.MODE_EAX) aes_cipher_text, tag = aes_cipher.encrypt_and_digest(message) pub = PKCS1_OAEP.new(recpient_public_key).encrypt(session_key) priv = pss.new(private_key).sign(SHA512.new(message)) return ' '.join( part.hex() for part in ( aes_cipher_text, tag, aes_cipher.nonce, pub, priv, ) ) @staticmethod def decrypt_msg(message, sender_public_key, private_key): """Splits the message into its sections Decrypts the session key, then decrypts the message body. If aes_cipher.verify throws an error that means an invalid tag was provided If pss.new throws an error that means the message signature is invalid""" aes_cipher_text, tag, nonce, enc_session_key, signature = ( value.encode().fromhex(value) for value in message.split(' ')) aes_cipher = AES.new( PKCS1_OAEP.new(private_key).decrypt(enc_session_key), AES.MODE_EAX, nonce=nonce, ) clear_text = aes_cipher.decrypt(aes_cipher_text) aes_cipher.verify(tag) pss.new(sender_public_key).verify(SHA512.new(clear_text), signature) return clear_text class PublicKey: """Handles public key storage and retrieval.""" def __init__(self): self.key_dict = {} def load_keys(self): """Read public keys in from file. Must be in same folder as script is run from.""" with open('public_key_bank.pkl', 'rb') as fpublic_key_file: self.key_dict = pickle.load(fpublic_key_file) def save_keys(self): """Saves key_dict to file.""" with open('public_key_bank.pkl', 'wb') as fpublic_key_file: pickle.dump(self.key_dict, fpublic_key_file) def add_key(self, address, key): """Adds key to to key_dict.""" self.key_dict[address] = key def retreive_key(self, address): """Retrieves public key based on email.""" return RSA.import_key(self.key_dict[address]) def remove_key(self, address): """Removes key from dict""" self.key_dict.pop(address) class PersonalKeys: """Handles users public and private keys.""" def __init__(self): self.my_private_key = None self.my_public_key = None def get_private(self, passwd): """Loads private key in from file.""" with open('private_key.pem', 'r') as fprivate_key_save: self.my_private_key = RSA.import_key(fprivate_key_save.read(), passphrase=passwd) def get_public(self): """Loads public key in from file.""" with open('my_public_key.pem', 'r') as fpublic_key_save: self.my_public_key = RSA.import_key(fpublic_key_save.read()) class CreateKeys: """Handles key pair creation and storage.""" def __init__(self, rsa_key_length=4096): self.rsa_key_length = rsa_key_length def generate_keys(self, passwd): """Generates public and private key pairs and exports them as .pem files.""" private_key = RSA.generate(self.rsa_key_length) public_key = private_key.publickey() with open('my_public_key.pem', 'wb') as fpub: fpub.write(public_key.export_key('PEM')) with open('private_key.pem', 'wb') as fpri: fpri.write(private_key.export_key('PEM', passphrase=passwd)) def generate_keys_test(self): """"Used for testing, returns key pair.""" private_key = RSA.generate(self.rsa_key_length) public_key = private_key.publickey() return private_key, public_key class EmailSMTP: """Handles the SMTP functionality.""" def __init__(self, username, passwd, server_address, pub_key_obj, per_key_obj, port=465): self.smtp = smtplib.SMTP_SSL(server_address, port) self.smtp.ehlo() self.username = username self.smtp.login(username, passwd) self.publickeys = pub_key_obj self.private = per_key_obj def close_connection(self): """Closes connection to server.""" self.smtp.close() def send(self, recipient, message): """Sends plain text email.""" self.smtp.sendmail(self.username, recipient, message) def send_encrypted(self, recipient, message): """Sends encrypted message.""" message = MailCrypt.encrypt_msg(message.encode(), self.publickeys.retreive_key(recipient), self.private.my_private_key) self.smtp.sendmail(self.username, recipient, message) def share_public_key(self, recipient): """Sends public key.""" self.send(recipient, self.private.my_public_key.export_key('PEM')) class EmailIMAP: """Handles the IMAP sever funcionality""" def __init__(self, username, passwd, server_address): self.imap = imaplib.IMAP4_SSL(server_address) self.imap.login(username, passwd) self.imap.select('inbox') def close_connection(self): """Logs out and closes connection to the server""" self.imap.logout() self.imap.close() def get_emails(self): """Yeilds uid and senders address for every message in the inbox folder.""" _, data, *_ = self.imap.uid('search', None, 'ALL') for uid in data[0].decode().split(' '): sender, _ = self.fetch(uid) yield uid, sender def fetch(self, uid): """returns sender address and message payload""" _, email_data = self.imap.uid('fetch', uid, '(RFC822)') msg = email.message_from_bytes(email_data[0][1]) return msg['From'], msg.get_payload() def read_encrypted(self, uid, sender_public, private): """Fetches email from given uid and returns clear text.""" _, payload = self.fetch(uid) return MailCrypt.decrypt_msg(payload, sender_public, private) def mark_delete(self, uid): """Moves the specified email to trash folder. If useing email provider other than gmail 'Trash' needs to be changed to whatever folder that service uses.""" self.imap.uid('store', uid, '+X-GM-LABELS', '(\\Trash)') def delete_all(self): """Empties the trash folder.""" self.imap.expunge() def import_key(self): """Checks message payloads for public keys, if found it yeilds the senders email address and the public key.""" for uid, sender in self.get_emails(): sender, msg_body = self.fetch(uid) if 'PUBLIC' in msg_body: yield sender, msg_body </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T15:48:21.133", "Id": "472051", "Score": "1", "body": "When are you going to add the CLI again?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T21:04:53.540", "Id": "472086", "Score": "0", "body": "I'm planning on building a CLI for it once this supporting library meets the standard and more or less meets the approval of others in this community. I was also considering releasing this library to be available through pip if there is enough interest in it." } ]
[ { "body": "<h2>Typo</h2>\n\n<p><code>recpient_public_key</code> -> <code>recipient_public_key</code></p>\n\n<h2>Type hints</h2>\n\n<p>Adding some would help for this code to be self-documenting, and to a certain extent, verified by some static analysis tools. For an example, your constructor:</p>\n\n<pre><code>def encrypt_msg(message, recpient_public_key, private_key, aes_session_key_length=32):\n</code></pre>\n\n<p>could be (I'm guessing a little)</p>\n\n<pre><code>def encrypt_msg(message: str, recpient_public_key: bytes, private_key: bytes, aes_session_key_length: int = 32):\n</code></pre>\n\n<p>Your other function signatures could similarly benefit, as well as member variables:</p>\n\n<pre><code> self.key_dict = {}\n</code></pre>\n\n<p>I see the key is an email address string, and I assume the value is a stringy key:</p>\n\n<pre><code>self.key_dict: Dict[str, str] = {}\n</code></pre>\n\n<h2>Context managers</h2>\n\n<p><code>EmailSMTP</code>, since it needs to close <code>self.smtp</code>, should implement <code>__enter__</code>/<code>__exit__</code> to do so, and any code you have that calls this should use it in a <code>with</code>. <code>EmailIMAP</code> should do the same.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T14:18:18.497", "Id": "472037", "Score": "1", "body": "Yep, PEP8 is a little odd that way. It says _When combining an argument annotation with a default value, however, do use spaces around the = sign_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T14:21:41.733", "Id": "472039", "Score": "1", "body": "I think it's a reasonable exception to the rule :) Otherwise I can see myself misreading some default arguments as part of the type." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T14:09:48.530", "Id": "240629", "ParentId": "240603", "Score": "3" } }, { "body": "<p>IMO good design is:</p>\n\n<ol>\n<li>It solves the purpose it sets out to solve.</li>\n<li>It only solves the problem you set out to solve.</li>\n<li>It doesn't add extra problems for the user.</li>\n<li>It doesn't solve extra problems for the user, making it hard to maintain.</li>\n</ol>\n\n<p><code>MailCrypt</code></p>\n\n<ol>\n<li>❌ It is not clear what it solves.</li>\n<li>-</li>\n<li>❌ The code is more annoying to use than if the code were just functions.</li>\n<li>❌ The code is more annoying to maintain than if it were just functions.</li>\n</ol>\n\n<p><code>PublicKey</code></p>\n\n<ol>\n<li> It stores public keys.</li>\n<li></li>\n<li><p>❌</p>\n\n<ul>\n<li>Save and load keys can be abstracted away.</li>\n<li>If the program doesn't exit as expected all the new keys are gone.</li>\n<li>Why can't I specify my own file location?</li>\n</ul></li>\n<li><p></p></li>\n</ol>\n\n<p><code>PersonalKeys</code> and <code>CreateKeys</code></p>\n\n<ol>\n<li> <em>Together</em> they handle personal keys.</li>\n<li> They handle personal keys.</li>\n<li><p>❌</p>\n\n<ul>\n<li>Why do I need two classes for public keys?</li>\n<li>Why does <code>get_private</code> and <code>get_public</code> not give me what I asked for?</li>\n<li>Why can I not specify my own file location?</li>\n<li>Why does generating my keys not give them to me?</li>\n<li>Why doesn't <code>my_public_key</code> update when I generate new keys?</li>\n</ul>\n\n<p><br>\nOverall, why do I have to jump through loops to interact with my keys?</p>\n\n<p>Please convert the following code to use your classes to see which is easier to use.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>personal = PersonalKeys(...)\npublic = personal.public\n_, private = personal.generate()\np, _ = personal.generate(save=True)\nassert personal.public == p\nassert personal.public != public\nassert personal.private != private\npersonal.save(public, private)\nassert personal.public == public\nassert personal.private == private\n</code></pre></li>\n<li><p> Why does <code>generate_keys</code> not call <code>generate_keys_test</code>?</p></li>\n</ol>\n\n<p><code>EmailSMTP</code> and <code>EmailIMAP</code></p>\n\n<ol>\n<li>❌ <em>Together</em> they handle emails (collection) and email (items).</li>\n<li>❌ They are handling both the collection and the item.</li>\n<li><p>❌ The interface is clunky. Contrast with usage of <a href=\"https://codereview.stackexchange.com/a/240350/42401\">my previous answer</a>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>mc = MailCrypt()\nfor email in mc.emails():\n try:\n data = email.read()\n except &lt;insert decrypt error&gt;:\n email.import_key()\n data = email.read()\n\n if 'delete' in data:\n email.delete()\n</code></pre></li>\n<li><p>❌ It's solving two things at once.</p></li>\n</ol>\n\n<hr>\n\n<p>The CLI gives your code purpose and shows you the usability problems of your code, helping to find both 1 and 3.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T00:11:06.943", "Id": "472096", "Score": "1", "body": "The use of Unicode icons is fun." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T00:11:22.577", "Id": "472097", "Score": "0", "body": "As always I greatly appreciate your feedback. As for the CLI I have written a bare bones one for each submission for testing and to check it meets functionality needed. Could you clarify the following: Are you suggesting just re-naming the MailCrypt class or removal of it entirely and have the two methods just be function and not be contained in a class? When you suggest the abstraction of save/load keys I'm not sure what you mean. (I know what abstraction means) As for not being able to specify file location, that is on the way. For SMTP/IMAP I grouped them based on what they interact with" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T00:11:38.547", "Id": "472098", "Score": "0", "body": "SMTP handling all outgoing mail and IMAP handling all incoming mails. I did not quite understand why in your previous response half of the email functionality was in MailCrypt and the other half was in Email with SMTP and IMAP intermixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T01:48:30.400", "Id": "472102", "Score": "1", "body": "@JoeSmith \"just be function and not be contained in a class\". Please reread the code I provided for `PublicStore` in my previous answer - same functionality no `save` / `load`. I'm not sure if you want me to reply to the other things, since there seems to be no questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T01:55:21.203", "Id": "472103", "Score": "1", "body": "@JoeSmith To note whilst I have said that `encrypt_msg` would be better as just a function. I don't think that's the best solution. My answer isn't a \"do this\" list this time, instead really think about the points I've raised and see if you'd put it somewhere else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T02:01:57.757", "Id": "472104", "Score": "0", "body": "@Peilonrayz I appreciate the response,yes you have provided the direction for me to better understand your recommendations, the rest was more of an explanation of where I was coming from in the approach I took." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T23:04:56.897", "Id": "240657", "ParentId": "240603", "Score": "3" } } ]
{ "AcceptedAnswerId": "240657", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T02:15:19.827", "Id": "240603", "Score": "1", "Tags": [ "python", "python-3.x", "cryptography", "email" ], "Title": "Mail Crypt Library for encrypted email [REVISION]" }
240603
<p>I'm working on an article about encapsulation in OOP, and I'm using the FizzBuzz problem to demonstrate what I think is so great about it. I'm hoping to share this with developers that might also be intermediate, as a way to start building a bridge for understanding common OO principles.</p> <p>To this end, any feedback, criticism, or questions are greatly appreciated.</p> <p>The concerns I'm trying to extract and encapsulate are:</p> <ul> <li>The printing of the numbers </li> <li>The iteration of the collection </li> <li>The logic for determining what should be returned</li> </ul> <pre class="lang-rb prettyprint-override"><code>class FizzNumber FIZZ_MAP = { "Fizzbuzz" =&gt; :fizzbuzz?, "Fizz" =&gt; :fizz?, "Buzz" =&gt; :buzz? } def initialize(number) @number = number end def fizz? @number % 3 == 0 end def buzz? @number % 5 == 0 end def fizzbuzz? fizz? &amp;&amp; buzz? end def fizz_value value = FIZZ_MAP.find { |key, value| send(value) } value&amp;.first || @number.to_s end end class FizzBuzzer include Enumerable def initialize(collection) @collection = collection end def each @collection.each do |item| yield FizzNumber.new(item) end end end fizzer = FizzBuzzer.new((1..100).to_a) puts fizzer.map(&amp;:fizz_value).join("\n") </code></pre>
[]
[ { "body": "<blockquote>\n<p>To this end, any feedback, criticism, or questions are greatly appreciated.</p>\n</blockquote>\n<p>Here are some ideas to improve the code.</p>\n<h2>Split printing and logic</h2>\n<p>Might be debatable but from my POV the</p>\n<blockquote>\n<p>The printing of the numbers</p>\n</blockquote>\n<p>and</p>\n<blockquote>\n<p>The logic for determining what should be returned</p>\n</blockquote>\n<p>are not split.</p>\n<p>One of the goals of object oriented design is to make the code easier to change. So imagine we want to implement now to print <code>Boom</code> if a number <code>number % 10 == 0</code>. How would we do this? We would need to implement a <code>BoomNumber</code> class and change <code>FizzBuzzer</code> and might even change the main method because <code>fizz_value</code> does not make sense anymore. Not good!</p>\n<p>In this example we can just swap out the <code>builder</code> and it would work.</p>\n<pre><code>class PrintableNumber\n def initialize(name)\n @name = name\n end\n\n def to_s\n @name\n end\nend\n\nclass BoomNumberBuilder\n def initialize(number)\n @number = number\n end\n\n def build\n PrintableNumber.new(name)\n end\n\n private\n\n attr_reader :number\n\n def name\n if boom?\n &quot;Boom&quot;\n else\n number\n end\n end\n \n def boom?\n number % 10 == 0\n end\nend\n\nclass FizzNumberBuilder\n def initialize(number)\n @number = number\n end\n\n def build\n PrintableNumber.new(name)\n end\n\n private\n\n attr_reader :number\n\n def name\n if fizzbuzz?\n &quot;FizzBuzz&quot;\n elsif fizz?\n &quot;Fizz&quot;\n elsif buzz?\n &quot;Buzz&quot;\n else\n number\n end\n end\n\n def fizzbuzz?\n fizz? &amp;&amp; buzz?\n end\n\n def fizz?\n number % 3 == 0\n end\n\n def buzz?\n number % 5 == 0\n end\nend\n\nclass PrintableNumberCollector\n include Enumerable\n\n def initialize(collection, builder = FizzNumberBuilder)\n @collection = collection\n @builder = builder\n end\n\n def each\n collection.each do |item|\n yield builder.new(item).build\n end\n end\n\n private\n\n attr_reader :collection, :builder\nend\n\nputs &quot;== Fizzer ==&quot;\nfizzer = PrintableNumberCollector.new((1..10).to_a)\nputs fizzer.map(&amp;:to_s).join(&quot;\\n&quot;)\n\nputs &quot;== Boomer ==&quot;\nboomer = PrintableNumberCollector.new((1..10).to_a, BoomNumberBuilder)\nputs boomer.map(&amp;:to_s).join(&quot;\\n&quot;)\n</code></pre>\n<h2> Implement common interface</h2>\n<p>In your <code>FizzNumber</code> class you implement a <code>fizz_value</code> method which you then use in your main <code>fizzer.map(&amp;:fizz_value).join(&quot;\\n&quot;)</code>. This creates an unnecessary coupling. If you look into the method, you can already see what the method name should be <code>number.to_s</code></p>\n<pre class=\"lang-rb prettyprint-override\"><code> def fizz_value\n value = FIZZ_MAP.find { |key, value| send(value) }\n value&amp;.first || @number.to_s\n end\nend\n</code></pre>\n<p>so a better function name would be</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def to_s\n value&amp;.first || @number.to_s\nend\n\nprivate\n\ndef value\n FIZZ_MAP.find { |key, value| send(value) }\nend\n</code></pre>\n<h2>Avoid meta programming</h2>\n<p>Try to avoid meta programming (<code>send</code>) if not absolutely necessary. It makes the code a lot harder to read. You only have 4 different cases which can easily reflected with an if else.</p>\n<pre class=\"lang-rb prettyprint-override\"><code> def to_s\n if fizzbuzz?\n &quot;FizzBuzz&quot;\n elsif fizz?\n &quot;Fizz&quot;\n elsif buzz?\n &quot;Buzz&quot;\n else\n number\n end\n end\n</code></pre>\n<h2>Use getter and setter</h2>\n<p>Instead of using instance variables <code>@collection</code> you should try to use getter / setter methods. If you need to do e.g. validations or some processing of the variable, you only need to change one place.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class FizzBuzzer\n attr_reader :collection\n\n def each\n collection.each do |item|\n yield FizzNumber.new(item)\n end\n end\nend\n</code></pre>\n<h2>Use simple delegator</h2>\n<p>Instead of implementing the <code>each</code> method you could also use the <code>SimpleDelegator</code> module.</p>\n<p><a href=\"https://ruby-doc.org/stdlib-2.5.1/libdoc/delegate/rdoc/SimpleDelegator.html\" rel=\"nofollow noreferrer\">https://ruby-doc.org/stdlib-2.5.1/libdoc/delegate/rdoc/SimpleDelegator.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-09T15:22:14.120", "Id": "478158", "Score": "0", "body": "Hey Thanks! When I said separate the printing from the logic, I just meant that the consumer/executing context should be responsible for actually printing the numbers. It appears you do that in your example as well. I'll definitely look through this. Good stuff." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-08T14:13:21.867", "Id": "243560", "ParentId": "240605", "Score": "0" } } ]
{ "AcceptedAnswerId": "243560", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T02:59:33.227", "Id": "240605", "Score": "2", "Tags": [ "ruby", "fizzbuzz" ], "Title": "FizzBuzz encapsulation In Ruby (identifying and separating concerns)" }
240605
<p>Problem statement:</p> <blockquote> <p>Given a string, look for a mirror image (backwards) string at both the beginning and end of the given string. In other words, zero or more characters at the very begining of the given string, and at the very end of the string in reverse order (possibly overlapping). For example, the string "abXYZba" has the mirror end "ab".</p> </blockquote> <p>Examples:</p> <ul> <li>mirrorEnds("abXYZba") → "ab"</li> <li>mirrorEnds("abca") → "a"</li> <li>mirrorEnds("aba") → "aba"</li> </ul> <p>Below is my solution to the problem in java: </p> <pre><code>public String mirrorEnds(String string) { final int len = string.length(); final int half = len / 2; String result = ""; for (int i = 0; i &lt; half; i++) { if (string.charAt(i) != string.charAt(len -1 -i)) { break; } else { result += string.substring(i, i + 1); } } return result.length() == half ? string : result; } </code></pre> <p>Is it safe to say that in terms of time complexity the solution is optimal already? Any other review comments are also welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T23:04:26.543", "Id": "472240", "Score": "1", "body": "I observe that the problem statement does not specify anything about the output and the title indicates that the output is a boolean, not a string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-21T19:12:35.610", "Id": "472748", "Score": "0", "body": "Reverse the string into string1 then compare String to String1 for length = 1 to StringLength / 2?" } ]
[ { "body": "<p>Below your question:</p>\n\n<blockquote>\n <p>Is it safe to say that in terms of time complexity the solution is\n optimal already?</p>\n</blockquote>\n\n<p>Yes, you are comparing chars from front and back of the string and stop when you encounter two different chars so this is a complexity O(n).</p>\n\n<p>Some minor changes to your code, instead of iterate over your string transform it to a char array and instead of break the cycle return directly the result with the use of a <code>StringBuilder</code> for the result:</p>\n\n<pre><code>char[] arr = string.toCharArray();\n\nStringBuilder builder = new StringBuilder();\nfor (int i = 0; i &lt; half; ++i) {\n if (arr[i] != arr[len -1 -i]) {\n return builder.toString();\n }\n builder.append(arr[i]);\n}\n\nreturn string;\n</code></pre>\n\n<p>In this way you avoid the use of consecutive creation of substrings and the code is simpler.</p>\n\n<p>Your method can be rewritten then in this equivalent way:</p>\n\n<pre><code>public static String mirrorEnds(String string) {\n final int len = string.length();\n final int half = len / 2;\n char[] arr = string.toCharArray();\n\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i &lt; half; ++i) {\n if (arr[i] != arr[len -1 -i]) {\n return builder.toString();\n }\n builder.append(arr[i]);\n }\n\n return string;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T12:27:42.963", "Id": "472024", "Score": "0", "body": "Could also use `int mirroredPosition = string.length()-1` decreasing inside loop instead of `len-1 -i` to make it clear. Optionally check for null or empty string before." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T14:35:10.690", "Id": "472042", "Score": "0", "body": "@hc_dev. Agree ,it is possible to use `mirroredPosition`. If the string is null it will raise the NPE when you call `length()` and in case of empty string it will not enter the cycle directly returning the empty string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T23:11:52.520", "Id": "472091", "Score": "5", "body": "You don't even need StringBuilder. If you just take a substring of the original string with the right number of elements, you're done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T23:17:43.227", "Id": "472092", "Score": "3", "body": "The repeated string concatenation means that OP's code does *not* have optimal time complexity, contrary to what you've said. It has worst case O(n^2) instead of linear runtime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T08:53:26.510", "Id": "472121", "Score": "0", "body": "@Turksarama. Completely agree with your thought. If you have the intention to upload an answer with your code sending here a comment so I know when you have done it, I upvote your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T09:34:18.927", "Id": "472133", "Score": "0", "body": "@KonradRudolph. I'm lot rusty about complexity so mine is probably a dumb question: the complexity is O(n ^ 2) because you are multiply the linear complexity of the loop O(n) for the complexity of substring operation that seemed me constant because bounds are always determined for every iteration and instead is 0(n) ? Thanks for your time, if I understand correctly and you are agree I would like to add your considerations as a note to my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T09:58:24.733", "Id": "472142", "Score": "1", "body": "@dariosicily The substring operation is constant (though needlessly inefficient). The *string concatenation* is not constant, since each concatenation operation will reallocate a larger buffer and copy all existing elements over (so each string concatenation is an O(n) operation in the length of the string, which in OP’s case goes from 1–n/2, and the sum of that is bounded by O(n^2)). This is fixed by your use of the `StringBuilder`, which has an (amortised) constant-time append operation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T10:14:36.983", "Id": "472145", "Score": "0", "body": "@KonradRudolph, What I can do is thank you for taking time and effort in writing a so detailed answer. Now I got it, thanks again for the great explanation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T15:52:19.360", "Id": "472187", "Score": "0", "body": "Adding to Konrad's comment - as written it's an n^2 algorithm, so it's misleading for you to say that it's linear and optimal. If you're trying to make some kind of distinction between finding the match and returning the match, you should be more explicit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-17T17:21:14.363", "Id": "472196", "Score": "0", "body": "@PierreMenard I'm agree with you." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T11:02:29.533", "Id": "240615", "ParentId": "240608", "Score": "9" } }, { "body": "<p>Algorithmic shortcuts like this should be documented with comments.</p>\n\n<pre><code>// Reaching half point means the string is a palindrome\nreturn result.length() == half ? string : result;\n</code></pre>\n\n<p>Dariosicily had everything else covered.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T13:25:04.903", "Id": "472030", "Score": "0", "body": "Agree on that advice, would even put that palindrome comment above `for` or at breaking inside, since explaining the loop's exit-condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T13:29:22.107", "Id": "472031", "Score": "0", "body": "Sorry Torben! Thought I was in plain SO first, then commented & downvoted. Think you must edit before I can revoke/upvote again " } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T12:40:15.783", "Id": "240620", "ParentId": "240608", "Score": "7" } }, { "body": "<p>The pattern of <strong>mirrored string</strong> is used also by algorithms that ckeck for a <strong><a href=\"http://en.wikipedia.org/wiki/Palindrome\" rel=\"nofollow noreferrer\">Palindrome</a></strong>.</p>\n\n<p>Such a Palindrome &amp; Java question was <a href=\"https://stackoverflow.com/questions/4138827/check-string-for-palindrome\">Check string for palindrome</a></p>\n\n<h3>Inspired by Palindrome checker</h3>\n\n<p>Inspired by one of the answers which was both concise and elegant:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static boolean isPalindrome(String s) {\n for (int i=0 , j=s.length()-1 ; i&lt;j ; i++ , j-- ) {\n if ( s.charAt(i) != s.charAt(j) ) {\n return false;\n }\n } \n return true;\n}\n</code></pre>\n\n<p>I adjusted <em>exit-condition</em> from <code>i&lt;j</code> to <code>i &lt; half</code> (comparing dynamic parts not needed).</p>\n\n<p>Then your extracting function may be implemented like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static String findMirroredPart(String s) {\n // optionally: check for null or empty respectively blank text\n\n final int half = s.length / 2;\n int i=0;\n\n for (int j = s.length()-1; i &lt; half ; i++, j-- ) {\n if (s.charAt(i) != s.charAt(j)) {\n break;\n }\n }\n\n String mirroredPartOrPalindrome = i &lt; half ? s.substring(0,i) : s;\n return mirroredPartOrPalindrome;\n}\n</code></pre>\n\n<h3>Benefits are:</h3>\n\n<ul>\n<li>name expresses what's happening: <code>findMirroredPart</code> (also <code>static</code>)</li>\n<li>mirrored position <code>j</code> is decreased inside for-definition (cleaner loop body; faster than calculating it using deepness <code>i</code> inside loop)</li>\n<li>result &amp; ternary expression explained by variable</li>\n<li>result string building is done outside loop, once only (better performance)</li>\n</ul>\n\n<h3>More expressive: replace loop <code>for</code> by <code>while</code></h3>\n\n<p>Since above for-loop's body only responsible to <em>check and exit</em> this votes for replace it by while. Body then would express its purpose: increase mirroring position thus final lenght of <em>mirroredPart</em>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static String findMirroredPart(String s) {\n // optionally: check for null or empty respectively blank text\n\n final int half = s.length / 2;\n int posFromBegin = 0;\n int posFromEnd = s.length() - 1;\n\n while (posFromBegin &lt; half &amp;&amp; s.charAt(posFromBegin) == s.charAt(posFromEnd)) {\n posFromBegin++;\n posFromEnd--;\n }\n\n String mirroredPartOrPalindrome = posFromBegin &lt; half ? s.substring(0, posFromBegin) : s;\n return mirroredPartOrPalindrome;\n}\n</code></pre>\n\n<p>Note: Introduced <strong>more expressive</strong> index names.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T13:01:55.197", "Id": "240624", "ParentId": "240608", "Score": "5" } }, { "body": "<p>I don't program much in Java, but suspect it is suboptimal to be building the string in the loop one character at a time.</p>\n\n<p>Also, calculating a \"fresh\" tail end position each time from base units may take cycles, rather than decrementing a reverse counter. You then end up with an empty else{}, which should also help loop optimisation.</p>\n\n<p>So something like, where j (as a variable that survives loop destruction) is overloaded to be the \"tail test\" position in the loop, and the number of matched characters as the loop exits:\n[BTW, can't test this as no Java system to hand - just editing as I go. Particularly check the final arithmetic on \"j\".]</p>\n\n<pre><code> public String mirrorEnds(String string) {\n final int len = string.length();\n final int half = len / 2;\n\n int j = len - 1;\n for (int i = 0; i &lt; half; i++) {\n if (string.charAt(i) != string.charAt(j--)) {\n j = len - j - 1; \n break; \n }\n }\n return j == half ? string : string.substring(0, j);\n }\n\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public String mirrorEnds(String string) {\n int len = string.length();\n final int half = len / 2;\n\n int i = 0; \n while (i &lt; half) {\n if (string.charAt(i) != string.charAt(--len)) {\n break; \n }\n i++;\n }\n return i == half ? string : string.substring(0, i);\n }\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T20:41:52.513", "Id": "240650", "ParentId": "240608", "Score": "6" } } ]
{ "AcceptedAnswerId": "240650", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T09:07:01.850", "Id": "240608", "Score": "8", "Tags": [ "java", "strings" ], "Title": "Determine if a String has a mirroring head and tail" }
240608
<p>For a web application, I have to transform a LaTeX document on the fly into an HTML string, that is delivered to connected clients via websockets. Thus I installed a filewatcher that waits for file updates and whenever the file is modified, I run <code>transformToHTML</code> to parse the LaTeX code with regular expressions and build an HTML document.</p> <pre><code>{-# LANGUAGE QuasiQuotes #-} import Text.Regex.PCRE.Heavy -- transforms a LaTeX document to an HTML document transformToHTML :: Text -&gt; Text transformToHTML latex = let raw = gsub [reM|\\(intertext|begin|end|textbf|textit|section|subsection|subsubsection|documentclass|usepackage|item)(?:{(.*?)})?(?:\[(.*?)\])*|] envs latex resolvedBreaks = gsub [re|(\\\\)(?![^\[]*\\\])|] ("&lt;br&gt;" :: Text) raw in gsub [reM|(\\begin{figure}(.*?)\\end{figure}|\\begin{tabular}(.*?)\\end{tabular})|] ("&lt;p&gt;Content not available in your country.&lt;/p&gt;" :: Text) resolvedBreaks where envs :: [Text] -&gt; Text envs ("begin":"enumerate":_) = "&lt;ol&gt;" envs ("end":"enumerate":_) = "&lt;/ol&gt;" envs ("begin":"itemize":_) = "&lt;ul&gt;" envs ("end":"itemize":_) = "&lt;/ul&gt;" envs ("begin":"definition":name:_) = lemmaLike "lemma" "Definition" (Just name) envs ("begin":"definition":_) = lemmaLike "lemma" "Definition" Nothing envs ("end":"definition":_) = "&lt;/div&gt;" envs ("begin":"lemma":name:_) = lemmaLike "lemma" "Lemma" (Just name) envs ("begin":"lemma":_) = lemmaLike "lemma" "Lemma" Nothing envs ("end":"lemma":_) = "&lt;/div&gt;" envs ("begin":"satz":name:_) = lemmaLike "lemma" "Theorem" (Just name) envs ("begin":"satz":_) = lemmaLike "lemma" "Theroem" Nothing envs ("end":"satz":_) = "&lt;/div&gt;" envs ("begin":"korrolar":name:_) = lemmaLike "lemma" "Corrolary" (Just name) envs ("begin":"korrolar":_) = lemmaLike "lemma" "Corrolary" Nothing envs ("end":"korrolar":_) = "&lt;/div&gt;" envs ("begin":"bem":name:_) = lemmaLike "bsp" "Annotation" (Just name) envs ("begin":"bem":_) = lemmaLike "bsp" "Annotation" Nothing envs ("end":"bem":_) = "&lt;/div&gt;" envs ("begin":"bsp":name:_) = lemmaLike "bsp" "Example" (Just name) envs ("begin":"bsp":_) = lemmaLike "bsp" "Example" Nothing envs ("end":"bsp":_) = "&lt;/div&gt;" envs ("begin":"proof":name:_) = "&lt;div class='proof'&gt;&lt;i&gt;Proof&lt;/i&gt; (" &lt;&gt; name &lt;&gt; ")." envs ("begin":"proof":_) = "&lt;div class='proof'&gt;&lt;i&gt;Proof&lt;/i&gt;." envs ("end":"proof":_) = "&lt;/div&gt;" envs ("begin":"align*":_) = "\\[\\begin{aligned}" envs ("end":"align*":_) = "\\end{aligned}\\]" envs ("begin":"document":_) = "" envs ("end":"document":_) = "" envs ("begin":tag:_) = "\\begin{" &lt;&gt; tag &lt;&gt; "}" envs ("end":tag:_) = "\\end{" &lt;&gt; tag &lt;&gt; "}" envs ("textbf":content:_) = surround "b" content envs ("textit":content:_) = surround "i" content envs ("section":content:_) = surround "h2" content envs ("subsection":content:_) = surround "h2" content envs ("subsubsection":content:_) = surround "h4" content envs ("intertext":content:_) = "\\\\ \\text{" &lt;&gt; content &lt;&gt; "} \\\\" envs ("item":_) = "&lt;li&gt;" envs _ = "" lemmaLike :: Text -&gt; Text -&gt; Maybe Text -&gt; Text lemmaLike cls name Nothing = "&lt;div class='" &lt;&gt; cls &lt;&gt; "'&gt;&lt;b&gt;" &lt;&gt; name &lt;&gt; "&lt;/b&gt;." lemmaLike cls name (Just title) = "&lt;div class='" &lt;&gt; cls &lt;&gt; "'&gt;&lt;b&gt;" &lt;&gt; name &lt;&gt; "&lt;/b&gt; (" &lt;&gt; title &lt;&gt; ")." surround :: Text -&gt; Text -&gt; Text surround surr content = "&lt;" &lt;&gt; surr &lt;&gt; "&gt;" &lt;&gt; content &lt;&gt; "&lt;/" &lt;&gt; surr &lt;&gt; "&gt;" </code></pre> <p>Is there a better way to efficiently parse a LaTeX document? One major issues here is, that I run through the document thrice and apply <code>gsub</code>.</p> <p>Also I think this is not really readable and it is hard to figure out, what is going on.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-03T23:24:13.773", "Id": "474292", "Score": "0", "body": "May be a silly question, but can't you simply use `pandoc`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-04T14:27:06.660", "Id": "490793", "Score": "0", "body": "Did you try [LaTeX2HTML](https://www.latex2html.org)? It seems to do the job you want." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T09:32:58.090", "Id": "240609", "Score": "1", "Tags": [ "haskell", "regex" ], "Title": "Convert LaTeX document to HTML" }
240609
<p>I'm primarily a C++ developer, but I find myself writing significant amounts of Python these days. One C++ feature I miss in Python are function-scope static variables (variables which are initialised once, but retain their value across calls to the function). So I wrote a decorator for adding static variables to a function, and I'd like some feedback on it.</p> <pre><code>from functools import wraps class Statics: class Current: class Value: def __init__(self, name): self.name = name def __init__(self, statics): self.__statics = statics def __getattr__(self, name): if hasattr(self.__statics, name): return self.Value(name) else: return None def __init__(self): self.current = self.Current(self) def __setattr__(self, name, value): if isinstance(value, self.Current.Value): assert value.name == name, \ f"static.current.{value.name} can only be use to assign to " \ f"static.{value.name}, not to static.{name}" else: super(Statics, self).__setattr__(name, value) def with_statics(f): """Add static variables to a function. A function decorated with @with_statics must accept a "static variables" or "statics" object as its very first argument; the recommended name for this parameter is 'static'. This "statics" object is used access the function's static variables. A static variable is initialised with a value the first time control flow reaches its initialisation, and retains its value after that, even across several calls to the function. To initialise a static variable, use the following syntax: `static.x = static.current.x or expression`. When executing this statement for the first time, `expression` will be evaluated and stored in `static.x`. On all subsequent executions of this statement (even on subsequent calls to the containing function), the statement does nothing and `expression` is guaranteed to *not* be evaluated. Here's an example of using statics to implement a call counter: &gt;&gt;&gt; @with_statics ... def counter(static): ... static.val = static.current.val or 0 ... val = static.val ... static.val += 1 ... return val &gt;&gt;&gt; (counter(), counter(), counter()) (0, 1, 2) The initialisation expression is guaranteed to only execute once: &gt;&gt;&gt; def get_string(): ... print("Getting string") ... return "" ... &gt;&gt;&gt; @with_statics ... def record(static, text): ... static.recorded = static.current.recorded or get_string() ... static.recorded += text ... return static.recorded ... &gt;&gt;&gt; record("Hello") Getting string 'Hello' &gt;&gt;&gt; record(", world!") 'Hello, world!' Notice the absence of "Getting string" after the second call. """ statics = Statics() @wraps(f) def wrapper(*args, **kwargs): return f(statics, *args, **kwargs) return wrapper </code></pre> <p>Relevant parts of its test file:</p> <pre><code>import doctest import unittest import statics from statics import * class TestWithStatics(unittest.TestCase): def test_simple(self): @with_statics def counter(static): static.x = static.current.x or 0 static.x += 1 return static.x self.assertSequenceEqual( (counter(), counter(), counter()), (1, 2, 3) ) def test_unique_init_calls(self): @with_statics def counter(static, init): static.x = static.current.x or init() static.x += 1 return static.x inits = [] def init(): inits.append(None) return 0 self.assertSequenceEqual( (counter(init), counter(init), counter(init)), (1, 2, 3) ) self.assertSequenceEqual(inits, [None]) def test_unique_init_loop(self): @with_statics def counter(static, init, count): for i in range(count): static.x = static.current.x or init() static.x += 1 return static.x inits = [] def init(): inits.append(None) return 0 self.assertEqual(counter(init, 3), 3) self.assertSequenceEqual(inits, [None]) @unittest.skipUnless(__debug__, "requires __debug__ run of Python") def test_name_mismatch_assertion(self): @with_statics def function(static): static.x = static.current.x or 0 static.y = static.current.x or 1 return static.y with self.assertRaises(AssertionError) as ex: function() msg = str(ex.exception) self.assertRegex(msg, r"static\.current\.x") self.assertRegex(msg, r"static\.x") self.assertRegex(msg, r"static\.y") def test_instance_method(self): class Subject: def __init__(self): self.val = 0 @with_statics def act(static, self): static.x = static.current.x or 0 self.val += static.x static.x += 1 return self.val s = Subject() self.assertSequenceEqual( (s.act(), s.act(), s.act()), (0, 1, 3) ) def test_class_method(self): class Subject: val = 0 @classmethod @with_statics def act(static, cls): static.x = static.current.x or 0 cls.val += static.x static.x += 1 return cls.val self.assertSequenceEqual( (Subject.act(), Subject.act(), Subject.act()), (0, 1, 3) ) def run(): if not doctest.testmod(statics)[0]: print("doctest: OK") unittest.main() if __name__ == "__main__": run() </code></pre> <p>I'm primarily looking for feedback in these areas:</p> <ul> <li>Is the implementation Pythonic? Being primarily a C++ developer, Python idioms don't come naturally to me; that's one thing I'm constantly trying to improve.</li> <li>Is the idea itself Pythonic (or at least neutral), or does it feel like something "true Python shouldn't have" for some reason?</li> <li>Am I reinventing a wheel and something like this already exists?</li> </ul> <p>I'll welcome any other feedback too, of course.</p>
[]
[ { "body": "<ul>\n<li><p>I really don't think <code>Value</code> is a help here.<br>\nWhilst I can see the allure of only assigning <code>x</code> to <code>static.x</code>.\nThis just looks like a smart, but not exactly good, work around to get default values.</p>\n\n<p>You can just have <code>with_statics</code> take keyword arguments as the defaults.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def with_statics(**defaults):\n statics = Statics(defaults) # Implementation left to imagination\n def inner(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n return f(statics, *args, **kwargs)\n return wrapper\n return inner\n</code></pre></li>\n<li><p>Defining <code>Value</code> inside of two other classes is not great.\nYou can just move it to the global scope and change the <code>isinstance</code> check to not need to use indexing.</p>\n\n<p>If you still want the class on the other classes then you can just assign it as a class attribute.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Current:\n Value = Value\n\n ...\n</code></pre></li>\n<li><p>I think I'm fairly well versed in the magical Python arts. However your code is just confusing.</p></li>\n<li><p>Your code looks like it's a hack when a hack isn't needed.</p>\n\n<p>To highlight this I will convert your doctests to not use your code.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def counter():\n counter.val += 1\n return counter.val\n\n\ncounter.val = 0\nprint(counter(), counter(), counter())\n\n\ndef get_string():\n print(\"Getting string\")\n return \"\"\n\n\ndef record(text):\n if record.recorded is None:\n record.recorded = get_string()\n record.recorded += text\n return record.recorded\n\n\nrecord.recorded = None\nprint(record(\"Hello\"))\nprint(record(\", world!\"))\n</code></pre>\n\n<p>Yes it works. However, honestly, why would you want this?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T17:47:52.873", "Id": "474836", "Score": "0", "body": "i agree with most of your sentiments, but your example of having `with_statics` take a defaults dictionary isn't by itself expressive enough to emulate OP's code. it's fine if the initialisation value were known at compile-time - but this isn't necessarily the case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T17:55:47.773", "Id": "474837", "Score": "0", "body": "@two_pc_turkey_breast_mince You can always _not_ provide a default, or set it to `SENTINEL` (`object()`). If you show me something it wouldn't be able to do, I'm sure I can show you it's able to do that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T17:58:53.367", "Id": "474839", "Score": "0", "body": "i'm sure you could - with more code. all i mean to say is that the suggestion taken alone is incomplete if the intent is to replicate all of OP's functionality." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T18:55:29.037", "Id": "474843", "Score": "0", "body": "@two_pc_turkey_breast_mince Not really, the OP's code is basically just a long winded `if ...: foo = bar`. They'd both be one line of code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T19:01:04.560", "Id": "474845", "Score": "0", "body": "with more code [than you expressed in your answer]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T19:02:17.933", "Id": "474848", "Score": "0", "body": "@two_pc_turkey_breast_mince Yeah, you can repeat your words. But just sounds like nonsense. Give me an example to prove me wrong." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T11:43:06.810", "Id": "240618", "ParentId": "240612", "Score": "1" } }, { "body": "<p>I think your implementation is broken. It states in the docstring </p>\n\n<blockquote>\n <p>The initialisation expression is guaranteed to only execute once</p>\n</blockquote>\n\n<p>but I think the initialisation expression could be run multiple times with multithreading (race condition). Initialisation of function static variables in late C++ employs synchronisation under-the-hood.</p>\n\n<p>Otherwise, I think the implementation is rather clever, but I wouldn't use it. I agree with most of <a href=\"https://codereview.stackexchange.com/a/240618/223689\">this</a> answer's criticisms, especially about nesting a class inside a class inside a class. That answer's final suggestion of using the function instance itself to store the static variables seems to miss the mark, though, in my opinion. One of the more useful properties of a function static variable is to minimise the scope of the variable. Ideally, it shouldn't be visible externally or depend on externally accessible state.</p>\n\n<p><em>Pythonic</em> in my experience just seems to mean \"constructs with which we're familiar\". I've toyed with replicating statics in Python, too, but I've never seen it used <em>anywhere</em> in the wild, including in the workplace. Implementing a generic language feature atop a language never seems to come off naturally, and the syntax for your statics is, in my opinion, clunky and incurs a fair runtime overhead - but that's <em>not</em> to say that I think it's possible to come up with something much better. I'd forgo this altogether.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T18:58:36.223", "Id": "241962", "ParentId": "240612", "Score": "-1" } }, { "body": "<p>In the few cases I've wanted C-style static variables, I've used a Class with a <code>__call__()</code> method:</p>\n\n<pre><code>class Foo:\n a = 1\n b = 2\n\n def __call__(self):\n print(self.a, self.b)\nfoo = Foo()\n\nfoo()\n</code></pre>\n\n<p>Or, you could use a function decorator</p>\n\n<pre><code>def staticvars(**vars):\n def f(func):\n for k,v in vars.items():\n setattr(func, k, v)\n return func\n return f\n\n@staticvars(a=1,b=2)\ndef foo():\n print(foo.a, foo.b)\n</code></pre>\n\n<p>Or, under the idea \"it's easier to get forgiveness than permission\":</p>\n\n<pre><code>def counter():\n try:\n counter.x += 1\n\n except AttributeError:\n counter.x = 1\n\n return counter.x\n\n\nprint(counter(), counter(), counter()) # prints: 1, 2, 3\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-08T21:06:23.830", "Id": "241970", "ParentId": "240612", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-16T10:07:42.760", "Id": "240612", "Score": "4", "Tags": [ "python", "python-3.x", "static" ], "Title": "Function decorator for static local variables" }
240612