body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I need to compare 2 objects to determine if they have strictly the same properties.</p>
<p>This is what I came up with so far:
<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>import isEmpty from 'lodash/isEmpty';
const shallowPropertiesMatch = (firstObject, secondObject) => {
if (isEmpty(firstObject) || isEmpty(secondObject)) return false;
const firstObjectKeys = Object.keys(firstObject);
const secondObjectKeys = Object.keys(secondObject);
if (firstObjectKeys.length !== secondObjectKeys.length) return false;
if (!firstObjectKeys.every(value => secondObjectKeys.includes(value))) return false;
return true;
};</code></pre>
</div>
</div>
</p>
<p>I was wondering if there is a more efficient, elegant or simpler way of doing this?</p>
| [] | [
{
"body": "<p>By this condition, the function returns <code>false</code> when both objects are empty:</p>\n\n<blockquote>\n<pre><code>if (isEmpty(firstObject) || isEmpty(secondObject)) return false;\n</code></pre>\n</blockquote>\n\n<p>I would expect <code>true</code> in this case, and rewrite the condition as:</p>\n\n<pre><code>if (isEmpty(firstObject) != isEmpty(secondObject)) return false;\n</code></pre>\n\n<p>That is, return <code>false</code> if one of them is empty while the other is not.</p>\n\n<p>In fact, this special treatment is not even necessary, because the rest of the function naturally handles the case of empty objects.</p>\n\n<hr>\n\n<blockquote>\n <p>I was wondering if there is a more efficient, elegant or simpler way of doing this?</p>\n</blockquote>\n\n<p>The current implementation is not efficient,\nbecause of this step:</p>\n\n<blockquote>\n<pre><code>if (!firstObjectKeys.every(value => secondObjectKeys.includes(value))) return false;\n</code></pre>\n</blockquote>\n\n<p>The problem is that <code>secondObjectKeys</code> is an array,\nand therefore <code>.includes</code> does a linear lookup.\nYou can improve the linear-time lookup to constant-time lookup by converting <code>secondObjectKeys</code> to a <em>set</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T18:41:26.783",
"Id": "215288",
"ParentId": "215263",
"Score": "1"
}
},
{
"body": "<p>How can you know if a function is efficient if you use 3rd party code. Even if you check the source, it is subject to change without notice so you can never know if your code is running the best it can. That is the price you pay for using 3rd party code.</p>\n\n<p>However I don't see the need to use <code>lodash/isEmpty</code> as you determine that when you get the object keys. If there are no keys the object is empty.</p>\n\n<p>Not delimiting a statement block eg <code>if (isEmpty(firstObject) || isEmpty(secondObject)) return false;</code> is a bad habit. Always delimit all blocks with <code>{}</code>.</p>\n\n<p>Your naming is way too verbose. Use the functions context to imply meaning. The function name implies (well sort of) you are handling objects.</p>\n\n<p>One solutions is as follows.</p>\n\n<pre><code>function compareObjKeys(A, B) {\n const keys = Object.keys(A);\n if (keys.length > 0) {\n const keysB = Object.keys(B);\n if (keysB.length === keys.length) {\n const keysA = new Set(keys);\n return keysB.every(k => keysA.has(k));\n }\n }\n return false;\n}\n</code></pre>\n\n<p>But I would not go as far and favor a smaller source size. The performance savings of the above are minor and only when one of the objects is empty which I would imagine would be rare</p>\n\n<pre><code>function compareObjKeys(A, B) {\n const kA = new Set(Object.keys(A)), kB = Object.keys(B);\n return kB.length > 0 && kA.size === kB.length && kB.every(k => kA.has(k));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T09:22:55.590",
"Id": "416604",
"Score": "0",
"body": "Please explain why being too verbose is a bad thing. `shallowPropertiesMatch` indicates the function returns a boolean, and ignores nested properties (it's located in `/utils/object.js`). With `compareObjKeys` I might want to double check what it does exactly before using it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T10:49:29.717",
"Id": "416613",
"Score": "0",
"body": "@ThunderDev Humans recognize words by shape first, https://www.sciencealert.com/word-jumble-meme-first-last-letters-cambridge-typoglycaemia Camel case long words force extra cognitive effort when scanning code. This make it less readable and harder to spot potential bugs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T13:57:43.157",
"Id": "416636",
"Score": "0",
"body": "The article states there is evidence only to *suggest* we recognize words by shape. Furthermore, it's camel casing in general that hinders shape recognition, not particularly camel casing with long words. Also, I would have thought it required an extra cognitive effort for our brain to translate abbreviations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:33:30.470",
"Id": "416646",
"Score": "0",
"body": "@ThunderDev I assume you were able to read the linked image. If you find `(!fristObjectKeys.every(value => secondObjectKeys.includes(value)))` easier to read than (in context) `kA.every(k => kB.includes(k))` you should keep with the style that best suits you. If you got to here without spotting the typo, maybe you should consider a shorter style?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:54:34.613",
"Id": "416648",
"Score": "0",
"body": "Haha, clever, did not spot the typo ^^ to me abbreviations are still harder to interpret though."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T19:37:12.713",
"Id": "215293",
"ParentId": "215263",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215293",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T13:41:41.240",
"Id": "215263",
"Score": "2",
"Tags": [
"javascript",
"functional-programming"
],
"Title": "Determine if 2 javascript objects have strictly the same properties"
} | 215263 |
<p>I am attempting to return all users and security groups that begin with the provided substring. The following does work but I suspect there may be a better way to write this and am interested in both improving the performance and the style of the <code>Search</code> function.</p>
<p><strong>ActiveDirectory.cs</strong></p>
<pre><code>public static class ActiveDirectory
{
public static IEnumerable<Recipient> Search(string search)
{
var recipients = new List<Recipient>();
using (var ctx = new PrincipalContext(ContextType.Domain))
{
search = $"{search}*";
var userPrincipals = new List<UserPrincipal>
{
new UserPrincipal(ctx) {DisplayName = search},
new UserPrincipal(ctx) {Name = search},
new UserPrincipal(ctx) {SamAccountName = search}
};
foreach (var principal in userPrincipals)
{
foreach (var usr in new PrincipalSearcher(principal).FindAll())
{
if (!(usr is UserPrincipal user) || recipients.Any(m => m.Name == (user.DisplayName ?? user.Name) && m.Type == RecipientType.Group)) continue;
recipients.Add(new Recipient()
{
Name = user.SamAccountName,
DisplayName = user.DisplayName ?? user.Name,
Type = RecipientType.User
});
}
}
var groupPrincipals = new List<GroupPrincipal>
{
new GroupPrincipal(ctx) {DisplayName = search},
new GroupPrincipal(ctx) {Name = search},
new GroupPrincipal(ctx) {SamAccountName = search}
};
foreach (var principal in groupPrincipals)
{
foreach (var grp in new PrincipalSearcher(principal).FindAll())
{
if (!(grp is GroupPrincipal group) || recipients.Any(m => m.Name == (group.DisplayName ?? group.Name) && m.Type == RecipientType.Group)) continue;
recipients.Add(new Recipient()
{
Name = group.SamAccountName,
DisplayName = group.DisplayName ?? group.Name,
Type = RecipientType.Group
});
}
}
}
return recipients;
}
}
</code></pre>
<p><strong>Recipient.cs</strong></p>
<pre><code>public class Recipient
{
public Guid? Id { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public RecipientType Type { get; set; }
public Guid? ChannelId { get; set; }
}
</code></pre>
<p><strong>RecipientType.cs</strong></p>
<pre><code>public enum RecipientType
{
User,
Group
}
</code></pre>
| [] | [
{
"body": "<p>I don't know better ways to query for principals, so below is some general comments.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (!(usr is UserPrincipal user) || recipients.Any(m => m.Name == (user.DisplayName ?? user.Name) && m.Type == RecipientType.Group)) continue;\n</code></pre>\n</blockquote>\n\n<p>I think <code>m.Type == RecipientType.Group</code> should be <code>m.Type == RecipientType.User</code></p>\n\n<hr>\n\n<p>When I run your function I get an <code>InvalidOpeartionException</code> for this filter:</p>\n\n<blockquote>\n <p><code>new GroupPrincipal(ctx) {DisplayName = search}</code></p>\n</blockquote>\n\n<hr>\n\n<p>You could consider to extend the function with an argument, that allows the client to specify the context type:</p>\n\n<pre><code>public static IEnumerable<Recipient> Search(string search, ContextType contextType)\n</code></pre>\n\n<hr>\n\n<p>The returned <code>Principals</code> from <code>new PrincipalSearcher(principal).FindAll()</code> is of the same type as the argument <code>Principal</code> so you can omit this check:</p>\n\n<blockquote>\n <p><code>if (!(grp is GroupPrincipal group)...</code></p>\n</blockquote>\n\n<hr>\n\n<hr>\n\n<p>Both <code>PrincipalSearcher</code> and <code>Principal</code> implements <code>IDisposable</code> so all those objects should call <code>Dispose()</code> or be wrapped in a <code>using()</code> statement. </p>\n\n<hr>\n\n<p>You do essentially the same in the two loops so you should only have one that can handle different types of data. Below I've tried to do that, where all disposable objects are disposed.</p>\n\n<pre><code>public static IEnumerable<Recipient> Search(string search, ContextType contextType)\n{\n search = $\"{search}*\";\n\n using (PrincipalContext context = new PrincipalContext(contextType))\n {\n var recipients = new List<Recipient>();\n\n var filterTypes = new[]\n {\n new {\n Filters = new Func<Principal>[]\n {\n () => new UserPrincipal(context) {DisplayName = search},\n () => new UserPrincipal(context) {Name = search},\n () => new UserPrincipal(context) {SamAccountName = search}\n },\n RepicientType = RecipientType.User },\n new {\n Filters = new Func<Principal>[]\n {\n //() => new GroupPrincipal(context) {DisplayName = search},\n () => new GroupPrincipal(context) {Name = search},\n () => new GroupPrincipal(context) {SamAccountName = search}\n },\n RepicientType = RecipientType.Group },\n };\n\n foreach (var principalFilter in filterTypes)\n {\n foreach (var filterFunc in principalFilter.Filters)\n {\n using (var filter = filterFunc())\n using (var searcher = new PrincipalSearcher(filter))\n {\n foreach (var foundPrincipal in searcher.FindAll())\n {\n using (foundPrincipal)\n {\n if (recipients.Any(m => m.Name == (foundPrincipal.DisplayName ?? foundPrincipal.Name) && m.Type == principalFilter.RepicientType))\n continue;\n\n recipients.Add(new Recipient()\n {\n Name = foundPrincipal.SamAccountName,\n DisplayName = foundPrincipal.DisplayName ?? foundPrincipal.Name,\n Type = principalFilter.RepicientType\n });\n }\n }\n }\n }\n }\n\n return recipients;\n }\n}\n</code></pre>\n\n<p>Here I use <code>new Func<Principal>[]</code> instead of just <code>new Principal[]</code> in order to signal, that the \"client\" (the loop) is responsible for cleaning up the created object.</p>\n\n<p>I'm not sure I like this:</p>\n\n<pre><code> foreach (Principal foundPrincipal in searcher.FindAll())\n {\n using (foundPrincipal)\n {\n ...\n</code></pre>\n\n<p>but it's doable.</p>\n\n<hr>\n\n<p>Just for the exercise: a version that goes all in on LINQ with the same considerations as above:</p>\n\n<pre><code> public static class ActiveDirectory\n {\n private static IEnumerable<TPrincipal> Search<TPrincipal>(\n this IEnumerable<Func<TPrincipal>> filters,\n IEqualityComparer<TPrincipal> equalityComparer,\n ContextType contextType) where TPrincipal : Principal\n {\n return filters\n .SelectMany(creator =>\n {\n using (TPrincipal principal = creator())\n using (var searcher = new PrincipalSearcher(principal))\n {\n return searcher.FindAll();\n }\n })\n .Cast<TPrincipal>()\n .Distinct(equalityComparer)\n .ToArray();\n }\n\n private static IEnumerable<Recipient> Convert<TPrincipal>(this IEnumerable<TPrincipal> principals, RecipientType recipientType, bool disposePrincipals = true) where TPrincipal : Principal\n {\n foreach (TPrincipal principal in principals)\n {\n Recipient recipient = new Recipient\n {\n Name = principal.SamAccountName,\n DisplayName = principal.DisplayName ?? principal.Name,\n Type = recipientType\n };\n\n if (disposePrincipals)\n principal.Dispose();\n\n yield return recipient;\n }\n }\n\n public static IEnumerable<Recipient> Search(string search, ContextType contextType)\n {\n search = $\"{search}*\";\n\n using (var context = new PrincipalContext(contextType))\n {\n var userFilters = new Func<UserPrincipal>[]\n {\n () => new UserPrincipal(context) {DisplayName = search},\n () => new UserPrincipal(context) {Name = search},\n () => new UserPrincipal(context) {SamAccountName = search}\n };\n\n var groupFilters = new Func<GroupPrincipal>[]\n {\n //() => new GroupPrincipal(context) {DisplayName = search},\n () => new GroupPrincipal(context) {Name = search},\n () => new GroupPrincipal(context) {SamAccountName = search}\n };\n\n var users = userFilters.Search(new PrincipalEqualityComparer<UserPrincipal>(), contextType);\n var groups = groupFilters.Search(new PrincipalEqualityComparer<GroupPrincipal>(), contextType);\n\n return users.Convert(RecipientType.User).Concat(groups.Convert(RecipientType.Group)).ToArray();\n }\n }\n }\n\n\n class PrincipalEqualityComparer<TPrincipal> : IEqualityComparer<TPrincipal> where TPrincipal : Principal\n {\n public bool Equals(TPrincipal x, TPrincipal y)\n {\n if (x != null && y == null || x == null && y != null) return false;\n return ReferenceEquals(x, y) || string.Equals(x.Name, y.Name) || string.Equals(x.DisplayName, y.DisplayName);\n }\n\n public int GetHashCode(TPrincipal obj)\n {\n return 0; // obj.GetHashCode();\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T18:10:51.383",
"Id": "215620",
"ParentId": "215264",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "215620",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T13:42:08.673",
"Id": "215264",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Search for all matching users and security groups using System.DirectoryServices.AccountManagement"
} | 215264 |
<p>I made a Minesweeper for school and it works already. The only problem I have is that I need to optimize one part of my code but I have no idea how. The code below is for the whole program. The second form is just a page for explaining to the user how to play. The part I need to optimize is the part where I basically repeat the same thing 4 times but change 1 number every 4 times. But if you find another part that could have been done better, please do let me know. That part of the code looks like this: </p>
<pre><code>foreach (Control item in groupBox1.Controls)
{
if (
item.Name == string.Format("button{0}", red1 - orange1) ||
item.Name == string.Format("button{0}", red1 + orange1) ||
item.Name == string.Format("button{0}", red1 - orange2) ||
item.Name == string.Format("button{0}", red1 + orange2) ||
item.Name == string.Format("button{0}", red2 - orange1) ||
item.Name == string.Format("button{0}", red2 + orange1) ||
item.Name == string.Format("button{0}", red2 - orange2) ||
item.Name == string.Format("button{0}", red2 + orange2) ||
item.Name == string.Format("button{0}", red3 - orange1) ||
item.Name == string.Format("button{0}", red3 + orange1) ||
item.Name == string.Format("button{0}", red3 - orange2) ||
item.Name == string.Format("button{0}", red3 + orange2) ||
item.Name == string.Format("button{0}", red4 - orange1) ||
item.Name == string.Format("button{0}", red4 + orange1) ||
item.Name == string.Format("button{0}", red4 - orange2) ||
item.Name == string.Format("button{0}", red4 + orange2))
{
item.ForeColor = Color.Orange;
}
}
</code></pre>
<p>This is the full code:</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;
namespace Minesweeper
{
public partial class MinesweeperForm : Form
{
private int ticks;
int currentHighscore;
//values to calculate which button should be orange
int orange1 = 1;
int orange2 = 5;
#region initializer
public MinesweeperForm()
{
InitializeComponent();
}
#endregion
//play button function
#region play button
private void btnPlay_Click(object sender, EventArgs e)
{
//start timer
GameTimer.Start();
//every button in playfield groupbox enabled
foreach (Control item in groupBox1.Controls)
{
item.Enabled = true;
}
//calls shuffle mines
ShuffleMines();
//disables play button and enables stop button
btnPlay.Enabled = false;
btnStop.Enabled = true;
}
#endregion
//shufflemines function
#region shuffleMines
private void ShuffleMines()
{
//makes list of all buttons in groupbox
List<Button> listButtons = new List<Button>
{
button1, button2, button3, button4, button5,
button6, button7, button8, button9, button10,
button11, button12, button13, button14, button15,
button16, button17, button18, button19, button20,
button21, button22, button23, button24, button25
};
//makes a new random
Random rnd = new Random();
//selects randoms button numbers from list
int red1 = rnd.Next(listButtons.Count);
int red2 = rnd.Next(listButtons.Count);
int red3 = rnd.Next(listButtons.Count);
int red4 = rnd.Next(listButtons.Count);
//makes the buttons name from the random button numbers
var redButton1 = string.Format("button{0}", red1);
var redButton2 = string.Format("button{0}", red2);
var redButton3 = string.Format("button{0}", red3);
var redButton4 = string.Format("button{0}", red4);
//set forecolor of the not selected buttons to green
foreach (Control item in groupBox1.Controls)
{
item.ForeColor = Color.Green;
}
foreach (Control item in groupBox1.Controls)
{
if (
item.Name == string.Format("button{0}", red1 - orange1) ||
item.Name == string.Format("button{0}", red1 + orange1) ||
item.Name == string.Format("button{0}", red1 - orange2) ||
item.Name == string.Format("button{0}", red1 + orange2) ||
item.Name == string.Format("button{0}", red2 - orange1) ||
item.Name == string.Format("button{0}", red2 + orange1) ||
item.Name == string.Format("button{0}", red2 - orange2) ||
item.Name == string.Format("button{0}", red2 + orange2) ||
item.Name == string.Format("button{0}", red3 - orange1) ||
item.Name == string.Format("button{0}", red3 + orange1) ||
item.Name == string.Format("button{0}", red3 - orange2) ||
item.Name == string.Format("button{0}", red3 + orange2) ||
item.Name == string.Format("button{0}", red4 - orange1) ||
item.Name == string.Format("button{0}", red4 + orange1) ||
item.Name == string.Format("button{0}", red4 - orange2) ||
item.Name == string.Format("button{0}", red4 + orange2))
{
item.ForeColor = Color.Orange;
}
}
//set forecolor of the selected buttons for red to right color
foreach (Control item in groupBox1.Controls)
{
if (item.Name == redButton1 || item.Name == redButton2 || item.Name == redButton3 || item.Name == redButton4)
{
item.ForeColor = Color.Red;
}
}
}
#endregion
//win function
#region win
private void Win()
{
//checks if all non-mine buttons are pressed
if(progressBarGame.Value == 21)
{
//checks for new highscore
currentHighscore = int.Parse(lblHighscore.Text);
if (ticks < currentHighscore)
{
lblHighscore.Text = ticks.ToString();
}
//displays messagebox saying you win
MessageBox.Show("You win!");
}
}
#endregion
//stop button function
#region stop button
private void btnStop_Click(object sender, EventArgs e)
{
//calls gameover function
gameOver();
}
#endregion
//gameover function
#region gameOver
private void gameOver()
{
//disables all playfield buttons and resets button color
foreach (Control item in groupBox1.Controls)
{
item.Enabled = false;
item.BackColor = Color.FromKnownColor(KnownColor.ControlLight);
}
//disables stop button and enables play button
btnStop.Enabled = false;
btnPlay.Enabled = true;
//resets progressbar
progressBarGame.Value = 0;
}
#endregion
//switch forms function
#region switch forms
//open howtoplay form and hides current form
private void btnHowToPlay_Click(object sender, EventArgs e)
{
HowToPlayForm frm2 = new HowToPlayForm();
frm2.Show();
this.Hide();
}
#endregion
//proper close function
#region proper close
//properly closes form after switching forms
private void MinesweeperForm_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
#endregion
//playfield button clicked
#region playfieldbutton pressed
private void PlayFieldButton_MouseDown(object sender, MouseEventArgs e)
{
//checks which button is pressed
Button button = sender as Button;
//if left mouse button pressed
if (e.Button == MouseButtons.Left)
{
//sets invisible color to visible
button.BackColor = button.ForeColor;
//if button is not a mine adds point to bar and checks win
if (button.BackColor == Color.Green || button.BackColor == Color.Orange)
{
progressBarGame.Value += 1;
Win();
}
//if button is mine calls function "gameOver"
else if (button.BackColor == Color.Red)
{
MessageBox.Show("Gameover!");
gameOver();
}
//disables the button that is presssed
button.Enabled = false;
}
//if right mouse button pressed set button color to black
if (e.Button == MouseButtons.Right)
{
button.BackColor = Color.Black;
}
}
#endregion
//timer function
#region timer
private void GameTimer_Tick(object sender, EventArgs e)
{
ticks++;
string regel1 = string.Format("Time: {0} sec", ticks);
lblTimer.Text = regel1;
}
#endregion
}
}
</code></pre>
<p>Designer code: </p>
<pre><code>namespace Minesweeper
{
partial class MinesweeperForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MinesweeperForm));
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.button8 = new System.Windows.Forms.Button();
this.button9 = new System.Windows.Forms.Button();
this.button10 = new System.Windows.Forms.Button();
this.button11 = new System.Windows.Forms.Button();
this.button12 = new System.Windows.Forms.Button();
this.button13 = new System.Windows.Forms.Button();
this.button14 = new System.Windows.Forms.Button();
this.button15 = new System.Windows.Forms.Button();
this.button16 = new System.Windows.Forms.Button();
this.button17 = new System.Windows.Forms.Button();
this.button18 = new System.Windows.Forms.Button();
this.button19 = new System.Windows.Forms.Button();
this.button20 = new System.Windows.Forms.Button();
this.button21 = new System.Windows.Forms.Button();
this.button22 = new System.Windows.Forms.Button();
this.button23 = new System.Windows.Forms.Button();
this.button24 = new System.Windows.Forms.Button();
this.button25 = new System.Windows.Forms.Button();
this.btnPlay = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnStop = new System.Windows.Forms.Button();
this.progressBarGame = new System.Windows.Forms.ProgressBar();
this.lblHighscoreText = new System.Windows.Forms.Label();
this.lblHighscore = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnHowToPlay = new System.Windows.Forms.Button();
this.lblTimer = new System.Windows.Forms.Label();
this.GameTimer = new System.Windows.Forms.Timer(this.components);
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Enabled = false;
this.button1.Location = new System.Drawing.Point(17, 34);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(50, 50);
this.button1.TabIndex = 0;
this.button1.Tag = "speelveld";
this.button1.UseVisualStyleBackColor = true;
this.button1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button2
//
this.button2.Enabled = false;
this.button2.Location = new System.Drawing.Point(73, 34);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(50, 50);
this.button2.TabIndex = 1;
this.button2.Tag = "speelveld";
this.button2.UseVisualStyleBackColor = true;
this.button2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button3
//
this.button3.Enabled = false;
this.button3.Location = new System.Drawing.Point(129, 34);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(50, 50);
this.button3.TabIndex = 2;
this.button3.Tag = "speelveld";
this.button3.UseVisualStyleBackColor = true;
this.button3.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button4
//
this.button4.Enabled = false;
this.button4.Location = new System.Drawing.Point(185, 34);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(50, 50);
this.button4.TabIndex = 3;
this.button4.Tag = "speelveld";
this.button4.UseVisualStyleBackColor = true;
this.button4.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button5
//
this.button5.Enabled = false;
this.button5.Location = new System.Drawing.Point(241, 34);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(50, 50);
this.button5.TabIndex = 4;
this.button5.Tag = "speelveld";
this.button5.UseVisualStyleBackColor = true;
this.button5.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button6
//
this.button6.Enabled = false;
this.button6.Location = new System.Drawing.Point(17, 90);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(50, 50);
this.button6.TabIndex = 5;
this.button6.Tag = "speelveld";
this.button6.UseVisualStyleBackColor = true;
this.button6.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button7
//
this.button7.Enabled = false;
this.button7.Location = new System.Drawing.Point(73, 90);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(50, 50);
this.button7.TabIndex = 6;
this.button7.Tag = "speelveld";
this.button7.UseVisualStyleBackColor = true;
this.button7.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button8
//
this.button8.Enabled = false;
this.button8.Location = new System.Drawing.Point(129, 90);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(50, 50);
this.button8.TabIndex = 7;
this.button8.Tag = "speelveld";
this.button8.UseVisualStyleBackColor = true;
this.button8.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button9
//
this.button9.Enabled = false;
this.button9.Location = new System.Drawing.Point(185, 90);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(50, 50);
this.button9.TabIndex = 8;
this.button9.Tag = "speelveld";
this.button9.UseVisualStyleBackColor = true;
this.button9.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button10
//
this.button10.Enabled = false;
this.button10.Location = new System.Drawing.Point(241, 90);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(50, 50);
this.button10.TabIndex = 9;
this.button10.Tag = "speelveld";
this.button10.UseVisualStyleBackColor = true;
this.button10.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button11
//
this.button11.Enabled = false;
this.button11.Location = new System.Drawing.Point(17, 146);
this.button11.Name = "button11";
this.button11.Size = new System.Drawing.Size(50, 50);
this.button11.TabIndex = 10;
this.button11.Tag = "speelveld";
this.button11.UseVisualStyleBackColor = true;
this.button11.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button12
//
this.button12.Enabled = false;
this.button12.Location = new System.Drawing.Point(73, 146);
this.button12.Name = "button12";
this.button12.Size = new System.Drawing.Size(50, 50);
this.button12.TabIndex = 11;
this.button12.Tag = "speelveld";
this.button12.UseVisualStyleBackColor = true;
this.button12.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button13
//
this.button13.Enabled = false;
this.button13.Location = new System.Drawing.Point(129, 146);
this.button13.Name = "button13";
this.button13.Size = new System.Drawing.Size(50, 50);
this.button13.TabIndex = 12;
this.button13.Tag = "speelveld";
this.button13.UseVisualStyleBackColor = true;
this.button13.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button14
//
this.button14.Enabled = false;
this.button14.Location = new System.Drawing.Point(185, 146);
this.button14.Name = "button14";
this.button14.Size = new System.Drawing.Size(50, 50);
this.button14.TabIndex = 13;
this.button14.Tag = "speelveld";
this.button14.UseVisualStyleBackColor = true;
this.button14.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button15
//
this.button15.Enabled = false;
this.button15.Location = new System.Drawing.Point(241, 146);
this.button15.Name = "button15";
this.button15.Size = new System.Drawing.Size(50, 50);
this.button15.TabIndex = 14;
this.button15.Tag = "speelveld";
this.button15.UseVisualStyleBackColor = true;
this.button15.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button16
//
this.button16.Enabled = false;
this.button16.Location = new System.Drawing.Point(17, 202);
this.button16.Name = "button16";
this.button16.Size = new System.Drawing.Size(50, 50);
this.button16.TabIndex = 15;
this.button16.Tag = "speelveld";
this.button16.UseVisualStyleBackColor = true;
this.button16.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button17
//
this.button17.Enabled = false;
this.button17.Location = new System.Drawing.Point(73, 202);
this.button17.Name = "button17";
this.button17.Size = new System.Drawing.Size(50, 50);
this.button17.TabIndex = 16;
this.button17.Tag = "speelveld";
this.button17.UseVisualStyleBackColor = true;
this.button17.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button18
//
this.button18.Enabled = false;
this.button18.Location = new System.Drawing.Point(129, 202);
this.button18.Name = "button18";
this.button18.Size = new System.Drawing.Size(50, 50);
this.button18.TabIndex = 17;
this.button18.Tag = "speelveld";
this.button18.UseVisualStyleBackColor = true;
this.button18.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button19
//
this.button19.Enabled = false;
this.button19.Location = new System.Drawing.Point(185, 202);
this.button19.Name = "button19";
this.button19.Size = new System.Drawing.Size(50, 50);
this.button19.TabIndex = 18;
this.button19.Tag = "speelveld";
this.button19.UseVisualStyleBackColor = true;
this.button19.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button20
//
this.button20.Enabled = false;
this.button20.Location = new System.Drawing.Point(241, 202);
this.button20.Name = "button20";
this.button20.Size = new System.Drawing.Size(50, 50);
this.button20.TabIndex = 19;
this.button20.Tag = "speelveld";
this.button20.UseVisualStyleBackColor = true;
this.button20.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button21
//
this.button21.Enabled = false;
this.button21.Location = new System.Drawing.Point(17, 258);
this.button21.Name = "button21";
this.button21.Size = new System.Drawing.Size(50, 50);
this.button21.TabIndex = 20;
this.button21.Tag = "speelveld";
this.button21.UseVisualStyleBackColor = true;
this.button21.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button22
//
this.button22.Enabled = false;
this.button22.Location = new System.Drawing.Point(73, 258);
this.button22.Name = "button22";
this.button22.Size = new System.Drawing.Size(50, 50);
this.button22.TabIndex = 21;
this.button22.Tag = "speelveld";
this.button22.UseVisualStyleBackColor = true;
this.button22.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button23
//
this.button23.Enabled = false;
this.button23.Location = new System.Drawing.Point(129, 258);
this.button23.Name = "button23";
this.button23.Size = new System.Drawing.Size(50, 50);
this.button23.TabIndex = 22;
this.button23.Tag = "speelveld";
this.button23.UseVisualStyleBackColor = true;
this.button23.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button24
//
this.button24.Enabled = false;
this.button24.Location = new System.Drawing.Point(185, 258);
this.button24.Name = "button24";
this.button24.Size = new System.Drawing.Size(50, 50);
this.button24.TabIndex = 23;
this.button24.Tag = "speelveld";
this.button24.UseVisualStyleBackColor = true;
this.button24.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// button25
//
this.button25.Enabled = false;
this.button25.Location = new System.Drawing.Point(241, 258);
this.button25.Name = "button25";
this.button25.Size = new System.Drawing.Size(50, 50);
this.button25.TabIndex = 24;
this.button25.Tag = "speelveld";
this.button25.UseVisualStyleBackColor = true;
this.button25.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PlayFieldButton_MouseDown);
//
// btnPlay
//
this.btnPlay.Location = new System.Drawing.Point(11, 460);
this.btnPlay.Name = "btnPlay";
this.btnPlay.Size = new System.Drawing.Size(172, 50);
this.btnPlay.TabIndex = 0;
this.btnPlay.Text = "Play!";
this.btnPlay.UseVisualStyleBackColor = true;
this.btnPlay.Click += new System.EventHandler(this.btnPlay_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.button9);
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Controls.Add(this.button25);
this.groupBox1.Controls.Add(this.button2);
this.groupBox1.Controls.Add(this.button24);
this.groupBox1.Controls.Add(this.button3);
this.groupBox1.Controls.Add(this.button23);
this.groupBox1.Controls.Add(this.button4);
this.groupBox1.Controls.Add(this.button22);
this.groupBox1.Controls.Add(this.button5);
this.groupBox1.Controls.Add(this.button21);
this.groupBox1.Controls.Add(this.button6);
this.groupBox1.Controls.Add(this.button20);
this.groupBox1.Controls.Add(this.button7);
this.groupBox1.Controls.Add(this.button19);
this.groupBox1.Controls.Add(this.button8);
this.groupBox1.Controls.Add(this.button18);
this.groupBox1.Controls.Add(this.button10);
this.groupBox1.Controls.Add(this.button17);
this.groupBox1.Controls.Add(this.button11);
this.groupBox1.Controls.Add(this.button16);
this.groupBox1.Controls.Add(this.button12);
this.groupBox1.Controls.Add(this.button15);
this.groupBox1.Controls.Add(this.button13);
this.groupBox1.Controls.Add(this.button14);
this.groupBox1.Location = new System.Drawing.Point(41, 90);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(300, 318);
this.groupBox1.TabIndex = 25;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Speelveld";
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(189, 460);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(192, 50);
this.btnStop.TabIndex = 26;
this.btnStop.Text = "Stop";
this.btnStop.UseVisualStyleBackColor = true;
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// progressBarGame
//
this.progressBarGame.Location = new System.Drawing.Point(11, 522);
this.progressBarGame.Maximum = 21;
this.progressBarGame.Name = "progressBarGame";
this.progressBarGame.Size = new System.Drawing.Size(370, 23);
this.progressBarGame.Step = 1;
this.progressBarGame.TabIndex = 29;
//
// lblHighscoreText
//
this.lblHighscoreText.AutoSize = true;
this.lblHighscoreText.Location = new System.Drawing.Point(177, 425);
this.lblHighscoreText.Name = "lblHighscoreText";
this.lblHighscoreText.Size = new System.Drawing.Size(76, 17);
this.lblHighscoreText.TabIndex = 32;
this.lblHighscoreText.Text = "Highscore:";
//
// lblHighscore
//
this.lblHighscore.AutoSize = true;
this.lblHighscore.Location = new System.Drawing.Point(259, 425);
this.lblHighscore.Name = "lblHighscore";
this.lblHighscore.Size = new System.Drawing.Size(24, 17);
this.lblHighscore.TabIndex = 33;
this.lblHighscore.Text = "20";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(289, 425);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(34, 17);
this.label1.TabIndex = 34;
this.label1.Text = "sec.";
//
// btnHowToPlay
//
this.btnHowToPlay.Location = new System.Drawing.Point(11, 12);
this.btnHowToPlay.Name = "btnHowToPlay";
this.btnHowToPlay.Size = new System.Drawing.Size(370, 56);
this.btnHowToPlay.TabIndex = 36;
this.btnHowToPlay.Text = "How to play";
this.btnHowToPlay.UseVisualStyleBackColor = true;
this.btnHowToPlay.Click += new System.EventHandler(this.btnHowToPlay_Click);
//
// lblTimer
//
this.lblTimer.AutoSize = true;
this.lblTimer.Location = new System.Drawing.Point(13, 425);
this.lblTimer.Name = "lblTimer";
this.lblTimer.Size = new System.Drawing.Size(47, 17);
this.lblTimer.TabIndex = 37;
this.lblTimer.Text = "Time: ";
//
// GameTimer
//
this.GameTimer.Interval = 1000;
this.GameTimer.Tick += new System.EventHandler(this.GameTimer_Tick);
//
// MinesweeperForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.ClientSize = new System.Drawing.Size(396, 558);
this.Controls.Add(this.lblTimer);
this.Controls.Add(this.btnHowToPlay);
this.Controls.Add(this.label1);
this.Controls.Add(this.lblHighscore);
this.Controls.Add(this.lblHighscoreText);
this.Controls.Add(this.progressBarGame);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.btnPlay);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximumSize = new System.Drawing.Size(414, 605);
this.MinimumSize = new System.Drawing.Size(414, 530);
this.Name = "MinesweeperForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Tag = "";
this.Text = "Minesweeper";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MinesweeperForm_FormClosing);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.Button button11;
private System.Windows.Forms.Button button12;
private System.Windows.Forms.Button button13;
private System.Windows.Forms.Button button14;
private System.Windows.Forms.Button button15;
private System.Windows.Forms.Button button16;
private System.Windows.Forms.Button button17;
private System.Windows.Forms.Button button18;
private System.Windows.Forms.Button button19;
private System.Windows.Forms.Button button20;
private System.Windows.Forms.Button button21;
private System.Windows.Forms.Button button22;
private System.Windows.Forms.Button button23;
private System.Windows.Forms.Button button24;
private System.Windows.Forms.Button button25;
private System.Windows.Forms.Button btnPlay;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.ProgressBar progressBarGame;
private System.Windows.Forms.Label lblHighscoreText;
private System.Windows.Forms.Label lblHighscore;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnHowToPlay;
private System.Windows.Forms.Label lblTimer;
private System.Windows.Forms.Timer GameTimer;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T15:25:11.520",
"Id": "416293",
"Score": "0",
"body": "@Henrik Hansen Do you need the full designer content?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T15:58:54.283",
"Id": "416301",
"Score": "0",
"body": "As a suggestion, feel free to check out (or implement) the c# [Minesweeper library](https://github.com/bradmarder/msengine) I built. All it requires is a UI and some minor client logic. It handles all the complicated internal logic, including chording, and has a simple API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:17:24.510",
"Id": "416307",
"Score": "0",
"body": "@Brad M Thanks for the suggestion. Unfortunately, my school wants us to create the program ourselves. If this wasn't the case I would definitely check it out."
}
] | [
{
"body": "<p>So what it looks like your doing is going through a list of <code>Controls</code> inside of <code>groupBox1</code> and trying to figure out what they are and if they are one of you random buttons. You're doing this by naming all the buttons the same but adding there number to the end and then searching them by going through each controller in the <code>groupBox1</code> and checking their name agents the ones you have generated.</p>\n\n<p>There is a way to speed this up a bunch by using a List instead of every time you need to find the correct item looping through <code>groupBox1</code> and checking ever name.\nYou have already created a list but you filled it with newly created buttons that you actual never used. I would suggest just looping through the <code>groupBox1</code> and adding all the Controls to the list.</p>\n\n<p>Here is a example. (Note if <code>groupBox1</code> has more than just buttons you might want to check its type to make sure it is a button and not something else)</p>\n\n<pre><code>//Creates and populates listButton with all button controls\nList<Control> listButtons = new List<Control>();\nforeach (Control item in groupBox1.Controls)\n listButtons.Add(item);\n</code></pre>\n\n<p>Now you have all the buttons in a list (hopefully in order (I don't know how you setup groupBox1)) and we can start doing the changes you wanted.</p>\n\n<p>Next we want to set all buttons to Green and then we can change the color of the once we want. You are already doing this with the <code>//set forecolor of the not selected buttons to green</code> But we are just going to change it to now work with <code>listButtons</code>. Also if you want to optimize this more just set the buttons colors to green when you create them in <code>groupBox1</code> Unfortunately, I cannot see were you created this group so I cannot help with that</p>\n\n<pre><code>foreach (Control item in listButtons)\n{\n item.ForeColor = Color.Green;\n}\n</code></pre>\n\n<p>Next we want to create a for loop for every time you want you had a random number.\nand then inside the for loop we want to create this new random number. Now we want to use that random number to access that button from the list and change its color to orange. And to change the red buttons Red.</p>\n\n<pre><code>Random rnd = new Random();\n\nfor (int i = 1; i <= 4; i ++)\n{\n int listLength = listButtons.Count - 1;\n int randomNumber = rnd.Next(listLength);\n\n int minOrange1 = randomNumber - orange1;\n int plusOrange1 = randomNumber + orange1;\n\n int minOrange2 = randomNumber - orange2;\n int plusOrange2 = randomNumber + orange2;\n\n //Sets the red random buttons red\n listButtons[randomNumber].ForeColor = Color.Red;\n //Sets all the orange random buttons orange\n if (listLength <= minOrange1 && minOrange1 >= 0)\n listButtons[minOrange1].ForeColor = Color.Orange;\n if (listLength <= plusOrange1 && plusOrange1 >= 0)\n listButtons[plusOrange1].ForeColor = Color.Orange;\n if (listLength <= minOrange2 && minOrange2 >= 0)\n listButtons[minOrange2].ForeColor = Color.Orange;\n if (listLength <= plusOrange2 && plusOrange2 >= 0)\n listButtons[plusOrange2].ForeColor = Color.Orange;\n}\n</code></pre>\n\n<p>Now if we put it all together the new <code>ShuffleMines()</code> should look something like this (Note you might have to make some tweaks to get it to work within your game. Let me know if you need help or if the code just won't build because of a error I made)</p>\n\n<p><strong>Make sure you added all the buttons in order in <code>groupBox1</code></strong> </p>\n\n<pre><code>public void ShuffleMines()\n{\n //Creates and populates listButton with all button controls\n List<Control> listButtons = new List<Control>();\n foreach (Control item in groupBox1.Controls)\n listButtons.Add(item);\n\n foreach (Control item in listButtons)\n item.ForeColor = Color.Green;\n\n Random rnd = new Random();\n\n //Loops for all 4 random sets of buttons\n for (int i = 1; i <= 4; i++)\n {\n int listLength = listButtons.Count - 1;\n int randomNumber = rnd.Next(listLength);\n\n int minOrange1 = randomNumber - orange1;\n int plusOrange1 = randomNumber + orange1;\n\n int minOrange2 = randomNumber - orange2;\n int plusOrange2 = randomNumber + orange2;\n\n\n\n //Sets the red random buttons red\n listButtons[randomNumber].ForeColor = Color.Red;\n //Sets all the orange random buttons orange\n if (listLength >= minOrange1 && minOrange1 >= 0)\n listButtons[minOrange1].ForeColor = Color.Orange;\n if (listLength >= plusOrange1 && plusOrange1 >= 0)\n listButtons[plusOrange1].ForeColor = Color.Orange;\n if (listLength >= minOrange2 && minOrange2 >= 0)\n listButtons[minOrange2].ForeColor = Color.Orange;\n if (listLength >= plusOrange2 && plusOrange2 >= 0)\n listButtons[plusOrange2].ForeColor = Color.Orange;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:02:09.457",
"Id": "416303",
"Score": "0",
"body": "@Stijn Hendriks Just wanted to say thanks for adding the designer code to your question. I wanted to ask you to but unfortunately, you cannot comment on other people questions when you have less then 50 rep. My answer was made without seeing it but it should all work. I dont have time now (IT took me like 35 minutes to type the answer out) to change anything from it. I hope it helps you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:12:12.193",
"Id": "416305",
"Score": "0",
"body": "I implemented your code into the program and it gave me a new sort error. It gave me this: \"System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.\nParameter name: index'\" And the few times that it did work, it doesn't put the orange color in the right place for some reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:20:34.947",
"Id": "416308",
"Score": "0",
"body": "@StijnHendriks Ah yes I forgot to check if the button was in the list. I have corrected the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:40:39.643",
"Id": "416314",
"Score": "0",
"body": "I changed the code to the new code and I still get the same error. I was also wondering where you have the following line: \"Random rnd = new Random();\" Are you sure this code works or am I doing something wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:46:04.803",
"Id": "416317",
"Score": "0",
"body": "@StijnHendriks Yes I also forgot to add back the creation of the random. I have added it the script. You should be able to figure out any other issues. Luckily C# has a rely good error system and the errors are pretty strait forward. Also if you are using VS or Rider or another modern IDE it will show you what line it failed at and then what the error is. Let me know if you need any help and what other errors you found and how to fix them. I wont be able to respond till the morning though if you need help because im heading off to bed. I hope you do well on your project!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T17:17:33.760",
"Id": "416325",
"Score": "0",
"body": "I run the new code and then press the play button in the program I still get the error: \"System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.\nParameter name: index'\" This error is located at the line: if (listLength <= plusOrange2)\n listButtons[plusOrange2].ForeColor = Color.Orange; If I run it a few times it does run sometimes when I press the play button, but then no button is orange."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T17:26:48.910",
"Id": "416328",
"Score": "0",
"body": "@stijn Ah looks like you are subtracting from random which can make it a negative. Add another check on those if statements that the value is a non-negative. As for nothing being orange, Are you getting red buttons? Looks like groupBox1 in you Designer class isnt adding the buttons from first-last 1-25 order. It is just adding them at random. I noted in my answer that they need to be in order. Do some simple troubleshooting, Its one of the best ways to understand how you CPU runs code and how the compiler works, which will give you a better understanding of how to write faster and better code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T21:32:03.910",
"Id": "416374",
"Score": "0",
"body": "I have tried every solution I could think of and i got it to work to the point where it doesn't crash but I still won't show any orange colors. Green and red work fine, it's just the orange that doesn't work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T09:32:12.940",
"Id": "416435",
"Score": "0",
"body": "@StijnHendriks Ah I see my problem. I was dumbly checking if `listLength` is grater then 0 and not the number we generated. I downloaded your code and made the change and it worked perfectly without issue. I have update my answer to show this. Sorry about that dumb mistake"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:03:38.263",
"Id": "416438",
"Score": "0",
"body": "I think it is now my fault that is doesn't work, because I am not sure how to make it so the buttons in groupbox1 are in the right order. Do you have any idea how to do that? Right now I just put the buttons in the groupbox in the design.cs. Is there a better way to do this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:08:16.563",
"Id": "416440",
"Score": "0",
"body": "@StijnHendriks Ya how i did it was I went to the Designer class and just changed how they were added to be in order. [Here is the past bin of the groupBox1] (https://pastebin.com/sB9Xu7Ji). If you have changed the form design sense you uploaded the design here I would recommend doing the change by hand and not copy-pasting. The only part that needs to be change from your original is the order the buttons were added."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:30:01.750",
"Id": "416448",
"Score": "0",
"body": "After changing it in the designer it seems to work. So I just wanna say thank you very much for not only helping me with my problems but also for explaining what was wrong and why you changed certain things the way you did. For this school project this program is perfect, because it doesn't use code we haven't covered during class. So thanks for making my code better by using things that are not top-level difficulty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:36:23.563",
"Id": "416450",
"Score": "0",
"body": "@StijnHendriks Your welcome and sense your new here im going to mention that if you think a answer is useful you should vote it up with the up error and then you can also hit ✅ for the best answer for this question which will put the answer at the top to make it easier for others who might have a similar question find the best answer."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T15:57:18.760",
"Id": "215273",
"ParentId": "215265",
"Score": "6"
}
},
{
"body": "<h3>Problems:</h3>\n\n<ul>\n<li><code>ShuffleMines</code> only works for exactly 4 mines. It also contains a fair amount of duplicate code. Changing the number of mines requires a decent amount of work.</li>\n<li>The random tile selection does not take duplicates into account. You may end up with less than 4 mines, but elsewhere you assume that there are exactly 21 empty tiles.</li>\n<li>Going through all buttons and comparing their name against what's essentially a list of names is not a very efficient approach.</li>\n<li>You're treating a 5x5 grid as a single list, and you're using an offset of 1 to find the buttons directly left and right of the current one. That does not work correctly for buttons on the left or right edge of the grid - you'll end up with an orange button on the opposite edge.</li>\n<li>The game-over logic does not stop the game timer.</li>\n</ul>\n\n<h3>Suggestions:</h3>\n\n<p>Why not treat these buttons as an actual grid? A <code>Button[][] buttonsGrid</code> field would let you access buttons by their coordinates: <code>buttonsGrid[x][y]</code>. That also makes it easier and more obvious to access a neighboring button: <code>buttonsGrid[x + 1][y]</code> gives you the button directly to the right. You'll need to guard against invalid coordinates, so write a few helper methods:</p>\n\n<pre><code>private bool IsValidCoordinate(int x, int y)\n{\n return x >= 0 && x < BoardWidth && y >= 0 && y < BoardHeight;\n}\n\nprivate void SetButtonColor(int x, int y, Color color)\n{\n if (!IsValidCoordinate(x, y))\n return;\n\n buttonsGrid[x][y].ForeColor = color;\n}\n</code></pre>\n\n<p>Now, instead of having a method that places exactly 4 mines, it's better to have a method that places 1 mine. If you want to add more mines, you would simply call that method multiple times:</p>\n\n<pre><code>private void AddMine(int x, int y)\n{\n SetButtonColor(x, y, Color.Red);\n\n SetButtonColor(x - 1, y, Color.Orange);\n SetButtonColor(x, y - 1, Color.Orange);\n SetButtonColor(x + 1, y, Color.Orange);\n SetButtonColor(x, y + 1, Color.Orange);\n}\n</code></pre>\n\n<p>However, the above method could accidentally overwrite existing mines. One way to solve that is to check that a button isn't red before overwriting its color, so a <code>GetButtonColor</code> method would be useful.</p>\n\n<hr>\n\n<p>One issue here is that it's still using UI elements to store actual game state. That not only ties the game heavily to a specific UI, it also results in code that's harder to understand. It's better to have a grid of <code>Tile</code> objects, where each <code>Tile</code> contains information such as whether it's a mine, how many mines are nearby, whether it's been uncovered by the player or marked with a flag, and so on. Something like <code>tile.HasMine</code> or <code>tile.IsFlagged</code> is much more self-explanatory than <code>tile.ForeColor == Color.Red</code> or <code>tile.ForeColor == Color.Black</code>.</p>\n\n<hr>\n\n<p>Other improvements would be to generate buttons based on the tile grid, which makes it easier to support different board sizes. It may also be a good idea to store tile coordinates in a buttons <code>Tag</code> property, so you can quickly look up the associated tile:</p>\n\n<pre><code>button.Tag = new Point(x, y);\n...\nif (button.Tag is Point position)\n{\n var tile = GetTile(position.X, position.Y);\n if (tile.IsMine)\n ...\n}\n</code></pre>\n\n<h3>Other notes:</h3>\n\n<ul>\n<li>Regions can be useful to group related things together, but that's often a sign that classes might be doing too many different thing. Surrounding every method with a region only clutters the code.</li>\n<li>Use comments to explain things that the code itself cannot tell you, such as why you decided to do something the way you did, or how or for what purpose a method is intended to be used, or certain gotcha's that a caller should be aware of. Repeating method names is not useful.</li>\n<li>I'd rename <code>Win</code> to <code>CheckWinCondition</code> - it more accurately describes what the method does.</li>\n<li><code>string.Format(\"button{0}\", id)</code> can be written more succinctly with an interpolated string: <code>$\"button{id}\"</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:51:55.853",
"Id": "416456",
"Score": "0",
"body": "First of all, thank you for addressing all the problems I have and for including some other notes that helped me out. And second, thank you for giving me some solutions. Unfortunately, the level of your solution goes above my head since I am still a beginner. I should have said that in the beginning, so sorry about that. If I had some more experience I would definitely use your solution, but because I am not and Tyler stayed closer to my current level of programming skill, I chose for his answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T12:09:59.817",
"Id": "416472",
"Score": "0",
"body": "@StijnHendriks: no problem. We all have to start somewhere."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T09:31:06.957",
"Id": "215333",
"ParentId": "215265",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "215273",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T13:49:51.573",
"Id": "215265",
"Score": "5",
"Tags": [
"c#",
"homework",
"winforms",
"minesweeper"
],
"Title": "Minesweeper game using Winforms"
} | 215265 |
<p>I want to write a very simple std::string like compile-time const char* string.</p>
<p>I need to work with strings in the compiletime, just like with strings, I implemented basic functions.</p>
<pre><code>class cstring final {
const char* str_;
std::size_t size_;
public:
constexpr cstring(const char* str, std::size_t size, std::size_t prefix = 0, std::size_t suffix = 0) noexcept
: str_{str + prefix},
size_{size - prefix - suffix} {}
template <std::size_t N>
constexpr cstring(const char (&str)[N]) noexcept : cstring{str, N - 1, 0, 0} {}
constexpr cstring() noexcept : cstring{nullptr, 0, 0, 0} {}
cstring(const std::string& str) noexcept : cstring{str.data(), str.size(), 0, 0} {}
constexpr cstring(const cstring&) = default;
cstring& operator=(const cstring&) = default;
constexpr std::size_t size() const noexcept { return size_; }
constexpr std::size_t length() const noexcept { return size_; }
constexpr std::size_t max_size() const noexcept {
return (std::numeric_limits<std::size_t>::max)();
}
constexpr bool empty() const noexcept { return size_ == 0; }
constexpr const char* begin() const noexcept { return str_; }
constexpr const char* end() const noexcept { return str_ + size_; }
constexpr const char* cbegin() const noexcept { return begin(); }
constexpr const char* cend() const noexcept { return end(); }
constexpr const char& operator[](std::size_t i) const { return str_[i]; }
constexpr const char& at(std::size_t i) const {
return (i < size_) ? str_[i]
: (throw std::out_of_range{"cstring::at"}, str_[0]);
}
constexpr const char& front() const { return str_[0]; }
constexpr const char& back() const { return str_[size_ - 1]; }
constexpr const char* data() const noexcept { return str_; }
constexpr cstring remove_prefix(std::size_t n) const {
return {str_ + n, size_ - n};
}
constexpr cstring add_prefix(std::size_t n) const {
return {str_ - n, size_ + n};
}
constexpr cstring remove_suffix(std::size_t n) const {
return {str_, size_ - n};
}
constexpr cstring add_suffix(std::size_t n) const {
return {str_, size_ + n};
}
constexpr cstring substr(std::size_t pos, std::size_t n) const {
return {str_ + pos, n};
}
constexpr int compare(cstring other) const {
return (size_ == other.size_) ? detail::StrCompare(str_, other.str_, size_)
: ((size_ > other.size_) ? 1 : -1);
}
friend constexpr bool operator==(cstring lhs, cstring rhs) {
return lhs.compare(rhs) == 0;
}
friend constexpr bool operator!=(cstring lhs, cstring rhs) {
return !(lhs == rhs);
}
std::string append(cstring s) const {
return std::string{str_, size_}.append(s.str_, s.size_);
}
friend std::string operator+(cstring lhs, cstring rhs) {
return std::string{lhs.str_, lhs.size_} + std::string{rhs.str_, rhs.size_};
}
friend std::ostream& operator<<(std::ostream& os, cstring str) {
os.write(str.str_, str.size_);
return os;
}
operator std::string() const { return std::string{str_, size_}; }
};
</code></pre>
<p>Note that I use C++11 in my project so I can't use <a href="https://en.cppreference.com/w/cpp/string/basic_string_view" rel="nofollow noreferrer"><code>std::string_view</code></a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T14:31:45.310",
"Id": "416283",
"Score": "2",
"body": "Welcome to Code Review. Could you add some additional information to your code, e.g. if you tried to reproduce the `string_view` interface, what you want reviewers to focus on, and so on? Also, you want to add missing `#include`s for `std::string` and `std::numeric_limits`. A usage example of your class would also be much appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:55:19.670",
"Id": "416457",
"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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T12:16:03.617",
"Id": "416476",
"Score": "0",
"body": "Ludisposed What should I do, roll back the changes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:06:38.433",
"Id": "416481",
"Score": "0",
"body": "I would suggest posting a follow-up, and mentioning it in this post, one of the options listed behind ludisposed's link. You can additionally accept an answer here."
}
] | [
{
"body": "<ol>\n<li><p>I would only ever mark polymorphic classes <code>final</code>. For them, there's a potential benefit to balance out the unnaturalness of not being able to inherit.</p></li>\n<li><p>You should really indent the contents of the class by one step. Though that could possibly be an artifact of only partially adapting to SE's markup.</p></li>\n<li><p>Consider verifying that <code>prefix</code> and <code>suffix</code> have sensible values, at least in debug-mode (<code>assert()</code>).</p></li>\n<li><p>The first ctor has sensible defaults for its last two parameters. Why not take advantage of that?</p></li>\n<li><p>Is there a reason you only accept <code>std::string</code>, instead of generally <code>std::basic_string<char, std::char_traits<char>, AnyAllocator></code>?</p></li>\n<li><p>You could use <code>!_size</code> instead of <code>_size == 0</code>. Well, de gustibus.</p></li>\n<li><p>Your comparison is curious, but at least consistent.</p></li>\n<li><p>I would suggest conforming to <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\">C++17 <code>std::string_view</code></a> as closely as possible so you can later remove your custom class, and to ease the burden for users.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:39:53.080",
"Id": "416313",
"Score": "0",
"body": "1. I will consider. The final is a habit from Java.\n\n2. Sorry for the indents, they disappeared during writing answer. Overlooked, correct when editing.\n\n3. I'll add a check.\n\n4. Do you mean to make the constructor like this? cstring() : cstring{nullptr, 0} {}\n\n5. Yes, i think std::basic_string<char, std::char_traits<char>, AnyAllocator> will be better.\n\n6. Ok, will be noted.\n\n7. Oh, i forgot add detail::StrCompare to src. Will be fix soon.\n\n8. I'll think about whether I can upgrade the project to C++17"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T17:12:11.923",
"Id": "416324",
"Score": "0",
"body": "re 4: Yes, that's it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:11:07.873",
"Id": "215275",
"ParentId": "215267",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215275",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T14:18:00.257",
"Id": "215267",
"Score": "6",
"Tags": [
"c++",
"c++11"
],
"Title": "std::string like compile-time const char* string"
} | 215267 |
<p>I have this user controller that follows the repository pattern. It works perfect, but is it easy to understand? Is this good quality work?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using DatingApp_API.Data;
using DatingApp_API.DataTransferObjects;
using DatingApp_API.Helpers;
using DatingApp_API.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace DatingApp_API.Controllers
{
[ServiceFilter(typeof(LogUserActivity))]
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IDatingRepository _repo;
private readonly IMapper _mapper;
public UsersController(IDatingRepository repo, IMapper mapper)
{
_mapper = mapper;
_repo = repo;
}
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
var userFromRepo = await _repo.GetUser(currentUserId);
userParams.UserId = currentUserId;
if(string.IsNullOrEmpty(userParams.Gender))
{
userParams.Gender = userFromRepo.Gender == "male" ? "female" : "male";
}
var users = await _repo.GetUsers(userParams);
var usersToReturn = _mapper.Map<IEnumerable<UserForListDTO>>(users);
Response.AddPagination(users.CurrentPage, users.PageSize, users.TotalCount, users.TotalPages);
return Ok(usersToReturn);
}
[HttpGet("{id}", Name = "GetUser")]
public async Task<IActionResult> GetUser(int id)
{
var user = await _repo.GetUser(id);
var userToReturn = _mapper.Map<UserForDetailedDTO>(user);
return Ok(userToReturn);
}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateUser(int id, UserForUpdateDTO userForUpdateDTO)
{
if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized();
var userFromRepo = await _repo.GetUser(id);
_mapper.Map(userForUpdateDTO, userFromRepo);
if(await _repo.SaveAll())
return NoContent();
throw new Exception($"Updating user {id} failed on save");
}
[HttpPost("{id}/like/{recipientId}")]
public async Task<IActionResult> LikeUser(int id, int recipientId)
{
if(id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
return Unauthorized();
var like = await _repo.GetLike(id, recipientId);
if(like != null)
return BadRequest("You already like this user");
if(await _repo.GetUser(recipientId) == null)
return NotFound();
like = new Like
{
LikerId = id,
LikeeId = recipientId
};
_repo.Add<Like>(like);
if(await _repo.SaveAll())
return Ok();
return BadRequest("Failed to like user");
}
}
}
</code></pre>
| [] | [
{
"body": "<h1>Errors</h1>\n\n<p>An assumption: you never ever want to return a 500 HTTP status code (<em>Internal server error</em>). It may leak information you do not want to expose and it's not informative enough. Do not throw any exception: return the correct HTTP status code and eventually supplement it with the an appropriate error message. For example if <code>SaveAll()</code> failed because a concurrent request you may return 409 (<em>Conflict</em>). This leads to two more points:</p>\n\n<ul>\n<li>In your code you should almost never catch <code>Exception</code> and never throw it. There are many, more informative, exceptions to use which will play well with your exception handling policy (do you have one, right?).</li>\n<li><code>SaveAll()</code> returning a boolean just to throw an exception is, TBH, sub-optimal. If it's an error condition then it should be an exception (and caller MUST handle it, if it can). A boolean return value can too easily be ignored (and you don't want this to happen if data has not been saved).</li>\n</ul>\n\n<p>You're not catching any exception, if anything happens with the repository then API calls will fail with an internal server error.</p>\n\n<h1>Reuse</h1>\n\n<p>You parse the current user ID in many functions, move it out to a separate function. Also do not use <code>Int32.Parse()</code> without specifying the culture you want to use (probably <code>CultureInfo.InvariantCulture</code>).</p>\n\n<h1>Security</h1>\n\n<p>Do not use <code>UserParams</code> both in your repository and in your controller. It <em>smells</em> because:</p>\n\n<ul>\n<li>You can't change them independently.</li>\n<li>You have unused values you can specify in the query.</li>\n<li>If you add a new field and you forget to handle it in a controller method you might end up with a vulnerability.</li>\n</ul>\n\n<p>ALWAYS validate and translate request parameters (and the easiest way is to have two separate objects). For example <code>userParams.Gender</code> is directly exposed to your repository as an unvalidated string.</p>\n\n<p><code>UpdateUser()</code> (and <code>LikeUser()</code>) does not actually need the user ID as parameter. Do not require useless and redundant data from the client (which must be validated) when you already have it server-side.</p>\n\n<h1>Gender</h1>\n\n<p>Do not compare strings using <code>==</code> unless you exactly know what it means. In this case an even simpler and faster ordinal comparison is enough however...</p>\n\n<p>Do not store the gender as a string. If your app is limited to binary genders (at birth) then you may use an <code>enum</code>, however...</p>\n\n<p><em>Gender</em> is much more <em>complex</em> than a simple binary identity:</p>\n\n<ul>\n<li>Gender at birth is not necessarily binary.</li>\n<li>Gender at birth may not be the current gender.</li>\n<li>The <em>assigned</em> gender at birth may not be what a person identifies with.</li>\n<li>Especially in a dating app it's also important the sexual orientation (which is obviously independent from gender).</li>\n</ul>\n\n<p>In short: do not use an hard-coded list and do not assume gender equals sexual orientation.</p>\n\n<h1>Performance</h1>\n\n<p>If your app will be successful then you definitely want to avoid to search the <code>likes</code> table (which will grow much faster than the <code>users</code> table) for an entry and to retrieve it only to return <em>Bad request</em>. Best case scenario is to have a simpler function to determine if the entry exists instead of reading, transmitting and mapping the entry itself. See also the next section...</p>\n\n<h1>Design</h1>\n\n<p>I'm generally against the indiscriminate use of the Repository pattern. It's an invaluable tool but the price you pay in complexity to use it (properly) must be justified. I do not see the <em>big picture</em> here but you should seriously consider if directly using your ORM is <em>enough</em>. From what I see you really need a domain model, much more than a repository.</p>\n\n<p>You have an instance field <code>_repo</code>, you do not show that code but I do not see any synchronization mechanism and I do not see how you dispose its resources when controller is re-created. Generally, in your controllers, you should avoid instance fields as much as possible.</p>\n\n<p>Your API should never ever work directly with the repository to perform any business logic. It should interact with an high-level model (or a Service layer on the top of the Data layer exposed by your ORM). For example I'd imagine the <em>Like</em> feature like this:</p>\n\n<pre><code>public async Task<IActionResult> LikeUser(int recipientId)\n{\n using (var service = _serviceFactory.Create())\n await service.AddLike(GetCurrentUserId(), recipientId);\n\n return Ok();\n}\n</code></pre>\n\n<p>Yes, controller methods should not contain much more than this. All the logic must be TESTABLE then it is much easier to have it elsewhere. Note that in this fictional example I used a factory to create the service object: you may get it directly from your DI framework in the controller ctor but do not create it here (...<code>new MyService()</code>) because you want to test the controller with a mocked service.</p>\n\n<p>Note that the <code>AddLike()</code> is probably implemented with a stored procedure, you really need performance here. Given that user should not be able to click <em>Like</em> for someone he already liked then when it happens it's definitely an error condition and as such it should trigger an exception. Code is probably more complex than this because of error handling but I think you now got the point:</p>\n\n<pre><code>try\n{\n ...\n}\ncatch (ItemNotFoundException e)\n{\n return NotFound(...);\n}\ncatch (ConcurrencyException e)\n{\n // TODO: try again?\n}\n</code></pre>\n\n<p>If you structure well your service layer then you can probably move all this boilerplate code into a function method and reuse it in all controller methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T13:36:48.693",
"Id": "416632",
"Score": "0",
"body": "*Given that user should not be able to click Like for someone he already liked then when it happens it's definitely an error condition and as such it should trigger an exception.* You should usually safely ignore if the user already done some action and return successful response. This is not an exception, it happens often under normal circumstances. User opened multiple tabs, windows, browsers, devices,... or he has spotty connection, gets on an elevator, drives throuh a tunnel. If you really need to make it known to the client you can return 201 the first time and 200 subsequently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T13:51:18.310",
"Id": "416634",
"Score": "0",
"body": "Maybe this more an UI problem than an API problem but I'd agree with you, that's the behavior user expects and the 201/200 pair is a nice solution to inform the client."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T17:50:09.843",
"Id": "215285",
"ParentId": "215276",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:36:51.063",
"Id": "215276",
"Score": "4",
"Tags": [
"c#",
"controller",
"repository",
"asp.net-core"
],
"Title": "User controller for a .net core WebAPI dating app"
} | 215276 |
<p>This is a simple "Rock, Paper, Scissors" game I made in Python 3. Feel free to critique me and give suggestions on how can I improve my newbie coding skills.</p>
<pre><code>import os
from random import randint
def ask_player():
while True:
print("Rock, paper or scissors?")
ans = input(">")
if ans in ('Rock', 'Paper', 'Scissors'):
return ans
def results_msg(x, y, result):
message = f"{x} beats {y}. You {result}!"
return message
def comp_play():
comp_choice = randint(0, 2)
if comp_choice == 0:
comp_choice = 'Rock'
elif comp_choice == 1:
comp_choice = 'Paper'
else:
comp_choice = 'Scissors'
return comp_choice
def results(wins, losses, draws):
player_choice = ask_player()
comp_choice = comp_play()
if player_choice == comp_choice:
print("Draw. Nobody wins or losses.")
draws += 1
elif player_choice == 'Rock':
if comp_choice == 'Paper':
print(results_msg(comp_choice, player_choice, 'lost'))
losses += 1
else:
print(results_msg(player_choice, comp_choice, 'won'))
wins += 1
elif player_choice == 'Paper':
if comp_choice == 'Rock':
print(results_msg(player_choice, comp_choice, 'won'))
wins += 1
else:
print(results_msg(comp_choice, player_choice, 'lost'))
losses += 1
else:
if comp_choice == 'Rock':
print(results_msg(comp_choice, player_choice, 'lost'))
losses += 1
else:
print(results_msg(player_choice, comp_choice, 'won'))
wins += 1
return wins, losses, draws
def play_again():
while True:
print("\nDo you want to play again?")
print("[1] Yes")
print("[2] No")
ans = input("> ")
if ans in '12':
return ans
def main():
wins = 0
losses = 0
draws = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print(f"Wins: {wins}\nLosses: {losses}\nDraws: {draws}")
wins, losses, draws = results(wins, losses, draws)
if play_again() == '2':
break
if __name__ == '__main__':
main()
</code></pre>
<p>The follow-up is "<em><a href="https://codereview.stackexchange.com/questions/215367/rock-paper-scissors-game-follow-up">"Rock, Paper, Scissors" game - follow-up</a></em>".</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T17:56:06.320",
"Id": "416334",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T18:11:33.223",
"Id": "416338",
"Score": "0",
"body": "@Mast I apologize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T06:40:04.430",
"Id": "416406",
"Score": "0",
"body": "Don't worry, many people don't know the specific rules of Code Review and luckily we got a system in place that catches most of the trouble. You're still quite welcome."
}
] | [
{
"body": "<p>Just a real fast suggestion before I go to bed.\nWhen doing the check for what type of action the player is doing set there input to lowercase so they dont have to get the case correct.</p>\n\n<p>Example</p>\n\n<pre><code>if player_choice.lower() == 'paper':\n</code></pre>\n\n<p>In this example the code will run the <code>paper</code> logic if the player inputted <code>Paper</code> or <code>paper</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T17:35:42.040",
"Id": "215283",
"ParentId": "215280",
"Score": "3"
}
},
{
"body": "<p>Welcome back! There are a lot of good things to say about your program, and a few not-so-good. First, the good:</p>\n\n<ol>\n<li><p>The code is clean, well laid-out, and generally written in a Pythonic style.</p></li>\n<li><p>You have used functions to break things down.</p></li>\n<li><p>You have structured your program as a module, which should make it easier to test.</p></li>\n</ol>\n\n<p>Here are some things that I think could be improved:</p>\n\n<ol>\n<li><p>Your function names need a little work. Consider this code:</p>\n\n<pre><code>player_choice = ask_player()\ncomp_choice = comp_play()\n</code></pre>\n\n<p>The object is to get two choices, one made by the player and the other made by the computer. Why are the two names so different? <code>ask_player</code> doesn't sound like getting a player's choice. It sounds like a generalized function that asks the player something and gets a response (i.e., <code>input()</code>). On the other hand, if <code>player</code> is spelled out why do you abbreviate the opponent in <code>comp_play</code>? </p>\n\n<p>Using <code>get</code> is not always a good thing. It's one of the times when a function or method name doesn't need a verb in it - because it is frequently implicit when you are doing <code>is_...</code> or <code>has_...</code> or <code>get_...</code> or <code>set_...</code>. I don't think you need to spell out <code>get_player_choice</code> and <code>get_computer_choice</code>, but certainly <code>player_choice</code> and <code>computer_choice</code> would be appropriate.</p></li>\n</ol>\n\n<p>This same logic applies to <code>results</code>. Instead of calling a function named <code>results</code>, why not call <code>play_once</code>? Or <code>one_game</code>? It's obvious from the code in <code>main</code> what is going on, but the function name doesn't really match the nature of the \"step\" being executed.</p>\n\n<ol start=\"2\">\n<li><p>Your code breakdown is uneven. Consider this code:</p>\n\n<pre><code>def main():\n wins = 0\n losses = 0\n draws = 0\n while True:\n os.system('cls' if os.name == 'nt' else 'clear')\n print(f\"Wins: {wins}\\nLosses: {losses}\\nDraws: {draws}\")\n wins, losses, draws = results(wins, losses, draws)\n if play_again() == '2':\n break\n</code></pre>\n\n<p>Let's break those lines down. The key point I want to make is to <strong>keep neighboring statements at a similar level of abstraction.</strong> </p>\n\n<p>First, you initialize your variables:</p>\n\n<pre><code>wins = 0\nlosses = 0\ndraws = 0\n</code></pre>\n\n<p>Because you are not using a class, and are not using globals (which would be appropriate in this scenario, IMO), you are stuck with doing variable initialization here. I suggest that you make this consistent with how you update the variables after each game:</p>\n\n<pre><code>wins, losses, draws = starting_scores()\n</code></pre>\n\n<p>Now, <code>starting_scores</code> could just <code>return 0,0,0</code> or it could load from a saved-game file. But it makes the initialization sufficiently abstract, and it also spells out what you are doing.</p>\n\n<p>Next, you loop:</p>\n\n<pre><code>while True:\n ...\n if play_again() == '2':\n break\n</code></pre>\n\n<p>The <code>while True ... break</code> could be rewritten to use a boolean variable. That's not super-critical, since the value of that variable is determined at only a single location. I consider the break to be equivalent in this case. </p>\n\n<p><em>However,</em> the comparison <code>== '2'</code> is not acceptable! Why? Because that's a detail, and your function name <code>play_again</code> <em>should take care of that detail for you!</em> Don't ask a question and then interpret the answer. Make your question-asking code handle the interpretation for you. Obviously <code>play_again</code> is short for \"do you want to play again?\" and <code>'2'</code> is not a valid answer. <code>True</code> or <code>False</code> are valid answers, so the code should look like:</p>\n\n<pre><code>while True:\n ...\n if not play_again():\n break\n</code></pre>\n\n<p>Finally, the inside of your loop has the same problem:</p>\n\n<pre><code>os.system('cls' if os.name == 'nt' else 'clear')\nprint(f\"Wins: {wins}\\nLosses: {losses}\\nDraws: {draws}\")\nwins, losses, draws = results(wins, losses, draws)\n</code></pre>\n\n<p>What are you doing here? Well, you are clearing the screen, showing a summary of the games played, and playing one more round of the game. So say that!</p>\n\n<pre><code>clear_screen()\nshow_statistics(wins, losses, draws)\nwins, losses, draws = play_one_round(wins, losses, draws)\n</code></pre></li>\n<li><p>Use appropriate data structures.</p>\n\n<p>Your <code>main</code> code passes three variables to your play-game code. That code then returns three data items in a tuple, which you unpack into three variables. </p>\n\n<p>In fact, you never use one of those variables without also having the others at hand. This should tell you that you are dealing with one aggregate data item, instead of three independent pieces of data. If that's true, just treat the scores as a single item:</p>\n\n<pre><code>def main():\n scores = starting_scores()\n\n while True:\n clear_screen()\n show_statistics(scores)\n scores = rock_paper_scissors(scores)\n\n if not play_again():\n break\n</code></pre>\n\n<p>Similarly, you can treat the scores as an aggregate until you have to update them:</p>\n\n<pre><code># NB: was `results(wins, losses, draws):`\ndef rock_paper_scissors(scores):\n player = player_choice()\n computer = computer_choice()\n outcome = game_outcome(player, computer)\n show_results(outcome, player, computer)\n new_scores = update_scores(scores, outcome)\n return new_scores\n</code></pre>\n\n<p>At this point, the \"play one game\" has also become a collection of abstract statements. But notice that I'm treating <code>scores</code> as an opaque blob that I don't need to deal with: I just pass it along to the lower levels, with another data item describing the update to make.</p></li>\n<li><p>Be consistent!</p>\n\n<p>I notice that when asking the player to choose rock, paper, or scissors, you allow them to type in an answer. But given a Yes/No question, you require a selection of either <code>1</code> or <code>2</code>. That's consistently surprising. When I ran your code, I wanted to keep typing my answers. (I kept hitting 'y' to play again.) </p>\n\n<p>I suggest you either present the Rock/Paper/Scissors options as a menu, or present the Yes/No options as a string input and look for 'y' or 'n'. Making the interface that much more consistent will be an improvement.</p></li>\n<li><p>Use data, or code. Not both.</p>\n\n<p>This one is a little subtle, but take a look:</p>\n\n<pre><code>if comp_choice == 'Paper':\n print(results_msg(comp_choice, player_choice, 'lost'))\n losses += 1\nelse:\n print(results_msg(player_choice, comp_choice, 'won'))\n wins += 1\n</code></pre>\n\n<p>What's significant here is that you have an <code>if/then</code> statement that decides whether you won or lost. And then you pass that into your <code>results_msg</code> function as a string parameter. The result of this is that you have a string parameter to be substituted that gives information you already knew: whether the player won or lost.</p>\n\n<p>Let's look at <code>results_msg</code>: </p>\n\n<pre><code>def results_msg(x, y, result):\n message = f\"{x} beats {y}. You {result}!\"\n return message\n</code></pre>\n\n<p>You have to consider that Python f-strings are code. And they're a pretty compact form of code, compared to the horror of <em>str.</em><code>format()</code>. So writing:</p>\n\n<pre><code>print(results_msg(player_choice, comp_choice, 'won'))\n</code></pre>\n\n<p>is not really an improvement on writing:</p>\n\n<pre><code>print(f\"{player} beats {computer}. You won!\")\n</code></pre>\n\n<p>It's not clearer. It's not shorter. It <em>does</em> avoid problems with changing the text of the message, although there isn't much text in the message to change.</p>\n\n<p>I don't think you need to hoist the f-string up into the calling function. I <em>do</em> think you should not pass 'won' or 'lost' as a parameter: you already decided you won or lost. Call a separate function instead. </p>\n\n<pre><code>if ...\n win_message(player_choice, comp_choice)\nelse:\n lose_message(player_choice, comp_choice)\n</code></pre>\n\n<p>Note that this will appear to conflict with the code structure I showed above- because in that code structure, I chose to treat the result as data, not code. I'm not saying you have to use data, or that you have to use code. I'm saying that you should pick one and stick with it. If you determine your outcome as code, go ahead and hard-code the outcome. If you determine your outcome as data, go ahead and treat it as data.</p>\n\n<p>And as a side note, strings with substitutions in them make it hard to do i18n. So there's nothing wrong with having an array of totally spelled out messages at the bottom. It also gives a bit more \"flavor\" if you customize the verbs:</p>\n\n<pre><code>\"Rock breaks scissors. You won!\",\n\"Scissors cuts paper. You won!\",\n\"Paper covers rock. You won!\",\n...\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T19:32:51.943",
"Id": "416348",
"Score": "0",
"body": "Hey! Thank you for your very detailed answer. I really appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T05:08:19.547",
"Id": "416399",
"Score": "0",
"body": "Hey again! I did almost everything you told me except that I can't understand how am I supposed to make game_outcome(), show_results() and update_scores() (they are called in rock_paper_scissors())."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T14:34:15.760",
"Id": "416497",
"Score": "0",
"body": "As I wrote it, `game_outcome(a,b)` would compare two choices, and return a result that indicated the outcome of the game. Could be a number, could be a string, could be anything that works. Similarly, `show_results()` would take the outcome and the two choices and generate some kind of results display for the user. Printing a message would be appropriate. Finally, `update_scores()` should take the old scores object and return a new scores object with updated information."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T19:22:18.440",
"Id": "215292",
"ParentId": "215280",
"Score": "6"
}
},
{
"body": "<p>In <code>comp_play</code>, you should return immediately instead of setting a variable to return at the end (although this is slightly controversial). However, you should replace your <code>random.randint</code>/<code>if</code>/<code>elif</code>/<code>else</code> with <code>random.choice</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def comp_play():\n return choice(('Rock', 'Paper', 'Scissors'))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:01:35.307",
"Id": "416480",
"Score": "0",
"body": "Hey! Thank you, that helped me get rid of some lines."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T11:06:34.470",
"Id": "215340",
"ParentId": "215280",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215292",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T16:50:49.740",
"Id": "215280",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"rock-paper-scissors"
],
"Title": "\"Rock, Paper, Scissors\" game"
} | 215280 |
<h3>Problem</h3>
<p>Method <code>getQuoteHTML</code> generates an HTML <code>string</code> using an array returned from <code>getQuoteParams</code> method. They are methods of a large class, <code>UpdateStocks</code>.</p>
<p>Would you be so kind and help me to replace them with faster, easier or more efficient methods, if possible?</p>
<h3>getQuoteHTML:</h3>
<pre><code> /**
*
* @return a large HTML string of current quote section
*/
public static function getQuoteHTML($a){
$i=UpdateStocks::getQuoteParams();
$bt='<a href="#" class="s18 ro tx-1 b119 r100 t-21 p-2 br-5 mv-3" onclick="J.s({d:this});return false;" title="'.$a["symbol"].' latest quote"> Quote: '.date('l, d F Y \⏱ H:i T',microtime(true)).'</a>';
$hs='';
foreach($i as $k=>$p){
$h='';
if(isset($p["id"])&&!empty($a[$p["ky"]])){
if(preg_match('/(^s-*)/i',$p["id"])==1){
$r=rand(20,99);
$h=$h.'<p id="'.$p["id"].'">';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.$p["lb"].'</b>: ';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.$a[$p["ky"]].'</b>';
$h=$h.'</p>';
$hs=$hs.$h;
}elseif(preg_match('/(^d-*)/i',$p["id"])==1){
$r=rand(20,99);
$h=$h.'<p id="'.$p["id"].'">';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.$p["lb"].'</b>: ';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.money_format('%=9.4n',(double)$a[$p["ky"]]).'</b>';
$h=$h.'</p>';
$hs=$hs.$h;
}elseif(preg_match('/(^v-*)/i',$p["id"])==1){
$r=rand(20,99);
$h=$h.'<p id="'.$p["id"].'">';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.$p["lb"].'</b>: ';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.money_format('%=*!#4.0n',(double)$a[$p["ky"]]).'</b>';
$h=$h.'</p>';
$hs=$hs.$h;
}elseif(preg_match('/(^t-*)/i',$p["id"])==1){
$r=rand(20,99);
$h=$h.'<p id="'.$p["id"].'">';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.$p["lb"].'</b>: ';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.date('l, d F Y \⏱ H:i T \(P \U\T\C\)',(double)$a[$p["ky"]]/1000).'</b>';
$h=$h.'</p>';
$hs=$hs.$h;
}elseif(preg_match('/(^p-*)/i',$p["id"])==1){
$r=rand(20,99);
$h=$h.'<p id="'.$p["id"].'">';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.$p["lb"].'</b>: ';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.money_format('%=*!#4.4n',(double)$a[$p["ky"]]).'%</b>';
$h=$h.'</p>';
$hs=$hs.$h;
}else{
$r=rand(20,99);
$h=$h.'<p id="'.$p["id"].'">';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.$p["lb"].'</b>: ';
$h=$h.'<b class="di-1 t-21 m-1 br-3 p-2 b119 r1'.$r.'">'.$a[$p["ky"]].'%</b>';
$h=$h.'</p>';
$hs=$hs.$h;
}
} // isset
$h='';
}
return '<div class="ro">'.$bt.'<div class="di-0"><div class="p-3">'.$hs.'</div></div></div>';
}
</code></pre>
<h3>getQuoteParams:</h3>
<p>Except for <code>ky</code>, <code>$params</code> array can be changed and additional key/value can be added into: </p>
<pre><code> /**
*
* @return an array of parameters for stock quote from version 1 API at iextrading
*/
public static function getQuoteParams(){
$params=array(
array(
"id"=>"s-sy",
"ky"=>"symbol",
"lb"=>"Symbol",
),
array(
"id"=>"s-cn",
"ky"=>"companyName",
"lb"=>"Company",
),
array(
"id"=>"s-mk",
"ky"=>"primaryExchange",
"lb"=>"Primary Exchange Market",
),
array(
"id"=>"s-st",
"ky"=>"sector",
"lb"=>"Market Sector",
),
array(
"id"=>"d-op",
"ky"=>"open",
"lb"=>"Open Share Price [$]",
),
array(
"id"=>"t-ot",
"ky"=>"openTime",
"lb"=>"Open Time",
),
array(
"id"=>"d-cl",
"ky"=>"close",
"lb"=>"Close Share Price [$]",
),
array(
"id"=>"t-ct",
"ky"=>"closeTime",
"lb"=>"Close Time",
),
array(
"id"=>"d-hi",
"ky"=>"high",
"lb"=>"Current High Share Price [$]",
),
array(
"id"=>"d-lo",
"ky"=>"low",
"lb"=>"Current Low Share Price [$]",
),
array(
"id"=>"d-lp",
"ky"=>"latestPrice",
"lb"=>"Current Latest Share Price [$]",
),
array(
"id"=>"s-ls",
"ky"=>"latestSource",
"lb"=>"Data Source",
),
array(
"id"=>"t-lu",
"ky"=>"latestUpdate",
"lb"=>"Current Latest Update",
),
array(
"id"=>"v-lv",
"ky"=>"latestVolume",
"lb"=>"Current Latest Volume [V]",
),
array(
"id"=>"d-rp",
"ky"=>"iexRealtimePrice",
"lb"=>"Source Near-Real-Time Share Price [$]",
),
array(
"id"=>"v-rs",
"ky"=>"iexRealtimeSize",
"lb"=>"Source Near-Real-Time Size [V]",
),
array(
"id"=>"t-iu",
"ky"=>"iexLastUpdated",
"lb"=>"Source Latest Update",
),
array(
"id"=>"d-dp",
"ky"=>"delayedPrice",
"lb"=>"Delayed Share Price [$]",
),
array(
"id"=>"t-dt",
"ky"=>"delayedPriceTime",
"lb"=>"Delayed Share Price Time",
),
array(
"id"=>"d-ep",
"ky"=>"extendedPrice",
"lb"=>"Extended Share Price [$]",
),
array(
"id"=>"d-ec",
"ky"=>"extendedChange",
"lb"=>"Extended Dollar Change [$]",
),
array(
"id"=>"p-cp",
"ky"=>"extendedChangePercent",
"lb"=>"Extended Percent Change [%]",
),
array(
"id"=>"t-et",
"ky"=>"extendedPriceTime",
"lb"=>"Extended Share Price Time",
),
array(
"id"=>"d-pc",
"ky"=>"previousClose",
"lb"=>"Close Share Price in Previous Session [$]",
),
array(
"id"=>"d-ch",
"ky"=>"change",
"lb"=>"Share Price Change [$]",
),
array(
"id"=>"p-pr",
"ky"=>"changePercent",
"lb"=>"Share Price Change [%]",
),
array(
"id"=>"p-mp",
"ky"=>"iexMarketPercent",
"lb"=>"Source Market Share [%]",
),
array(
"id"=>"v-vl",
"ky"=>"iexVolume",
"lb"=>"Source Volume [V]",
),
array(
"id"=>"v-av",
"ky"=>"avgTotalVolume",
"lb"=>"Average Total Volume [V]",
),
array(
"id"=>"d-bp",
"ky"=>"iexBidPrice",
"lb"=>"Source Bid Price [$]",
),
array(
"id"=>"v-bs",
"ky"=>"iexBidSize",
"lb"=>"Source Bid Size [V]",
),
array(
"id"=>"d-ap",
"ky"=>"iexAskPrice",
"lb"=>"Source Ask Price [$]",
),
array(
"id"=>"v-as",
"ky"=>"iexAskSize",
"lb"=>"Source Ask Size [V]",
),
array(
"id"=>"d-cc",
"ky"=>"marketCap",
"lb"=>"Company Market Cap [$]",
),
array(
"id"=>"s-pe",
"ky"=>"peRatio",
"lb"=>"PE Ratio",
),
array(
"id"=>"d-wh",
"ky"=>"week52High",
"lb"=>"52-Week High [$]",
),
array(
"id"=>"d-wl",
"ky"=>"week52Low",
"lb"=>"52-Week Low [$]",
),
array(
"id"=>"p-yt",
"ky"=>"ytdChange",
"lb"=>"YTD Change",
),
);
return $params;
}
</code></pre>
<h3>HTML Output:</h3>
<pre><code><div class="ro">
<a href="#" class="s18 ro tx-1 b119 r100 t-21 p-2 br-5 mv-3" onclick="J.s({d:this});return false;" title="AAPL latest quote"> Quote: Tuesday, 12 March 2019 ⏱ 12:08 EDT</a>
<div class="di-0">
<div class="p-3">
<p id="s-sy"><b class="di-1 t-21 m-1 br-3 p-2 b119 r179">Symbol</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r179">AAPL</b></p>
<p id="s-cn"><b class="di-1 t-21 m-1 br-3 p-2 b119 r151">Company</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r151">Apple Inc.</b></p>
<p id="s-mk"><b class="di-1 t-21 m-1 br-3 p-2 b119 r157">Primary Exchange Market</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r157">Nasdaq Global Select</b></p>
<p id="s-st"><b class="di-1 t-21 m-1 br-3 p-2 b119 r136">Market Sector</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r136">Technology</b></p>
<p id="d-op"><b class="di-1 t-21 m-1 br-3 p-2 b119 r127">Open Share Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r127">$180.0000</b></p>
<p id="t-ot"><b class="di-1 t-21 m-1 br-3 p-2 b119 r136">Open Time</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r136">Tuesday, 12 March 2019 ⏱ 09:30 EDT (-04:00 UTC)</b></p>
<p id="d-cl"><b class="di-1 t-21 m-1 br-3 p-2 b119 r190">Close Share Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r190">$178.9000</b></p>
<p id="t-ct"><b class="di-1 t-21 m-1 br-3 p-2 b119 r163">Close Time</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r163">Monday, 11 March 2019 ⏱ 16:00 EDT (-04:00 UTC)</b></p>
<p id="d-hi"><b class="di-1 t-21 m-1 br-3 p-2 b119 r158">Current High Share Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r158">$182.6700</b></p>
<p id="d-lo"><b class="di-1 t-21 m-1 br-3 p-2 b119 r177">Current Low Share Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r177">$179.3700</b></p>
<p id="d-lp"><b class="di-1 t-21 m-1 br-3 p-2 b119 r143">Current Latest Share Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r143">$181.4100</b></p>
<p id="s-ls"><b class="di-1 t-21 m-1 br-3 p-2 b119 r185">Data Source</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r185">IEX real time price</b></p>
<p id="t-lu"><b class="di-1 t-21 m-1 br-3 p-2 b119 r148">Current Latest Update</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r148">Tuesday, 12 March 2019 ⏱ 12:06 EDT (-04:00 UTC)</b></p>
<p id="v-lv"><b class="di-1 t-21 m-1 br-3 p-2 b119 r195">Current Latest Volume [V]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r195"> 17,157,291</b></p>
<p id="d-rp"><b class="di-1 t-21 m-1 br-3 p-2 b119 r168">Source Near-Real-Time Share Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r168">$181.4100</b></p>
<p id="v-rs"><b class="di-1 t-21 m-1 br-3 p-2 b119 r150">Source Near-Real-Time Size [V]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r150"> **100</b></p>
<p id="t-iu"><b class="di-1 t-21 m-1 br-3 p-2 b119 r173">Source Latest Update</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r173">Tuesday, 12 March 2019 ⏱ 12:06 EDT (-04:00 UTC)</b></p>
<p id="d-dp"><b class="di-1 t-21 m-1 br-3 p-2 b119 r121">Delayed Share Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r121">$181.7210</b></p>
<p id="t-dt"><b class="di-1 t-21 m-1 br-3 p-2 b119 r171">Delayed Share Price Time</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r171">Tuesday, 12 March 2019 ⏱ 11:51 EDT (-04:00 UTC)</b></p>
<p id="d-ep"><b class="di-1 t-21 m-1 br-3 p-2 b119 r197">Extended Share Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r197">$181.4100</b></p>
<p id="t-et"><b class="di-1 t-21 m-1 br-3 p-2 b119 r137">Extended Share Price Time</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r137">Tuesday, 12 March 2019 ⏱ 12:06 EDT (-04:00 UTC)</b></p>
<p id="d-pc"><b class="di-1 t-21 m-1 br-3 p-2 b119 r144">Close Share Price in Previous Session [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r144">$178.9000</b></p>
<p id="d-ch"><b class="di-1 t-21 m-1 br-3 p-2 b119 r179">Share Price Change [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r179">$2.5100</b></p>
<p id="p-pr"><b class="di-1 t-21 m-1 br-3 p-2 b119 r155">Share Price Change [%]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r155"> ****0.0140%</b></p>
<p id="p-mp"><b class="di-1 t-21 m-1 br-3 p-2 b119 r154">Source Market Share [%]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r154"> ****0.0222%</b></p>
<p id="v-vl"><b class="di-1 t-21 m-1 br-3 p-2 b119 r168">Source Volume [V]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r168"> 381,235</b></p>
<p id="v-av"><b class="di-1 t-21 m-1 br-3 p-2 b119 r124">Average Total Volume [V]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r124"> 27,155,838</b></p>
<p id="d-bp"><b class="di-1 t-21 m-1 br-3 p-2 b119 r165">Source Bid Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r165">$180.0000</b></p>
<p id="v-bs"><b class="di-1 t-21 m-1 br-3 p-2 b119 r166">Source Bid Size [V]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r166"> **100</b></p>
<p id="d-ap"><b class="di-1 t-21 m-1 br-3 p-2 b119 r125">Source Ask Price [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r125">$185.0000</b></p>
<p id="v-as"><b class="di-1 t-21 m-1 br-3 p-2 b119 r175">Source Ask Size [V]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r175"> **500</b></p>
<p id="d-cc"><b class="di-1 t-21 m-1 br-3 p-2 b119 r133">Company Market Cap [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r133">$855,398,944,800.0000</b></p>
<p id="s-pe"><b class="di-1 t-21 m-1 br-3 p-2 b119 r166">PE Ratio</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r166">15.28</b></p>
<p id="d-wh"><b class="di-1 t-21 m-1 br-3 p-2 b119 r150">52-Week High [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r150">$233.4700</b></p>
<p id="d-wl"><b class="di-1 t-21 m-1 br-3 p-2 b119 r177">52-Week Low [$]</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r177">$142.0000</b></p>
<p id="p-yt"><b class="di-1 t-21 m-1 br-3 p-2 b119 r159">YTD Change</b>: <b class="di-1 t-21 m-1 br-3 p-2 b119 r159"> ****0.1517%</b></p>
</div>
</div>
</div>
</code></pre>
<h3>JavaScript Switch</h3>
<pre><code>/*switch display*/
s:function(z){
var x,a;
x=/(di-0)/i;
if(x.test(z.d.nextElementSibling.attributes.getNamedItem('class').nodeValue)){a=1}else{a=0}
switch (a){
case 1:
z.d.nextElementSibling.attributes.getNamedItem('class').nodeValue='di-2';
break;
case 0:
z.d.nextElementSibling.attributes.getNamedItem('class').nodeValue='di-0';
break;
}
}
</code></pre>
<h3>Switch Display CSS</h3>
<pre><code>.di-0{display:none!important}.di-1{display:inline-block}.di-2{display:block}.di-3{display:grid}
</code></pre>
<h3>Color Map CSS</h3>
<pre><code>.r100,
r100 a {
color: #FFFFFF
}
.b100,
.b100 a {
background-color: #FFFFFF
}
.r101,
r101 a {
color: #F8F8FF
}
.b101,
.b101 a {
background-color: #F8F8FF
}
.r102,
r102 a {
color: #F7F7F7
}
.b102,
.b102 a {
background-color: #F7F7F7
}
.r103,
r103 a {
color: #F0F0F0
}
.b103,
.b103 a {
background-color: #F0F0F0
}
.r104,
r104 a {
color: #F2F2F2
}
.b104,
.b104 a {
background-color: #F2F2F2
}
.r105,
r105 a {
color: #EDEDED
}
.b105,
.b105 a {
background-color: #EDEDED
}
.r106,
r106 a {
color: #EBEBEB
}
.b106,
.b106 a {
background-color: #EBEBEB
}
.r107,
r107 a {
color: #E5E5E5
}
.b107,
.b107 a {
background-color: #E5E5E5
}
.r108,
r108 a {
color: #E3E3E3
}
.b108,
.b108 a {
background-color: #E3E3E3
}
.r109,
r109 a {
color: #E0E0E0
}
.b109,
.b109 a {
background-color: #E0E0E0
}
.r110,
r110 a {
color: #858585
}
.b110,
.b110 a {
background-color: #858585
}
.r111,
r111 a {
color: #666666
}
.b111,
.b111 a {
background-color: #666666
}
.r112,
r112 a {
color: #545454
}
.b112,
.b112 a {
background-color: #545454
}
.r113,
r113 a {
color: #4D4D4D
}
.b113,
.b113 a {
background-color: #4D4D4D
}
.r114,
r114 a {
color: #474747
}
.b114,
.b114 a {
background-color: #474747
}
.r115,
r115 a {
color: #363636
}
.b115,
.b115 a {
background-color: #363636
}
.r116,
r116 a {
color: #333333
}
.b116,
.b116 a {
background-color: #333333
}
.r117,
r117 a {
color: #222222
}
.b117,
.b117 a {
background-color: #222222
}
.r118,
r118 a {
color: #1C1C1C
}
.b118,
.b118 a {
background-color: #1C1C1C
}
.r119,
r119 a {
color: #050505
}
.b119,
.b119 a {
background-color: #050505
}
.r120,
r120 a {
color: #EEEE00
}
.b120,
.b120 a {
background-color: #EEEE00
}
.r121,
r121 a {
color: #FFD700
}
.b121,
.b121 a {
background-color: #FFD700
}
.r122,
r122 a {
color: #EEC900
}
.b122,
.b122 a {
background-color: #EEC900
}
.r123,
r123 a {
color: #EAC80D
}
.b123,
.b123 a {
background-color: #EAC80D
}
.r124,
r124 a {
color: #FFC125
}
.b124,
.b124 a {
background-color: #FFC125
}
.r125,
r125 a {
color: #FFB90F
}
.b125,
.b125 a {
background-color: #FFB90F
}
.r126,
r126 a {
color: #EEAD0E
}
.b126,
.b126 a {
background-color: #EEAD0E
}
.r127,
r127 a {
color: #DAA520
}
.b127,
.b127 a {
background-color: #DAA520
}
.r128,
r128 a {
color: #BFA30C
}
.b128,
.b128 a {
background-color: #BFA30C
}
.r129,
r129 a {
color: #B78A00
}
.b129,
.b129 a {
background-color: #B78A00
}
.r130,
r130 a {
color: #FFA500
}
.b130,
.b130 a {
background-color: #FFA500
}
.r131,
r131 a {
color: #FF9912
}
.b131,
.b131 a {
background-color: #FF9912
}
.r132,
r132 a {
color: #ED9121
}
.b132,
.b132 a {
background-color: #ED9121
}
.r133,
r133 a {
color: #FF7F00
}
.b133,
.b133 a {
background-color: #FF7F00
}
.r134,
r134 a {
color: #FF8000
}
.b134,
.b134 a {
background-color: #FF8000
}
.r135,
r135 a {
color: #EE7600
}
.b135,
.b135 a {
background-color: #EE7600
}
.r136,
r136 a {
color: #EE6A50
}
.b136,
.b136 a {
background-color: #EE6A50
}
.r137,
r137 a {
color: #EE5C42
}
.b137,
.b137 a {
background-color: #EE5C42
}
.r138,
r138 a {
color: #FF6347
}
.b138,
.b138 a {
background-color: #FF6347
}
.r139,
r139 a {
color: #FF6103
}
.b139,
.b139 a {
background-color: #FF6103
}
.r140,
r140 a {
color: #32CD32
}
.b140,
.b140 a {
background-color: #32CD32
}
.r141,
r141 a {
color: #00C957
}
.b141,
.b141 a {
background-color: #00C957
}
.r142,
r142 a {
color: #43CD80
}
.b142,
.b142 a {
background-color: #43CD80
}
.r143,
r143 a {
color: #00C78C
}
.b143,
.b143 a {
background-color: #00C78C
}
.r144,
r144 a {
color: #1ABC9C
}
.b144,
.b144 a {
background-color: #1ABC9C
}
.r145,
r145 a {
color: #20B2AA
}
.b145,
.b145 a {
background-color: #20B2AA
}
.r146,
r146 a {
color: #03A89E
}
.b146,
.b146 a {
background-color: #03A89E
}
.r147,
r147 a {
color: #00C5CD
}
.b147,
.b147 a {
background-color: #00C5CD
}
.r148,
r148 a {
color: #00CED1
}
.b148,
.b148 a {
background-color: #00CED1
}
.r149,
r149 a {
color: #48D1CC
}
.b149,
.b149 a {
background-color: #48D1CC
}
.r150,
r150 a {
color: #63B8FF
}
.b150,
.b150 a {
background-color: #63B8FF
}
.r151,
r151 a {
color: #00B2EE
}
.b151,
.b151 a {
background-color: #00B2EE
}
.r152,
r152 a {
color: #1E90FF
}
.b152,
.b152 a {
background-color: #1E90FF
}
.r153,
r153 a {
color: #1C86EE
}
.b153,
.b153 a {
background-color: #1C86EE
}
.r154,
r154 a {
color: #1C86EE
}
.b154,
.b154 a {
background-color: #1C86EE
}
.r155,
r155 a {
color: #1874CD
}
.b155,
.b155 a {
background-color: #1874CD
}
.r156,
r156 a {
color: #436EEE
}
.b156,
.b156 a {
background-color: #436EEE
}
.r157,
r157 a {
color: #4169E1
}
.b157,
.b157 a {
background-color: #4169E1
}
.r158,
r158 a {
color: #3A5FCD
}
.b158,
.b158 a {
background-color: #3A5FCD
}
.r159,
r159 a {
color: #014B96
}
.b159,
.b159 a {
background-color: #014B96
}
.r160,
r160 a {
color: #EE7AE9
}
.b160,
.b160 a {
background-color: #EE7AE9
}
.r161,
r161 a {
color: #DA70D6
}
.b161,
.b161 a {
background-color: #DA70D6
}
.r162,
r162 a {
color: #BA55D3
}
.b162,
.b162 a {
background-color: #BA55D3
}
.r163,
r163 a {
color: #BF3EFF
}
.b163,
.b163 a {
background-color: #BF3EFF
}
.r164,
r164 a {
color: #B23AEE
}
.b164,
.b164 a {
background-color: #B23AEE
}
.r165,
r165 a {
color: #9B30FF
}
.b165,
.b165 a {
background-color: #9B30FF
}
.r166,
r166 a {
color: #836FFF
}
.b166,
.b166 a {
background-color: #836FFF
}
.r167,
r167 a {
color: #7A67EE
}
.b167,
.b167 a {
background-color: #7A67EE
}
.r168,
r168 a {
color: #9F79EE
}
.b168,
.b168 a {
background-color: #9F79EE
}
.r169,
r169 a {
color: #8968CD
}
.b169,
.b169 a {
background-color: #8968CD
}
.r170,
r170 a {
color: #FF6EB4
}
.b170,
.b170 a {
background-color: #FF6EB4
}
.r171,
r171 a {
color: #FF69B4
}
.b171,
.b171 a {
background-color: #FF69B4
}
.r172,
r172 a {
color: #EE3A8C
}
.b172,
.b172 a {
background-color: #EE3A8C
}
.r173,
r173 a {
color: #FF34B3
}
.b173,
.b173 a {
background-color: #FF34B3
}
.r174,
r174 a {
color: #FF1493
}
.b174,
.b174 a {
background-color: #FF1493
}
.r175,
r175 a {
color: #EE1289
}
.b175,
.b175 a {
background-color: #EE1289
}
.r176,
r176 a {
color: #CD2990
}
.b176,
.b176 a {
background-color: #CD2990
}
.r177,
r177 a {
color: #D02090
}
.b177,
.b177 a {
background-color: #D02090
}
.r178,
r178 a {
color: #C71585
}
.b178,
.b178 a {
background-color: #C71585
}
.r179,
r179 a {
color: #CD1076
}
.b179,
.b179 a {
background-color: #CD1076
}
.r180,
r180 a {
color: #FF4500
}
.b180,
.b180 a {
background-color: #FF4500
}
.r181,
r181 a {
color: #EE4000
}
.b181,
.b181 a {
background-color: #EE4000
}
.r182,
r182 a {
color: #FF4040
}
.b182,
.b182 a {
background-color: #FF4040
}
.r183,
r183 a {
color: #EE3B3B
}
.b183,
.b183 a {
background-color: #EE3B3B
}
.r184,
r184 a {
color: #EE2C2C
}
.b184,
.b184 a {
background-color: #EE2C2C
}
.r185,
r185 a {
color: #FF0000
}
.b185,
.b185 a {
background-color: #FF0000
}
.r186,
r186 a {
color: #DC143C
}
.b186,
.b186 a {
background-color: #DC143C
}
.r187,
r187 a {
color: #CD0000
}
.b187,
.b187 a {
background-color: #CD0000
}
.r188,
r188 a {
color: #B0171F
}
.b188,
.b188 a {
background-color: #B0171F
}
.r189,
r189 a {
color: #8B2323
}
.b189,
.b189 a {
background-color: #8B2323
}
.r190,
r190 a {
color: #FF6A6A
}
.b190,
.b190 a {
background-color: #FF6A6A
}
.r191,
r191 a {
color: #CD7054
}
.b191,
.b191 a {
background-color: #CD7054
}
.r192,
r192 a {
color: #CD6839
}
.b192,
.b192 a {
background-color: #CD6839
}
.r193,
r193 a {
color: #CD661D
}
.b193,
.b193 a {
background-color: #CD661D
}
.r194,
r194 a {
color: #C76114
}
.b194,
.b194 a {
background-color: #C76114
}
.r195,
r195 a {
color: #CD5B45
}
.b195,
.b195 a {
background-color: #CD5B45
}
.r196,
r196 a {
color: #CD4F39
}
.b196,
.b196 a {
background-color: #CD4F39
}
.r197,
r197 a {
color: #CD3333
}
.b197,
.b197 a {
background-color: #CD3333
}
.r198,
r198 a {
color: #CD2626
}
.b198,
.b198 a {
background-color: #CD2626
}
.r199,
r199 a {
color: #CD3700
}
.b199,
.b199 a {
background-color: #CD3700
}
</code></pre>
<h3>HTML Random Color View</h3>
<p><a href="https://i.stack.imgur.com/N9whV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N9whV.png" alt="Random Color HTML"></a></p>
| [] | [
{
"body": "<p>There is a lot going on here but I will focus on 3 specific problems that I find most glaring in your example, readability, DRY and redundancy.</p>\n\n<p><strong>Readability:</strong></p>\n\n<p>Code should be as easy to read as possible, complexity should be avoided as much as one can. Code that is hard to read is hard to change and we always need to change the code sooner or later. </p>\n\n<p>Naming variables is important, using single character variable names is just confusing.</p>\n\n<p><strong>DRY</strong></p>\n\n<p>Don't repeat yourself. Repetitive coding practises that crams in a lot of duplicate code in multiple places.</p>\n\n<p><strong>Redundancy</strong></p>\n\n<p>Code that is unnecessary </p>\n\n<p><strong>Changes:</strong></p>\n\n<ul>\n<li>Rename <code>$a</code> variable to something more appropriate, <code>$data</code> for instance (Readability)</li>\n<li>Move <code>UpdateStocks::getQuoteParams()</code> into the <code>foreach</code>, remove the <code>$i</code> variable (Redundancy)</li>\n<li>Remove the <code>$k</code> variable inside the <code>foreach</code> (Redundancy)</li>\n<li>Inverse the isset/empty condition so you don't need to wrap the whole code segment into it (Readability)</li>\n<li>Rename the <code>$p</code> variable to <code>$parameters</code> (Readability)</li>\n<li>Simplify array parameter, use <code>$id</code> in place of <code>$parameter[\"id\"]</code> (Readability)</li>\n<li>While <code>preg_match</code> is usable, since you only use the first 2 characters in this particular case you can use <code>substr</code> instead, it is easier on the eyes (Readability)</li>\n<li>Rename <code>$hs</code> variable to something more suitable like <code>$html</code> (Readability)</li>\n<li>Move up/down code that is repeated in each if/else (DRY)</li>\n<li>Use <code>$lb</code> instead of <code>$parameter[\"lb\"]</code> (Readability)</li>\n<li>Remove the <code>$h</code> variable altogether, not necessary (Redundancy)</li>\n<li>Replace if/elseif/elseif.../else with a switch statement (Readability)</li>\n<li>Define variables close to where they are used, move <code>$bt</code> to the bottom (Readability)</li>\n</ul>\n\n<p>I made a gif just showing you en example refactoring of your code, it's about 10 minutes. </p>\n\n<p><strong>NOTE</strong>: Don't copy the code straight up, it has not been tested, has made up mock data and a few changes to it so I could run it(changed date for example). It is just an example, you have been warned. :-)</p>\n\n<p><a href=\"https://gifyu.com/image/3nZB\" rel=\"nofollow noreferrer\">https://gifyu.com/image/3nZB</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T20:43:14.507",
"Id": "417158",
"Score": "1",
"body": "No problems, I made a couple of errors in the gif, I didn't properly invert the `if (isset...`, you need to invert the `!empty` to `empty` as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T20:58:44.153",
"Id": "417169",
"Score": "1",
"body": "Glad to help! Just be careful, as I said I have not tested this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T20:27:30.020",
"Id": "215629",
"ParentId": "215281",
"Score": "2"
}
},
{
"body": "<p>General pieces of advice that I will apply to your posted code:</p>\n\n<ol>\n<li>Avoid generating single-use variables.</li>\n<li>Try to avoid excessively long lines of code.</li>\n<li>Avoid repeatedly writing static text in your code</li>\n<li>Some brevity in variable naming is okay, but not to the detriment of readability.</li>\n<li>Avoid excessive nesting of control structures (e.g. <code>if</code>, <code>foreach</code>, etc) because they increase horizontal scrolling when reading your code.</li>\n<li>I have a distaste for switch blocks, but in this case, it is a sensible choice. Abstracting that process into a new method, afford the use of <code>return</code> instead of the usual <code>break</code> so the syntax is slightly more compact.</li>\n<li>Try to separate processing from printing (as much as possible).</li>\n</ol>\n\n<p>It seems you don't need to validate the defining character(s) of the <code>$p[\"id\"]</code>, you aren't even using the hyphen. For this reason, you don't need to call any functions to extract the first (single-byte) character -- you can use square brace syntax to access a character by its offset (<code>0</code> in this case).</p>\n\n<p>I'm going to try to maintain some semblance of tabbing within the html elements without making line width suffer too badly. This can be accomplished in a number of ways. I won't be offended if you or anyone else choose to declare the concatenation of <code>$html</code> differently.</p>\n\n<p>I can imagine that <code>$a</code> means <code>array</code>, but it would be better to give it a more descriptive name. Variables like <code>$string</code>, <code>$array</code>, <code>$data</code>, <code>$number</code> are often good candidates for renaming. Scripts often have multiple arrays within them.</p>\n\n<p>If your project actually demands a bit more validation on the leading substring of <code>$p[\"id\"]</code>, then try using non-regex tools like <code>substr()</code> before resorting to <code>preg_</code> functions.</p>\n\n<p>Untested Code:</p>\n\n<pre><code>public static function formatQuoteValue($id, $a_ky) {\n switch ($id[0]) {\n case \"s\": return $a_ky;\n case \"d\": return money_format('%=9.4n', (double)$a_ky);\n case \"v\": return money_format('%=*!#4.0n', (double)$a_ky);\n case \"t\": return date('l, d F Y \\⏱ H:i T \\(P \\U\\T\\C\\)', (double)$a_ky/1000);\n case \"p\": return money_format('%=*!#4.4n', (double)$a_ky) . '%';\n default: return $a_ky . '%';\n }\n}\n\npublic static function getQuoteHTML($a) {\n $html = '<div class=\"ro\">' .\n '<a href=\"#\"' .\n ' class=\"s18 ro tx-1 b119 r100 t-21 p-2 br-5 mv-3\"' .\n ' onclick=\"J.s({d:this}); return false;\"' .\n ' title=\"' . $a[\"symbol\"] . ' latest quote\">' .\n ' Quote: ' . date('l, d F Y \\⏱ H:i T', microtime(true)) .\n '</a>' .\n '<div class=\"di-0\">' .\n '<div class=\"p-3\">';\n\n foreach (UpdateStocks::getQuoteParams() as $param) {\n if (!isset($param[\"id\"]) || empty($a[$param[\"ky\"]])) {\n continue;\n }\n $class = 'di-1 t-21 m-1 br-3 p-2 b119 r1' . rand(20,99);\n $html .= '<p id=\"' . $param[\"id\"] . '\">';\n $html .= '<b class=\"' . $class . '\">' . $param[\"lb\"] . '</b>: ';\n $html .= '<b class=\"' . $class . '\">' . UpdateStocks::formatQuoteValue($param[\"id\"], $a[$param[\"ky\"]]) . '</b>';\n $html .= '</p>';\n }\n\n $html .= '</div>' .\n '</div>' .\n '</div>';\n\n return $html;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T06:36:08.323",
"Id": "215726",
"ParentId": "215281",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215629",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T17:02:31.060",
"Id": "215281",
"Score": "0",
"Tags": [
"beginner",
"php",
"html"
],
"Title": "Methods To Generate an HTML String using an Array in PHP"
} | 215281 |
<p>I am new to Jenkins. I am doing a build through Jenkins, but the build is very slow. Is there any way I can speed it up?</p>
<pre><code>#!/usr/bin/env groovy
@Library('cplib') _
import com.sports.paas.cplib.helpers.Build
import com.sports.paas.cplib.helpers.Workspace
import com.sports.paas.cplib.utils.Openshift
def bld = new Build()
def wspace = new Workspace()
def osh = new Openshift()
def appReleaseTag = ""
def NODE_HOME = "${JENKINS_HOME_SLAVE}/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/Node_6.11.1"
def projectName = "player"
def appName = "ball"
def appOcpConfigBranch = "master"
// ########################################################################################
// PIPELINE WORKFLOW
// ########################################################################################
pipeline {
agent { node('nodejs')}
tools {
nodejs 'nodejs-8.11.2'
}
options {
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '30', daysToKeepStr: '15'))
skipDefaultCheckout(true)
timestamps()
skipStagesAfterUnstable()
}
parameters {
choice (
name : 'DEPLOY_ENVIRONMENT',
choices: ' \nunit\ntest\nstage',
description: '[Required] Select the location to deploy.'
)
}
stages {
stage('Prepare') {
steps {
script {
log.info "Explicit scm checkout ..."
checkout scm
wspace.init()
// wspace.checkoutAppOcpConfig(appName, appOcpConfigBranch)
appReleaseTag = wspace.getBuildProperty("version") + "." + env.BUILD_NUMBER
}
}
}
stage('Build Artifacts') {
steps {
script {
sh """
echo "Building artifacts ..."
export PATH=$PATH:$NODE_HOME/bin;
echo "Running node build ..."
# Please build your application using npm or yarn. Application build
# using yarn has been tested for a 35% faster execution when compared to yarn.
#npm install --no-optional --production --silent
npm install
echo "@@@ NPM RUN PROD ( BUILD )"
npm run build
#yarn
"""
}
prepareForBuildImage()
}
}
stage('Build Image') {
steps {
script {
if(!wspace.releaseVersionExists()) {
appReleaseTag = osh.buildAppImage(appName, appReleaseTag)
} else {
appReleaseTag = env.RELEASE_VERSION
}
}
}
}
stage('Deploy Unit') {
steps {
script {
envName=env.DEPLOY_ENVIRONMENT
osh.deploy(projectName+"-"+envName, appName, envName,appReleaseTag)
}
}
}
} //stages
} // pipeline
def prepareForBuildImage() {
sh '''
echo "Preparing Image contents ..."
rm -rf tmp
mkdir -p tmp
chmod -R 777 tmp
echo "Compressing files ..."
tar cvzf tmp.tar.gz client server *.json node_modules index.js build.properties README.md
cp -pr tmp.tar.gz tmp/
echo "Decompressing files ..."
cd tmp
tar xvzf tmp.tar.gz
rm -fr tmp.tar.gz
cd ..
echo "Displaying deployment artifacts ..."
ls -Rlt tmp/ --ignore=node_modules
'''
}
</code></pre>
| [] | [
{
"body": "<p>I have just really dove in and the approach you are using wouldn't be the way I would use.</p>\n<p>A lot of the redundant env variables you define and use can simply be extracted from the environment.</p>\n<p>The environment block is the suggested way to set env variables, of course doing it within a 'sh' script works but it gets lost and there are a variety of variables being set all over the place. Trying to just keep features/functionality together does help readability. And in improving readability, you personally will start to uncover the unnecessary and/or duplicate or even triplicate methods that are easily lost when the file basically is a hold your breath and jump.</p>\n<p>I've taken this file and have gotten rid of about 64% of the code, which is 64% you don't have to read, try to assimilate or even worry about.</p>\n<p>To answer your very succinct question after all this;</p>\n<p>Clean it up, refactor out redundancy, unnecessary code, prefer the gatekeeper pattern instead of nested conditions, this will keep all code at the same indentation (that's assuming you actually indent, so many don't, so aggravating)</p>\n<p>the pattern is</p>\n<pre><code>if(isNotValid()) return <value if need be>\n\n// if the code is here, the above check passed\n</code></pre>\n<p>Start there, challenge yourself to see if you can get this file down 50%.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T20:00:15.837",
"Id": "527945",
"Score": "0",
"body": "Please add further details to expand on your answer, such as working code or documentation citations."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T14:36:21.453",
"Id": "267734",
"ParentId": "215290",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T18:58:42.250",
"Id": "215290",
"Score": "1",
"Tags": [
"javascript",
"performance",
"node.js",
"json",
"yaml"
],
"Title": "jenkins deployment making the build very slow"
} | 215290 |
<p>I put a solution to <a href="https://edabit.com/challenge/prCamevvoWkq27KBz" rel="nofollow noreferrer">this coding problem</a> together. The problem is this:</p>
<blockquote>
<p>Create a function that takes an array, finds the most often repeated element(s) within it and returns it/them in an array. The function should work for both integers and strings mixed together within the input list (e.g. <code>[1, 1, "a"]</code>).</p>
<p>If there is a tie for highest occurrence, return both.</p>
<p>Separate integers and strings in the result.</p>
<p>If returning multiple elements, sort result alphabetically with numbers coming before strings.</p>
</blockquote>
<p>This is the solution I came up with:</p>
<pre><code>def highest_occurrence(arr)
# Separate the unique values into individual sub-arrays
x = rand(2**32).to_s(16)
result = arr.sort do |a, b|
a = a.to_s + x if a.is_a?(Numeric)
b = b.to_s + x if b.is_a?(Numeric)
a <=> b
end.chunk_while {|a, b| a == b }.to_a
# Get an array of all of the individual values with the max size,
# Sort them by integers first, strings second
result = result.select do |a2|
a2.size == result.max_by(&:size).size
end.map(&:uniq).flatten.sort_by { |v| v.class.to_s }
end
</code></pre>
<p>It passes these tests:</p>
<pre><code>p highest_occurrence(["a","a","b","b"]) == ["a","b"]
p highest_occurrence([1,"a","b","b"]) == ["b"]
p highest_occurrence([1,2,2,3,3,3,4,4,4,4]) == [4]
p highest_occurrence(["ab","ab","b"]) == ["ab"]
p highest_occurrence(["ab","ab","b","bb","b"]) == ["ab","b"]
p highest_occurrence([3,3,3,4,4,4,4,2,3,6,7,6,7,6,7,6,"a","a","a","a"]) == [3,4,6,"a"]
p highest_occurrence([2,2,"2","2",4,4]) == [2,4,"2"]
</code></pre>
<p>I'd like to know whether there are better ways to solve some of the specific problems in this exercise. In particular, the requirement to sort strings and integers together without being able to convert the integers to strings in the sort block was an interesting one. I managed this by appending a random hex value (the same value) to each integer during the sort process. This seems a bit hackish, and I have the feeling it could be improved upon.</p>
<p>I would also appreciate any other suggestions for how to do a cleaner job.</p>
| [] | [
{
"body": "<p>Your test cases should include lexical sort of integers; that is, <code>[9,11]</code> must return <code>[11,9]</code>. (Your implementation does pass this test since you're converting everything to a string).</p>\n\n<p>As you suspected, mangling the input is hacky. This is better accomplished with a <a href=\"https://stackoverflow.com/questions/29856004/how-to-sort-a-ruby-array-by-two-conditions\">multi-criteria sort</a>. This technique maps each individual value to an array of sort criteria. Ruby will compare the arrays only until it finds unequal elements; this means you can mix integers and strings in the second field, so long as the first field distinguishes them.</p>\n\n<p>For our problem, the first field will be 0 for integers else 1. The second field is the value itself.</p>\n\n<p>Although this approach will never compare integers to strings—if the first criteria distinguishes the two elements, the comparison is done—the second criteria must be a string anyway, to satisfy the \"sort alphabetically\" requirement.</p>\n\n<p>It's not necessary to sort the entire array or store a full copy of it. Instead, count duplicates in a hash table. Traverse the values of the hash to find a maximum. Traverse again to extract the corresponding keys.</p>\n\n<pre><code>def highest_occurrence(arr)\n return arr if arr.size <= 1\n count = Hash.new(0)\n arr.each { |k| count[k] += 1 }\n max = count.max_by{|k,n| n}[1]\n return count.select { |k,n| n==max }.keys.sort_by { |k| [ k.is_a?(Integer)?0:1, k.to_s ] }\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T01:26:32.810",
"Id": "416391",
"Score": "0",
"body": "Thanks for your answer and your very helpful example. I've stepped through it, and it's entirely clear. Very nice upgrade to mine! Two things I don't quite understand: the spec says to return integers sorted in ascending order, followed by strings sorted in ascending order. Why, then, should `[9,11]` return `11,9]`? Also, why can't you just do `.sort_by { |k| k.is_a?(Integer)?0:1 }`? What test cases would fail to that? None of miine do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T01:43:30.063",
"Id": "416392",
"Score": "1",
"body": "I answered my second question, once I went to the trouble of reading the link that you posted and doing a few other test cases. All my test cases happen to have the max values in the proper sorted order already! I switched them around and they failed. So, that's how you do a nested sort: put the criteria in an array. I'll put that in the file. Also, now that I look at it, I think that's what you were trying to tell me up front. Is it possible that you intended to say that `[11, 9]` should return '[9,11]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T01:50:30.747",
"Id": "416393",
"Score": "0",
"body": "One more thing. I don't think that `return [] unless arr.length` will ever return a `[]`, since `0` evaluates to `true` in Ruby. Is this a carry-over pattern from some other language such as JS? I would put `return [] if arr.size.zero?` myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T02:40:14.407",
"Id": "416394",
"Score": "0",
"body": "you're right, that's a bug. Edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T02:46:59.123",
"Id": "416395",
"Score": "1",
"body": "You post said \"sort result alphabetically\" which to me means \"lexically,\" implying 9 vs 11 should sort the same way \"9\" vs \"11\" does: with 11 first. It's an odd phrasing and maybe just sloppiness on the part of the problem's author. If this were a contract I'd ask the client if that's what they really wanted. To sort the integers numerically, simply remove `.to_s` at the very end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T07:09:16.787",
"Id": "416410",
"Score": "1",
"body": "Aha, good point. Yes, so would I! I'll mention this in the comments section to the problem. Thanks again for your help; this has been very instructive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T22:37:10.223",
"Id": "418328",
"Score": "0",
"body": "I think you might `return arr if arr.size <= 1`, as a single input is also a bit of a special case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T23:51:08.493",
"Id": "418332",
"Score": "0",
"body": "@DavidAldridge nice. Done."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T00:58:28.300",
"Id": "215311",
"ParentId": "215294",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "215311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T19:50:31.937",
"Id": "215294",
"Score": "2",
"Tags": [
"ruby",
"sorting"
],
"Title": "Sorting an assortment of strings and integers together, while keeping them separate"
} | 215294 |
<p>For comparison with other external sorting algorithms, I have implemented <em>external polyphase merge sort</em>, purported to be useful to sort large files that do not fit into main memory. More theoretical info about the algorithm itself can be found <a href="https://en.wikipedia.org/wiki/Polyphase_merge_sort" rel="nofollow noreferrer">here</a>.<br>
My implementation uses a <em>Priority Queue</em> (PQ) as the internal data structure used to extract the smallest element when needed. Elements of the PQ are of a type <code>StringRecord</code> which represents a single line from the main input file.</p>
<p>The algorithm works as expected but it is very slow.<br>
The first - <strong>distribution phase</strong> works just fine without any performance issues.<br>
The problem must be somewhere in the second - <strong>merge phase</strong>. I have already removed/fixed some minor performance issues but the major issue is obviously still present.<br>
For benchmarking, this <a href="https://drive.google.com/open?id=1W1AZjr5TGpDa0inbDQM_9s_vyPhEUXsT" rel="nofollow noreferrer">~786 MB input file</a> with 134217728 lines has been generated. In one test with all files on a local WD Blue 1 TB HDD with 16 MB of cache, sorting took about 230 seconds after warm-up. Timing has been established using <code>System.currentTimeMillis()</code> & <code>System.out.println()</code> as shown.</p>
<pre><code>/**
* StringRecord class represent a single line of text in input files that algorithm is working with
* in merge procedure. It is defined by two attributes: value itself and a file index where value is stored in.
*/
public class StringRecord implements Comparable<StringRecord>
{
/** String value of this StringRecord. */
private String value;
/** Index of an input file where this value is stored in. */
private int file_index;
/**
* Constructor used to create new instance of StringRecord class.
*
* @param value string value of this StringRecord.
* @param file_index index of a file where @param value is stored in.
*/
public StringRecord(String value, int file_index)
{
this.value = value;
this.file_index = file_index;
}
/**
* Returns value of this StringRecord object.
*/
public String getValue()
{
return value;
}
/**
* Returns file_index of this StringRecord object.
*/
public int getFileIndex()
{
return file_index;
}
/**
* Compares this StringRecord value to @param string_record value for their lexicographical order.
*
* It returns 0 if the argument is a string value lexicographically equal to this string value,
* less than 0 if the argument is a string value lexicographically greater than
* this string value and greater than 0 if the argument is a string value lexicographically
* less than this string value.
*
* @param string_record string record where it's value is compared to this object value.
*/
public int compareTo(StringRecord string_record)
{
return this.value.compareTo(string_record.value);
}
}
</code></pre>
<p></p>
<pre><code>import java.io.*;
import java.util.PriorityQueue;
/**
* PMSS algorithm sorts input text file of strings using polyphase merge procedure with a help of two or more auxilary files.
* In the first part it uses these files to distribute input data and then merges them in the second part.
* <p>
* Distribution of the input data is based on Fibonacci numbers sequence which is depending
* on number of auxilary files that algorithm is working with. The algorithm uses internal
* data structure <i>PriorityQueue</i> to store run elements. Priority queue is also used
* to find a minimum element that will be first written to the output file.
* The algorithm uses a class named <i>StringRecord</i> which represent a single line in
* input file defined by two attributes: value itself and file index where value is stored in.
* All elements of the priority queue are of type StringRecord.
* <p>
* Distribute procedure repeats until entire input data is distributed following Fibonacchi sequence numbers.
* Merge procedure repeats until all the data is sorted in ascending order. The algorithm
* produces a brand new output file which contains sorted data and thus retains input file unchanged.
* <p>
* @param temp_files number of auxiliary files used for data distribution and merging.
* @param working_dir path to local directory where all the sorting takes place.
* @param main_string_file local text file which contains all input data separated by new a line character.
*
* @throws IOException if an input or output exception occurred during file operations.
*
*/
public class PMSS
{
/** Amount of input data read by input file reader in distribute phase of the algorithm. */
static long data_read = 0;
/** Variable used to store the first element of next run. Used only in writeNextStringRun() method. */
static String next_run_element;
/** Index of current active output file where runs are being merged. */
static int output_file_index;
/** Index of previous active output file (previous distribution level). */
static int old_output_file_index;
/** Amount of runs on current distribution level. */
static int runs_per_level;
/** Array used to store missing (dummy) runs for each input file after the distribute phase. */
static int missing_runs[];
/** Array used to determine distribution of runs in input files. Each input file should
* contain exactly the same amount of runs as specified in this arrays indexes.
**/
static int distribution_array[];
/** Array used as a semaphore for input file readers. If value on a certain index equals 1,
* input file reader is allowed to read from attached file. If value is 0, reading is not allowed.
**/
static int allow_read[];
/** Array used to store all last elements of the current runs from each input file. */
static String last_elements[];
/** Array used to store all last elements of the current runs from each input file. Used only in
* distribute phase of the algorithm.
**/
static String run_last_elements[];
/** Array used to store all first elements of the next runs from each input file. */
static StringRecord next_run_first_elements[];
/**
* Main data structure of the algorithm. It is used to extract next minimum string
* that needs to be written to output file. When q is empty on a certain distribution
* level, all runs on this level have merged to output file.
*/
static PriorityQueue<StringRecord> q = new PriorityQueue<StringRecord>();
public static void main(String args[]) throws Exception
{
int temp_files = 24;
String file_extension = ".txt";
String working_dir = "/path/to/working/directory";
File main_file = new File(working_dir + "/main" + file_extension);
File sorted_file = new File(working_dir + "/sorted" + file_extension);
BufferedReader main_file_reader = new BufferedReader(new FileReader(main_file));
long main_file_length = main_file.length();
File working_files[] = new File[temp_files + 1];
sorted_file.delete();
allow_read = new int[temp_files + 1];
missing_runs = new int[temp_files + 1];
last_elements = new String[temp_files + 1];
distribution_array = new int[temp_files + 1];
run_last_elements = new String[temp_files + 1];
next_run_first_elements = new StringRecord[temp_files + 1];
String working_file_name = "working_file_";
BufferedReader run_file_readers[] = new BufferedReader[temp_files + 1];
for(int i=0; i<working_files.length; i++)
{
working_files[i] = new File(working_dir + working_file_name + (i+1) + file_extension);
}
/* START - initial run distribution */
distribute(temp_files, working_files, main_file_length, main_file_reader);
/* END - initial run distribution */
/* START - polyphase merge */
long start = System.currentTimeMillis();
int min_dummy_values = getMinDummyValue();
initMergeProcedure(min_dummy_values);
BufferedWriter writer = new BufferedWriter(new FileWriter(working_files[output_file_index]));
for(int i=0; i<run_file_readers.length-1; i++)
{
run_file_readers[i] = new BufferedReader(new FileReader(working_files[i]));
}
while(runs_per_level > 1)
{
last_elements[output_file_index] = null;
merge(distribution_array[getMinFileIndex()] - min_dummy_values, run_file_readers, writer);
setPreviousRunDistributionLevel();
updateOutputFileIndex();
resetAllowReadArray();
min_dummy_values = getMinDummyValue();
writer = new BufferedWriter(new FileWriter(working_files[output_file_index]));
run_file_readers[old_output_file_index] = new BufferedReader(new FileReader(working_files[old_output_file_index]));
}
writer.close();
main_file_reader.close();
closeReaders(run_file_readers);
clearTempFiles(working_dir, main_file, working_files);
long end = System.currentTimeMillis();
/* END - polyphase merge */
System.out.println("Merge phase done in " + (end-start) + " ms");
}
/**
* Distributes contents of main input file to @temp_files temporary output files.
* Input data is distributed according to distribution_array which contains for
* every temporary file a predifined amount of runs that should reside in certain file
* on a certain distribution level. Calculation of array values is based on Fibonacci
* sequence numbers. When input data on a certain level is distributed, next level is calculated
* if and only if the input file is not consumed yet.
*
* @param temp_files number of temporary files to work with.
* @param working_files array of all working files. The size of this array equals @temp_files.
* @param main_file_length length of the main input file.
* @param main_file_reader reader used to read main input file.
*/
private static void distribute(int temp_files, File working_files[], long main_file_length, BufferedReader main_file_reader)
{
try
{
long start = System.currentTimeMillis();
runs_per_level = 1;
distribution_array[0] = 1;
output_file_index = working_files.length - 1;
int write_sentinel[] = new int[temp_files];
BufferedWriter run_file_writers[] = new BufferedWriter[temp_files];
for(int i=0; i<temp_files; i++)
{
run_file_writers[i] = new BufferedWriter(new FileWriter(working_files[i],true));
}
/* START - distribute runs */
while(data_read < main_file_length)
{
for(int i=0; i<temp_files; i++)
{
while(write_sentinel[i] != distribution_array[i])
{
while(runsMerged(main_file_length, i, next_run_element))
{
writeNextStringRun(main_file_length, main_file_reader, run_file_writers[i], i);
}
writeNextStringRun(main_file_length, main_file_reader, run_file_writers[i], i);
missing_runs[i]++;
write_sentinel[i]++;
}
}
setNextDistributionLevel();
}
closeWriters(run_file_writers);
setPreviousRunDistributionLevel();
setMissingRunsArray();
long end = System.currentTimeMillis();
System.out.println("Distribute phase done in " + (end-start) + " ms");
/* END - distribute runs */
}
catch(Exception e)
{
System.out.println("Exception thrown in distribute(): " + e.getMessage());
}
}
/**
* Merges predefined amount of dummy runs from all input files to output file.
* Amount of dummy runs that can be merged is defined by @param min_dummy.
* Since there should be no special markers in input files, all the merging results
* as adequate substraction/addition in missing_runs array.
* Additionaly this method resets allow_read array once dummy run merge is over.
*
* @param min_dummy minimum amount of runs which is the same for all input files.
*/
private static void initMergeProcedure(int min_dummy)
{
try
{
for(int i=0; i<missing_runs.length - 1; i++)
{
missing_runs[i] -= min_dummy;
}
missing_runs[output_file_index] += min_dummy;
resetAllowReadArray();
}
catch(Exception e)
{
System.out.println("Exception thrown in initMergeProcedure(): " + e.getMessage());
}
}
/**
* Merges @param min_file_values runs into a single run and writes it to output file bounded by @param writer.
* @param min_file_values is a minimum number of runs per current distribution level. Procedure merges @param min_file_values
* from all of the input files and terminates afterwards.
*
* @param min_file_values number of runs that will be merged in a single execution of merge procedure.
* @param run_file_readers array of all input file readers.
* @param writer writer for output file.
*/
private static void merge(int min_file_values, BufferedReader run_file_readers[], BufferedWriter writer)
{
String line;
int min_file;
int heap_empty = 0;
StringRecord record;
/* Initial heap population */
populateHeap(run_file_readers);
try
{
while(heap_empty != min_file_values)
{
record = q.poll();
writer.write(record.getValue() + "\n");
min_file = record.getFileIndex();
if(allow_read[min_file] == 1 && (line = readFileLine(run_file_readers[min_file],min_file)) != null)
{
q.add(new StringRecord(line,min_file));
}
try
{
/* Once heap is empty all n-th runs have merged */
if(q.size() == 0)
{
heap_empty++;
for(int i=0; i<next_run_first_elements.length; i++)
{
try
{
q.add(new StringRecord(next_run_first_elements[i].getValue(),i));
last_elements[i] = next_run_first_elements[i].getValue();
}
catch(Exception e){}
}
populateHeap(run_file_readers);
resetAllowReadArray();
if(heap_empty == min_file_values)
{
writer.close();
return;
}
}
}
catch(Exception e){}
}
}
catch(Exception e)
{
System.out.println("Exception thrown in merge(): " + e.getMessage());
}
}
/**
* Updates current output_file_index which points to output file where runs are being merged to.
*/
private static void updateOutputFileIndex()
{
if(output_file_index > 0)
{
output_file_index--;
}
else
{
output_file_index = distribution_array.length - 1;
}
}
/**
* Reads next value of each run into a priority queue. Reading is allowed if certain input file
* contains no dummy runs and reading from input file is allowed by allow_read array.
*
* @param run_file_readers array of all input file readers.
*/
private static void populateHeap(BufferedReader run_file_readers[])
{
try
{
String line;
for(int i=0;i<run_file_readers.length;i++)
{
if(missing_runs[i] == 0)
{
if((allow_read[i] == 1) && (line = readFileLine(run_file_readers[i],i)) != null)
{
q.add(new StringRecord(line,i));
}
}
else
{
missing_runs[i]--;
}
}
}
catch(Exception e)
{
System.out.println("Exception thrown while initial heap population: " + e.getMessage());
}
}
/**
* Reads next line of text from file bounded by @param file_reader.
*
* @param file_reader reader used to read from input file.
* @param file_index index of a file from which @param file_reader reads the data.
* @return next line of text from file, null instead.
*/
private static String readFileLine(BufferedReader file_reader, int file_index)
{
try
{
String current_line = file_reader.readLine();
/* End of run */
if(last_elements[file_index] != null && current_line.compareTo(last_elements[file_index]) < 0)
{
next_run_first_elements[file_index] = new StringRecord(current_line,file_index);
allow_read[file_index] = 0;
return null;
}
else
{
last_elements[file_index] = current_line;
return current_line;
}
}
catch(Exception e)
{
allow_read[file_index] = 0;
next_run_first_elements[file_index] = null;
}
return null;
}
/**
* Resets allow_read array to its initial state. It additionally sets
* index of output_file_index to 0 and thus prevents read operations
* from output file.
*/
private static void resetAllowReadArray()
{
for(int i=0; i<allow_read.length; i++)
{
allow_read[i] = 1;
}
allow_read[output_file_index] = 0;
}
/**
* Returns the minimum amount of dummy runs present amongst input files.
*
* @return the minimum amount of present runs.
*/
private static int getMinDummyValue()
{
int min = Integer.MAX_VALUE;
for(int i=0; i<missing_runs.length; i++)
{
if(i != output_file_index && missing_runs[i] < min)
{
min = missing_runs[i];
}
}
return min;
}
/**
* Returns index of a file which according to distribution_array contains the minimum amount of runs.
*
* @return index of a file with minimum amount of runs.
*/
private static int getMinFileIndex()
{
int min_file_index = -1;
int min = Integer.MAX_VALUE;
for(int i=0; i<distribution_array.length; i++)
{
if(distribution_array[i] != 0 && distribution_array[i] < min)
{
min_file_index = i;
}
}
return min_file_index;
}
/**
* Writes next string run to output file pointed by @param run_file_writer.
*
* @param main_file_length length of the main input file.
* @param main_file_reader reader used to read main input file.
* @param run_file_writer writer used to write to a specific output file
* @param file_index used to update missing_runs and run_last_elements arrays.
* In case when main input file is read to the end amount of
* dummy runs on this index in missing_runs array needs to be
* decreased. When run is ended run_last_elements array on
* this index is populated with the last element of the run.
*
*/
private static void writeNextStringRun(long main_file_length, BufferedReader main_file_reader, BufferedWriter run_file_writer, int file_index)
{
if(data_read >= main_file_length)
{
missing_runs[file_index]--;
return;
}
try
{
if(next_run_element != null)
{
run_file_writer.write(next_run_element + "\n");
data_read += next_run_element.length() + 1;
}
String min_value = "";
String current_line = main_file_reader.readLine();
/* Case if run is a single element: acordingly update variables and return */
if(next_run_element != null)
{
if(next_run_element.compareTo(current_line) > 0)
{
run_last_elements[file_index] = next_run_element;
next_run_element = current_line;
return;
}
}
while(current_line != null)
{
if(current_line.compareTo(min_value) >= 0)
{
run_file_writer.write(current_line + "\n");
data_read += current_line.length() + 1;
min_value = current_line;
current_line = main_file_reader.readLine();
}
else
{
next_run_element = current_line;
run_last_elements[file_index] = min_value;
return;
}
}
}
catch(Exception e){}
}
/**
* Checks if two adjacent runs have merged into a single run. It does this by comparing the first element
* of the second run with the last element of the first run. If this two elements are in sorted order, the runs
* have merged.
*
* @param main_file_length length of the main input file.
* @param file_index index in array from which last element of the first run is taken for comparison.
* @param first_element first element of the second run to be taken into comparison.
* @return true if the runs have merged, false instead.
*/
private static boolean runsMerged(long main_file_length, int file_index, String first_element)
{
if(data_read < main_file_length && run_last_elements[file_index] != null && first_element != null)
{
return run_last_elements[file_index].compareTo(first_element) <= 0 ? true:false;
}
return false;
}
/**
* Calculates next run distribution level. The new level is calculated following
* Finonacchi sequence rule.
*/
private static void setNextDistributionLevel()
{
runs_per_level = 0;
int current_distribution_array[] = distribution_array.clone();
for(int i=0; i<current_distribution_array.length - 1; i++)
{
distribution_array[i] = current_distribution_array[0] + current_distribution_array[i+1];
runs_per_level += distribution_array[i];
}
}
/**
* Calculates previous run distribution level. The new level is calculated following.
* Finonacchi sequence rule.
*/
private static void setPreviousRunDistributionLevel()
{
int diff;
int current_distribution_array[] = distribution_array.clone();
int last = current_distribution_array[current_distribution_array.length - 2];
old_output_file_index = output_file_index;
runs_per_level = 0;
runs_per_level += last;
distribution_array[0] = last;
for(int i=current_distribution_array.length - 3; i>=0; i--)
{
diff = current_distribution_array[i] - last;
distribution_array[i+1] = diff;
runs_per_level += diff;
}
}
/**
* Calculates the amount of dummy runs for every input file after distribute phase of the algorithm.
*/
private static void setMissingRunsArray()
{
for(int i=0; i<distribution_array.length - 1; i++)
{
missing_runs[i] = (distribution_array[i] - missing_runs[i]);
}
}
/**
* Closes all file readers used to read from run files in distribute phase of the algorithm.
*
* @param run_file_readers array of readers to read from run files.
*/
private static void closeReaders(BufferedReader run_file_readers[])
{
try
{
for(int i=0; i<run_file_readers.length; i++)
{
run_file_readers[i].close();
}
}
catch(Exception e){}
}
/**
* Closes all file writers used to write to run files in distribute phase of the algorithm.
*
* @param run_file_writers array of writers to write to run files.
*/
private static void closeWriters(BufferedWriter run_file_writers[])
{
try
{
for(int i=0; i<run_file_writers.length; i++)
{
run_file_writers[i].close();
}
}
catch(Exception e){}
}
/**
* Clears all unnecessary temporary files and renames the sorted one to its final name.
*
* @param working_dir path to working directory where entire sorting process is taking place.
* @param main_file main input file.
* @param temp_files number of temporary files to work with.
*/
private static void clearTempFiles(String working_dir, File main_file, File temp_files[])
{
File sorted_file = new File(working_dir+"sorted.txt");
for(int i=0; i<temp_files.length; i++)
{
if(temp_files[i].length() == main_file.length())
{
temp_files[i].renameTo(sorted_file);
temp_files[i].delete();
}
temp_files[i].delete();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T06:00:38.620",
"Id": "416401",
"Score": "1",
"body": "(Welcome to CodeReview!) That is a lot of code: does it contain everything to reproduce the timing issues? Can you give an overview of the strategy used? (Beyond *algorithm*: are the files in tmp files on disks, SSD, cloud? Synchronous IO or not? (you import io, not nio?!) …) What *are* your findings about where wall clock time goes: key comparison? Waiting for file input? Output? Copying records from buffer to buffer? (For laughs: PQ operations?) How did you establish temporal performance? What can you say about the input: number of records and distribution of key length & record size?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T06:10:20.580",
"Id": "416402",
"Score": "1",
"body": "(Can't remember seeing source on CR before that made me think *running javadoc is bound to provide me with food for thought if not insight*: well done!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T07:57:02.010",
"Id": "416416",
"Score": "0",
"body": "@greybeard this is all the code I have. What do you mean by \"strategy used\"? All the temporary files that algorithm works with are stored on a local WD Blue 1 TB HDD with 16 MB of cache. The main input file for the algorithm is .txt file with strings of a random lengths (1-15) separated by a new line character. All the files that algorithm works with (temp files, main input file, final sorted file) are stored in the same directory defined by working_dir variable. There is no special order defined for the main file - it is randomly distributed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T08:20:36.533",
"Id": "416421",
"Score": "0",
"body": "I don't have useful idea why it works so slow. Key (string) comparison is by default slow since comparing strings right? One idea is that writing is somehow slow (despite I am using BufferedWritter and BufferedReader). There is no special wait for input/output file(s), it is just the sort phase that needs to finish. Just an example of timing: sorting txt file with 134217728 lines (786 MB) takes about 260 second. If running the algorithm in loop for about 10 times, this time stabilises at around 230 seconds. I can link the file if needed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T06:53:21.290",
"Id": "416582",
"Score": "0",
"body": "`main input […] is .txt file with strings of a random lengths (1-15) …` This looks *generated file*: rather than linking to such a file, include the generator source. *Strategy*: I gave two examples of *what* hoping for *why*s, more: how many files to use (symmetric merge can be expected to use *less* passes above 8), \"character set\" or unicode I/O. *How* did you establish `distribution phase works just fine without any performance issues` and `merge phase […] major issue […] still present`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T21:54:01.967",
"Id": "416743",
"Score": "0",
"body": "(Just started tinkering - timing seems to be much worse (~50 seconds for distribution)?! From the temp file sizes, something is very, very wrong. (Like my picture of the workings of polyphase merge, maybe.) hm. Keeping one core semi-busy.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T05:46:13.413",
"Id": "416773",
"Score": "0",
"body": "I find repeated strings in the output that are not repeated in the input - dummy run handling seems to be off."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T08:13:10.297",
"Id": "416775",
"Score": "0",
"body": "I am sorry but the generator used to generate this file is gone, that is why I posted link to it. The input file was generated picking random strings from https://norvig.com/big.txt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T08:35:09.957",
"Id": "416780",
"Score": "0",
"body": "I was apparently wrong about distribute phase performance. In comparison with merge phase it is much faster. But still: since I have to check if every two adjacent runs have merged that must add something to timing issue?"
}
] | [
{
"body": "<blockquote>\n <p>The algorithm works as expected …</p>\n</blockquote>\n\n<p>How do you know? Sketch what tests you did how. </p>\n\n<blockquote>\n <p>…but it is very slow.</p>\n</blockquote>\n\n<p>My current take: due to Exception handling, due in turn to <strong><em>not</strong> working as specified</em>.<br>\n(Test input: download of <a href=\"https://norvig.com/big.txt\" rel=\"nofollow noreferrer\">norvig.com/big.txt</a> - loads of <code>NullPointerException</code> trying to dereference <code>next_run_first_elements[i]</code>.) </p>\n\n<hr>\n\n<p>For every class where instances can be expected to turn up in arrays, collections and such, override <code>toString()</code>:</p>\n\n<pre><code>@Override\npublic String toString() {\n return new StringBuilder().append(value)\n .append('#').append(file_index).toString();\n}\n</code></pre>\n\n<p>I failed to come up with a <em>good</em> summary of what <code>setNextDistributionLevel()</code> and <code>setPreviousRunDistributionLevel()</code> do, which is why I present the 1st <em>without doc comment</em>. (The naming is inconsistent.)</p>\n\n<pre><code>private static void setNextDistributionLevel()\n{\n final int\n ways_1 = distribution_array.length - 2,\n diff = distribution_array[0];\n for (int i = 0, next ; i <= ways_1 ; i = next)\n distribution_array[i] = distribution_array[next = i+1] + diff;\n runs_per_level += diff * ways_1;\n // System.out.println(\"next \" + runs_per_level + \": \" + Arrays.toString(distribution_array));\n}\n\n/**\n* Calculates previous run distribution level:\n* every number of runs is smaller than in the previous level\n* by the smallest number therein */// ToDo: describe commendably\nprivate static void setPreviousRunDistributionLevel()\n{\n final int \n ways_1 = distribution_array.length - 2,\n diff = distribution_array[ways_1];\n\n for (int i = ways_1, next ; 0 < i ; i = next)\n distribution_array[i] = distribution_array[next = i-1] - diff;\n runs_per_level -= diff * ways_1;\n distribution_array[0] = diff;\n // System.out.println(\"prev \" + runs_per_level + \": \" + Arrays.toString(distribution_array));\n}\n</code></pre>\n\n<p><code>closeReaders()</code> & <code>closeWriters()</code> contain repeated code and don't live up to their documentation in case of an exception - suggestion:</p>\n\n<pre><code>/** Closes all Writers in <code>run_file_writers</code>. */\nprivate static void closeWriters(BufferedWriter run_file_writers[]) {\n closeAll(run_file_writers);\n}\n\n/** Closes all <code>candidates</code>. */\nprivate static void closeAll(Closeable candidates[]) {\n for (Closeable candidate: candidates)\n try {\n candidate.close();\n } catch (Exception e) {\n }\n}\n</code></pre>\n\n<p>Use the runtime environmnt's support in favour of open coding, e.g. <code>Arrays.fill()</code> instead of iterating over array indices to assign to elements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T07:26:43.903",
"Id": "416411",
"Score": "0",
"body": "(Musing doing a full code review once the question supports reproduction of timing issues.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T07:25:45.750",
"Id": "416583",
"Score": "0",
"body": "***Guesses*** about causes for unsatisfactory speed: **1) Not creating initial runs of max. achievable size** (1st sentence of en.wikipedia's article…) **2)** Choice of algorithm. *Polyphase merge* looked a Good Idea when when your computing centre had nine tape drives (four fast, two of the sluggish not able to read backwards, two of the fast ones able to *write* backwards (and two dead ones for spares) - and at any given time, seven could be expected in working condition, but at most five available for data tapes of any single job of a mere mortal)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:06:24.980",
"Id": "416588",
"Score": "0",
"body": "Regarding 1): I am not sure if I understand what seems to be a problem with initial runs and their max. achievable size? I just distribute the runs following distribution array. Regarding 2): since I am comparing this algorithm with other external sorting algorithms, the choice is not really a question. I have applied your suggestion with closeables, will also change IO for NIO. Have you noticed any other issues in the code? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:43:02.520",
"Id": "416597",
"Score": "0",
"body": "**3)** using too few files **4)** using buffers no larger than the smallish default size. *(More) Things that justifying experimentation*: **a)** using unicode in temp files instead of en-/decoding time&again **b)** asynchronous I/O"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T09:16:05.920",
"Id": "416603",
"Score": "0",
"body": "`I just distribute the runs` detected in the input - which would be the thing to do in the *internal sort* algorithm *natural merge*. For an external merge, use the biggest PQ you can justify to create *initial runs* with an expected length about twice the capacity of that PQ, and proportionally fewer of those. (Say 1GB for a PQ of 9 char Strings - I'd expect runs of about 50E6 records, as opposed to 1.5 for \"natural\" - a factor of about 30E6. With an approximate reduction factor of 4.3 for a 20 file polyphase merge, that's almost 12 passes saved.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T09:48:18.370",
"Id": "416610",
"Score": "0",
"body": "I have measured the execution time with System.currentTimeMillis() & System.out.println(), no other code used. I will post the link from where you can download the input file or will try to find the generator. The files were generated some time ago."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:10:50.870",
"Id": "416677",
"Score": "0",
"body": "As promised here is the link to input file (cca 786MB txt file with random string distribution): https://drive.google.com/open?id=1W1AZjr5TGpDa0inbDQM_9s_vyPhEUXsT Change the working directory path and run the algorithm with 24 working files (on Linux or macOS). If you need any more info please let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T19:31:41.340",
"Id": "416718",
"Score": "0",
"body": "Regarding 3) and 4): 24 temporary files is a max I use in my comparison and default buffer size is used for all other algorithms. And by the way I do not use NIO with other algorithms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T09:13:38.710",
"Id": "417228",
"Score": "0",
"body": "(@henrich If a prospective follow-up is about performance, too, please invest more diligence in establishing a base line such that reviewers can decide for themselves they have reproduced the issue(s) and are in a position to improve the implementation. Such as *issue: merge unexpectedly slow compared to distribute* - provide timings for both!)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T07:25:17.590",
"Id": "215321",
"ParentId": "215295",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T19:58:29.737",
"Id": "215295",
"Score": "2",
"Tags": [
"java",
"performance",
"algorithm",
"mergesort"
],
"Title": "External polyphase merge sort"
} | 215295 |
<p>The user selects one of the three categories then makes a note on that selection. Then the note is appended and saved to the appropriate list.</p>
<p>It took me four hours to write this. I'm trying to learn and was wondering if this could be improved or cleaned up at all.</p>
<pre><code>#!/bin/bash
#get the date
date=$(date +%d-%B-%Y)
#save locations
wsave="${HOME}/worknotes.txt"
shsave="${HOME}/shoppingnotes.txt"
scsave="${HOME}/schoolnotes.txt"
#list
while [ true ]
do
read -p "What is this note for?
Work
School
Shopping
> " topic
case $topic in
"Work" )
read -p "
Note
> " wnote
echo "$date: $wnote" >> "$wsave"
echo "Note saved to $wsave"
break
;;
"Shopping" )
read -p "
Note
> " shnote
echo "$date: $shnote" >> "$shsave"
echo "Note saved to $shsave"
break
;;
"School" )
read -p "
Note
> " scnote
echo "$date: $scnote" >> "$scsave"
echo "Note saved to $scsave"
break
;;
*) echo "Error: Selection was not on list, try again.
"
;;
esac
done
</code></pre>
| [] | [
{
"body": "<p>Extract common code into a common block. You only need the <code>case</code> to determine the save-location. The note itself can be read before switching:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>#...\nread -p \"What is this note for?\nWork\nSchool\nShopping\n> \" topic\nread -p \"\nNote \n> \" note\nsave=\"\"\ncase $topic in\n \"Work\")\n save=$wsave\n break\n ;;\n \"School\")\n save=scsave\n break\n ;;\n \"Shopping\")\n save=$shsave\n break\n ;;\n *) echo \"Error: Selection was not on list, try again.\n\"\n ;;\nesac\nif [[ $save!=\"\" ]]; then\n echo \"$date: $note\" >> \"$save\"\n echo \"Note saved to $save\"\nfi\n#...\n</code></pre>\n\n<p>this removes the duplication in the case-blocks and still allows you to clearly work with what you expect for every note.</p>\n\n<hr>\n\n<p>The variable names could use a bit more... characters in general. You could even use snake_case to differentiate between words and all that. This allows you to make the code significantly more speaking.</p>\n\n<hr>\n\n<p>The comment <code>#list</code> is really not adding any value. <code>#get the date</code> is already clearly outlined by the code, maybe a more human readable format explanation might be useful there. <code>#save locations</code> should be completely replaceable with proper variable names.</p>\n\n<hr>\n\n<p>A word on the save locations you are using. As it stands, these are totally visible and will clutter the user's home directory. You should consider making these hidden by default by prefixing the filenames with a <code>.</code>, maybe even put them into a separate folder in the home-directory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T17:32:23.907",
"Id": "416529",
"Score": "0",
"body": "Thanks for the ideas! I would like it though if the note only saved after the user selected an option from the predefined list. With your code if the user misspelled a topic name there potentially long note wouldn't be saved, right? I agree the comments I make aren't very helpful. I made a separate directory for the notes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T21:52:04.827",
"Id": "215301",
"ParentId": "215297",
"Score": "4"
}
},
{
"body": "<p>A couple of points:</p>\n\n<ol>\n<li><p>You determine the date outside your loop, then loop forever. Every note you make after the first one is going to have the same date stamp.</p>\n\n<p>A better approach would be to collect the date stamp just as you are writing to the file:</p>\n\n<pre><code>datestamp=$(...)\necho \"$datestamp: $note\" >> ...\n</code></pre></li>\n<li><p>When shells were originally written, almost <em>everything</em> was a program. The <code>if</code> statement takes an executable as its conditional element. (If you look, you will find a program named <code>[</code> in <code>/bin</code> so that <code>if [ ...</code> will work.)</p>\n\n<p>There is a program named <code>true</code> and a program named <code>false</code>. You can run them, and they don't do anything except set their exit codes to appropriate values.</p>\n\n<p>You don't need to write <code>while [ true ]</code>. Instead, just write <code>while true</code>. This is important because <code>while false</code> will do something different from <code>while [ false ]</code>. You may be surprised ...</p></li>\n<li><p>As @Vogel612 points out, you have duplicated code. I think you should keep the user feedback close to the user entry, so your checking should happen before typing the note. You can use another variable to hold the destination file path:</p>\n\n<pre><code>read -p \"What is this note for?\nWork\nSchool\nShopping \n> \" topic\ndestfile=''\ncase $topic in\n \"Work\" ) destfile=\"$wsave\" ;;\n \"School\" ) destfile=\"$scsave\" ;;\n \"Shopping\" ) destfile=\"$shsave\" ;;\n * ) echo \"Error: Selection was not on list, try again.\\n\" ;;\nesac\n\nif [ \"$destfile\" ]; then \n read -p \"\\nNote\\n> \" note\n echo \"$date: $note\" >> \"$destfile\"\n echo \"Note saved to $destfile\"\nfi\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T18:35:44.920",
"Id": "416536",
"Score": "0",
"body": "Awesome, thanks! I added a quit option using a break command under shopping. I added a -e to the echo commands becuase the newlines weren't coming through. Read that printf is a subsitute, but that didn't display the way I wanted to. Moved the date variable to right before the ehco statement that calls it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T22:49:08.113",
"Id": "215305",
"ParentId": "215297",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "215305",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T20:57:13.470",
"Id": "215297",
"Score": "4",
"Tags": [
"beginner",
"bash",
"linux",
"shell"
],
"Title": "Append a note to one of three files based on user choice"
} | 215297 |
<p>This code below is what I think should be the implementation of merge sort in Python and it works as expected. It sorts the given list, where we can safely assume that all values are distinct. But after considering some online implementations I am doubtful about mine. So the base question is "Is this even Merge sort?".</p>
<pre><code>def merge(arr):
# base case
length = len(arr)
half = length//2
if length == 1 or length == 0:
return arr
# recursive case
firstHalf = merge(arr[:half]) # sort first half
secondHalf = merge(arr[half:]) # sort second half
length_firstHalf = len(firstHalf)
length_secondHalf = len(secondHalf)
sortedList = []
i, j = 0, 0 # variables for iteration
while i != length_firstHalf and j != length_secondHalf: # add elements into the new array until either of then two sub arrays is completely traversed
if firstHalf[i] > secondHalf[j]:
sortedList.append(secondHalf[j])
j += 1
continue
if firstHalf[i] < secondHalf[j]:
sortedList.append(firstHalf[i])
i += 1
return(sortedList + firstHalf[i:] + secondHalf[j:]) # return the array after adding whats left of sub array which wasnt completely traversed
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T21:06:56.127",
"Id": "416364",
"Score": "0",
"body": "@200_success thank you for the advice, the code is edited now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T21:10:38.900",
"Id": "416366",
"Score": "0",
"body": "@200_success now its okay i believe"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T21:17:46.180",
"Id": "416369",
"Score": "0",
"body": "@200_success thank you for editing. much better now"
}
] | [
{
"body": "<p>To address your immediate concern, yes it is a merge sort.</p>\n\n<ul>\n<li><p>The naming is quite unusual. The procedure you call <code>merge</code> does the merge sort, and should be called so. The <em>merge</em> phase of the merge sort is done by the</p>\n\n<pre><code> while i != length_firstHalf and j != length_secondHalf:\n</code></pre>\n\n<p>loop and the subsequent <code>return</code>. It is advisable to factor it out into a standalone <code>merge</code> procedure. OTOH I don't endorse a complicated return expressions.</p></li>\n<li><p>It is unclear why do you limit yourself to the distinct values. The second <code>if</code> clause may be safely made into an <code>else</code>, and there is no more worries. Notice that your first comparison <code>firstHalf[i] > secondHalf[j]</code> <em>is</em> the way to handle duplicates.</p></li>\n<li><p>Computing <code>half</code> doesn't belong to the base case.</p></li>\n<li><p>As a nitpick, <code>length == 1 or length == 0</code> is a long way to say <code>length < 2</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T05:04:07.877",
"Id": "416398",
"Score": "0",
"body": "Using distinct values was the requirement in the question that i was asked to solve. I think if I add this `if firstHalf[i] >= secondHalf[j]` then it can handle duplicate values."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T21:33:17.113",
"Id": "215300",
"ParentId": "215298",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215300",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T20:57:56.353",
"Id": "215298",
"Score": "3",
"Tags": [
"python",
"mergesort"
],
"Title": "Python merge sort for a list containing distinct values"
} | 215298 |
<p>I have code for a function to calculator the addition of two sorted List. Each element of List is tuple type (xi, yi) that represents graph individual (x,y) points at coordinate system.</p>
<blockquote>
<p>two input List is sorted by x value and length of A, B list may be different<br>
[(Ax0, Ay0),..., (Axi, Ayi), (Axi+1, Ayi+1),, ...(Axn, Ayn)]<br>[(Bx0, By0),..., (Bxi, Byi), (Bxi+1, Byi+1),, ...(Bxk, Byk)]<br></p>
</blockquote>
<pre><code>example 1:
A:[(1, 1]]=> one point: 1, at x coordinate, 0 at y coordinate
B:[(0, 0]]=> one point: 0, at x coordinate, 0 at y coordinate
=> graph_addition(A, B) == [(0,0), (1,1)]
a line with two point (0,0) and (1,1)
example 2:
A:[(3, 3), (5,5)]=> one line at (3,3), (5,5)
B:[(4, 4), (5, 5), (10, 8)]=> 2 segment line:
ex: graph_addition(A, B) = [(3, 3), (4, 8.0), (5, 10)]
3 segment line with 3 point [(3, 3), (4, 8.0), (5, 10), (10, 8)]
For A when x at 4, y should be 4 based on slope calculation
example 3:
A:[(3,3), (5,5), (6,3), (7,5)]
B:[(0,0), (2,2), (4,3), (5,3), (10,2)]
explanation
when x = 0 at B line, y=0, at A line y = 0 => (0, 0)
when x = 2 at B line, y=2, at A line y = 0 => (0, 0)
when x = 4 at B line, y=3, at A line y = (5-3 / 5-3 * 4) => (4, 7)
when x = 5 at B line, y=3, at A line y = 5 => (5, 8)
when x = 6 at B line, y= (2 - 3)/(10-5) * 6, at A line y = 3 => (6, 0)
when x = 7 at B line, y= (2 - 3)/(10-5) * 7, at A line y = 5 => (7, 1.5)
when x = 10 at B line, y=3, at A line y = (5-3 / 5-3 * 4) => (4, 7)
=> [(0, 0), (2, 2), (3, 5.5), (4, 7.0), (5, 8), (6, 5.8), (7, 7.6), (10, 2)]
</code></pre>
<p>Is there a better way for me to not using bruteforce way to calculate x, y values?</p>
<pre><code>def graph_addition(A, B):
if not A or not B: return A or B
res = []
i = j = 0
while i < len(A) and j < len(B):
if A[i][0] < B[0][0]:
x, y = A[i]
i += 1
elif B[j][0] < A[0][0]:
x, y = B[j]
j += 1
elif A[i][0] < B[j][0]:
x = A[i][0]
y = (B[j][1] - B[j - 1][1]) / (B[j][0] - B[j - 1][0]) * (x - B[j - 1][0]) + B[j - 1][1] + A[i][1]
i += 1
elif A[i][0] > B[j][0]:
x = B[j][0]
y = (A[i][1] - A[i - 1][1]) / (A[i][0] - A[i - 1][0]) * (x - A[i - 1][0]) + A[i - 1][1] + B[j][1]
j += 1
else:
x = A[i][0]
y = A[i][1] + B[j][1]
i += 1
j += 1
res.append((x, y))
if A[i:]: res += A[i:]
if B[j:]: res += B[j:]
return res
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T06:55:10.887",
"Id": "416408",
"Score": "4",
"body": "Hello @Alee. I do not understand the intended functionality from your brief description or example. Could you edit the question to include more detail?"
}
] | [
{
"body": "<ol>\n<li>Use <code>yield</code> instead of building a list. There is no need for an explicit list.</li>\n<li>At start of method <code>or</code> input with <code>[]</code> for cleaner <code>None</code> checks.</li>\n<li>Move interpolation into a function. This avoid repeated code.</li>\n<li>Move all the casework into the interpolation function.</li>\n</ol>\n\n<pre><code>def graph_value(L, i, x):\n if x == L[i][0]: return L[i][1]\n if i == 0: return 0\n m = (L[i][1] - L[i - 1][1]) / (L[i][0] - L[i - 1][0])\n return m * (x - L[i - 1][0]) + L[i - 1][1]\n\ndef graph_addition(A, B):\n A = A or []\n B = B or []\n i = j = 0\n while i < len(A) and j < len(B):\n x = min(A[i][0], B[j][0])\n y = graph_value(A, i, x) + graph_value(B, j, x)\n i += (x == A[i][0])\n j += (x == B[j][0])\n yield (x,y)\n yield from A[i:]\n yield from B[j:]\n</code></pre>\n\n<p>Exercise to the reader: write a version that takes in two arbitrary iterables and performs the same functionality.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T18:55:21.777",
"Id": "416537",
"Score": "0",
"body": "nice code. totally agree yield make the code more clean and any better way for not doing the math calculation you can think of?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:32:40.287",
"Id": "215354",
"ParentId": "215299",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T21:22:11.193",
"Id": "215299",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "Merge two sorted linear graphs"
} | 215299 |
<p>I created a program in python that reads a file and outputs a frequency graph of the words it contains. Any feedback or tips would be appreciated. </p>
<pre><code>from re import split
from collections import Counter
size = int(input("Output window size(in chars): "))
with open("text.txt", "r") as f:
words = [w for w in split(r"[\W_\d]+", f.read().strip()) if w]
if not words:
print("Put some text in `text.txt`!")
quit()
word_count = Counter(words)
top_words = sorted(word_count.keys(), key = lambda w : word_count[w], reverse = True)
scale = (size - len(max(top_words, key = len))) / word_count[top_words[0]]
for word in top_words[:10]:
print("-" * (int(word_count[word] * scale) - 2) + "| " + word)
</code></pre>
| [] | [
{
"body": "<h2>Review</h2>\n<ul>\n<li><p>The Python style guide <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">[PEP8]</a> advises to use 4 space indentation</p>\n</li>\n<li><p>You don't have to sort the words</p>\n<p><code>Counter</code> has some features that allow you to get the most common occurrences, aptly named <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter.most_common\" rel=\"nofollow noreferrer\">most_common()</a></p>\n</li>\n<li><p>String formatting is cleaner vs manual string appending</p>\n<p>Instead of manually concatenating use <code>str.format()</code> or even <code>f"{string}"</code> with Python3.6+</p>\n</li>\n</ul>\n<h2>Code</h2>\n<p>Using these additions we can rewrite your last code block into:</p>\n<pre><code>word_count = Counter(words)\nscale = (size - max(map(len, word_count))) / word_count.most_common(1)[0][1]\nfor word, occurence in word_count.most_common(10):\n print("{}| {}".format("-" * int(occurence * scale - 2), word))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:08:05.417",
"Id": "416439",
"Score": "1",
"body": "Wouldn't `max(len(word) for word in word_count)` or `max(map(len, word_count))` be a lot easier than calling `max` with `len` as the key and then calling `len` on it again?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:09:32.053",
"Id": "416441",
"Score": "1",
"body": "Ohh I like `max(map(len, word_count))` didn't cross my mind to write it this way!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T14:09:30.540",
"Id": "416494",
"Score": "1",
"body": "You want to scale to the longest word in top ten, not the longest word in the whole corpus. Also `.most_common` is presumably \\$O(n)\\$ in the number of unique words; it would be better to retrieve the top ten once and take the top one from there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:40:28.990",
"Id": "416508",
"Score": "0",
"body": "@OhMyGoodness \"You want to scale to the longest word in top ten, not the longest word in the whole corpus\" **I agree**, but this is not done by OP. It leaves me guessing at their intentions, and I didn't want to deviate from OP's code behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T18:07:17.743",
"Id": "416535",
"Score": "0",
"body": "@Ludisposed OP's code is `len(max(top_words, key = len)))` and it selects longest length from within `top_words`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T20:20:21.713",
"Id": "416555",
"Score": "0",
"body": "@OhMyGoodness `top_words` is all the words. Don't get me wrong I agree it is probably what OP intended but not wrote"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:00:06.023",
"Id": "215334",
"ParentId": "215307",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "215334",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T23:05:44.713",
"Id": "215307",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"strings",
"ascii-art",
"data-visualization"
],
"Title": "Word count graph"
} | 215307 |
<p>The following code attempts to implement <code>memset_s()</code> based on <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf#%5B%7B%22num%22%3A1353%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C0%2C792%2C0%5D" rel="nofollow noreferrer">section K.3.7.4.1 of the ISO/IEC 9899:201x N1570 draft</a>:</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdint.h>
errno_t memset_s(void *s,rsize_t smax, int c, rsize_t n)
{
errno_t violation_present = 0;
volatile unsigned char * v = s;
if ( s == NULL )
{
fprintf(stderr,"memset_s: Error: void * s == NULL!\n");
return 1;
}
if ( n > RSIZE_MAX )
{
fprintf(stderr,"memset_s: Warning: rsize_t n > RSIZE_MAX!\n");
violation_present = 1;
}
if ( n > smax )
{
fprintf(stderr,"memset_s: Warning: rsize_t n > rsize_t smax!\n");
violation_present = 1;
}
if ( smax > RSIZE_MAX )
{
fprintf(stderr,"memset_s: Error: rsize_t smax > RSIZE_MAX!\n");
return 1;
}
volatile unsigned char * v_p = &v[0];
rsize_t i = 0;
if ( violation_present == 1 ) // && (s != NULL) && (smax <= RSIZE_MAX) )
{
i = 0;
while ( i < smax )
{
*v_p++ = (unsigned char)c;
i++;
}
return violation_present;
}
else // no runtime-constraint violation found
{
i = 0;
while ( i < n )
{
*v_p++ = (unsigned char)c;
i++;
}
return violation_present;
}
}
</code></pre>
<p>I have also made a C source test file for <code>memset_s()</code>:</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define ARRAY_SIZE 8
typedef struct Node
{
struct Node * link;
int val;
} Node;
int main(void)
{
errno_t result = 0;
printf("This program only checks for runtime-constraint\n"
"violations in an invocation of memset_s.\n\n"
);
static char test[ARRAY_SIZE];
printf("Does memset_s return nonzero value when void * s"
" == NULL?\n\n"
);
result = memset_s(NULL,sizeof(test),0,sizeof(test));
printf("Return Value: %llu\n\n",result);
printf("Does memset_s return nonzero value when smax >"
" RSIZE_MAX?\n\n"
);
result = memset_s(test,RSIZE_MAX+1,0,sizeof(test));
printf("Return Value: %llu\n\n",result);
printf("Does memset_s set the inputted char value into\n"
"each of the first smax characters of the object\n"
"pointed to by void *s only when there is a\n"
"violation and void * s != NULl and when rsize_t\n"
"smax is less than or equal to RSIZE_MAX and return\n"
"nonzero value?\n\n"
);
result = memset_s(test,8*sizeof(char),84,RSIZE_MAX+1);
printf("Return Value: %llu\n\n",result);
printf("test string set with memset_s:\n%s\n",test);
for ( rsize_t i = 0; i < ARRAY_SIZE; i++)
{
test[i] = '\0';
}
printf("Does memset_s correctly set the inputted char value\n"
"into each of the first n characters of the object\n"
"pointed to by void *s when there is NO runtime\n"
"constraint violation?\n\n"
);
result = memset_s(test,8*sizeof(char),84,4*sizeof(char));
printf("Return Value: %llu\n\n",result);
printf("test string set with memset_s for first four char\n"
"elements in a char array of 8 elements:\n%s\n\n",
test
);
printf("Does memset_s only set the first smax values when\n"
"rsize_t n > rsize_t smax?\n\n"
);
for ( rsize_t i = 0; i < ARRAY_SIZE; i++)
{
test[i] = '\0';
}
result = memset_s(test,8*sizeof(char),84,8*sizeof(char)+1);
printf("Return Value: %llu\n\n",result);
printf("test string below:\n%s\n\n",
test
);
printf("Does memset_s correctly allocate unsigned chars to objects\n"
"that in turn, store other objects, like a struct?\n"
"In the example below, a struct Node of a Linked List\n"
"is initialized through memset_s\n\n"
);
Node * node;
result = memset_s(node,sizeof(Node),0,sizeof(Node));
printf("Return Value: %llu\n\n",result);
printf("node->link == %p\n",node->link);
printf("node->val == %d\n\n",node->val);
printf("Does memset_s do what was tested previously except that\n"
"it initializes with a nonzero unsigned char value? In the\n"
"example below, a second struct Node name node_two is\n"
"initialized with the unsigned char value 84\n\n"
);
Node * node_two;
Node * node_three;
result = memset_s(node_two,sizeof(Node),84,sizeof(Node));
printf("Return Value: %llu\n\n",result);
printf("node_two->link == %p\n",node_two->link);
printf("node_two->val == %d\n\n",node_two->val);
printf("node_two->val in Hexadecimal format == 0x%x\n\n",node_two->val);
return 0;
}
</code></pre>
<p>My only concern is that I forgot to find a security flaw in my implementation of <code>memset_s()</code>. Did I forget to test for any values?</p>
<p>I plan to use <code>memset_s()</code> in <a href="https://raw.githubusercontent.com/tanveerasalim/SSL-TLS/master/ch1/my_http_c11.c" rel="nofollow noreferrer">my implementation</a> of http.c from the book "<em>Implementing SSL/TLS Using Cryptography and PKI</em>" by Joshua Davies.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T09:43:17.013",
"Id": "416436",
"Score": "0",
"body": "Is this actually meant to be [tag:c99] code to implement a [tag:c11] feature? With appropriate definitions of `rsize_t`, `errno_t` and `RSIZE_MAX`, it compiles fine as C99, so perhaps that's the tag that makes more sense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:24:35.627",
"Id": "416488",
"Score": "1",
"body": "You are aware that the optional Annex K is largely seen as politically motivated and a serious misstep? See [the tag-wiki on SO](https://stackoverflow.com/tags/tr24731/info) and questions under it."
}
] | [
{
"body": "<pre><code>errno_t memset_s(void *s,rsize_t smax, int c, rsize_t n)\n</code></pre>\n\n<p>You've got a missing space after that first comma. (Sure, inconsistent whitespace doesn't affect functionality; but like any spelling mistake, it indicates that you haven't proofread your code. Which means it <em>probably</em> has some other one-character typos too. Some of which <em>might</em> affect functionality. Always read your code after writing it!)</p>\n\n<p>The typedef <code>errno_t</code> is invariably <code>int</code>. So personally I'd just write <code>int</code> — unless you were planning to use the association with <code>errno</code> in some significant way. Right now your code just returns <code>0</code> on success and <code>1</code> (which is to say <code>EPERM</code>) on failure. Consider whether <code>memset_s</code> should return a more specific and helpful errno than simply <code>EPERM</code>. For example, maybe if you pass NULL to it, you should get back <code>EINVAL</code> \"Invalid argument\"?</p>\n\n<p>However, at the same time, <a href=\"https://martinfowler.com/bliki/Yagni.html\" rel=\"nofollow noreferrer\">YAGNI</a> — it may be counterproductive to spend a lot of time agonizing over what are the proper errno return values, unless you have an actual use-case for these return values. The only reason to return <code>EINVAL</code> for a null argument instead of the generic <code>EPERM</code> is that it enables a caller to detect that specific error case and handle the error accordingly. <em>But the caller can already detect that case!</em> The caller doesn't need your help to detect <code>s == NULL</code>! The caller controls the value of <code>s</code> in the first place, and can easily check for null beforehand, if they think it's possible for <code>s</code> to be null. (And if it's <em>not</em> possible for <code>s</code> to be null, then there's no point checking inside <code>memset_s</code> either. That's just a waste of CPU cycles.)</p>\n\n<p>Can you tell that I think <code>memset_s</code> is largely a waste of time, design-wise? :)</p>\n\n<hr>\n\n<p>I find your chain of <code>if</code>s difficult to match up to the specification. The specification is as follows:</p>\n\n<blockquote>\n <p><strong>Runtime-constraints:</strong> <code>s</code> shall not be a null pointer. Neither <code>smax</code> nor <code>n</code> shall be greater than <code>RSIZE_MAX</code>. <code>n</code> shall not be greater than <code>smax</code>.</p>\n \n <p>If there is a runtime-constraint violation, then if <code>s</code> is not a null pointer and <code>smax</code> is not greater than <code>RSIZE_MAX</code>, the <code>memset_s</code> function stores the value of <code>c</code> (converted to an <code>unsigned char</code>) into each of the first <code>smax</code> characters of the object pointed to by <code>s</code>.</p>\n \n <p><strong>Description:</strong> The <code>memset_s</code> function copies the value of <code>c</code> (converted to an <code>unsigned char</code>) into each of the first <code>n</code> characters of the object pointed to by <code>s</code>.</p>\n</blockquote>\n\n<p>So I would naturally implement it something like this:</p>\n\n<pre><code>errno_t memset_s(void *s, rsize_t smax, int c, rsize_t n) {\n bool violation = (s == NULL) || (smax > RSIZE_MAX) || (n > RSIZE_MAX) || (n > smax);\n if (violation) {\n if ((s != NULL) && !(smax > RSIZE_MAX)) {\n for (rsize_t i = 0; i < smax; ++i) {\n ((volatile unsigned char*)s)[i] = c;\n }\n }\n return EPERM;\n } else {\n for (rsize_t i = 0; i < n; ++i) {\n ((volatile unsigned char*)s)[i] = c;\n }\n return 0;\n }\n}\n</code></pre>\n\n<p>That seems to implement the specification 100% correctly, line for line.</p>\n\n<p>You write the second <code>for</code>-loop above as</p>\n\n<pre><code> i = 0;\n\n\n while ( i < n )\n {\n *v_p++ = (unsigned char)c;\n\n i++;\n }\n</code></pre>\n\n<p>(yes, with <em>two</em> blank lines between the <code>i = 0</code> and the rest of the loop). That's definitely too much code for a simple <code>for</code>-loop. Even without doing anything else to your code, you could replace those 9 lines with 3 lines:</p>\n\n<pre><code> for (int i = 0; i < n; ++i) {\n *v_p++ = (unsigned char)c;\n }\n</code></pre>\n\n<p>A 66% reduction in lines-of-code is not bad for a day's work!</p>\n\n<hr>\n\n<pre><code>volatile unsigned char * v = s;\n// ...\nvolatile unsigned char * v_p = &v[0];\n</code></pre>\n\n<p>You know that <code>&v[0]</code> is the same thing as <code>v</code>, right?</p>\n\n<hr>\n\n<pre><code>rsize_t i = 0;\n\nif ( violation_present == 1 ) // && (s != NULL) && (smax <= RSIZE_MAX) )\n{\n\n i = 0;\n</code></pre>\n\n<p>Three things:</p>\n\n<ul>\n<li><p>You initialize <code>i</code> to <code>0</code>, and then <em>again</em> initialize it to <code>0</code>. Are you worried that the first initialization might not have taken? :)</p></li>\n<li><p>The commented-out code is confusing. (I left a comment on the question referring to this and some other commented-out code; you did remove some of it, but left this snippet commented out.) If you meant for this code to take effect, you should uncomment it. If you meant for this code <em>not</em> to take effect, you should just delete it. Don't leave commented-out code hanging around. (If it's for historical interest, you should learn <code>git</code> or some other version-control system.)</p></li>\n<li><p>You branch on if <code>violation_present == 1</code>. This suggests that <code>violation_present</code> might take on other values, such as <code>0</code> (which it does) or <code>2</code> or <code>42</code> (which it does not). The compiler will likely generate code to compare <code>violation_present</code> against the constant <code>1</code>. But actually all you mean here is \"If there's a violation present...\", which is idiomatically expressed as <code>if (violation_present) ...</code>. Furthermore, you should look up the <code>bool</code> type (defined in <code><stdbool.h></code>) — it's tailor-made for boolean variables that can only ever take on the value <code>true</code> or <code>false</code>. (Notice the use of <code>bool</code> in my reference implementation above.)</p></li>\n</ul>\n\n<hr>\n\n<pre><code>fprintf(stderr,\"memset_s: Error: void * s == NULL!\\n\");\n</code></pre>\n\n<p>Missing whitespace again.</p>\n\n<p>Here you have a <code>memset_s</code> function, whose job is to set a range of bytes to a value... and you've got it pulling in <code>fprintf</code> from the standard library! Does that seem appropriate to you?</p>\n\n<p><code>memset_s</code> is a very low-level function. It should be usable even on embedded systems that have never heard of <code>fprintf</code> or <code>stderr</code>. You should find a way to report errors that doesn't involve <code><stdio.h></code>. (Might I suggest <code>errno_t</code>? :))</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T02:40:29.713",
"Id": "416759",
"Score": "0",
"body": "\" it indicates that you haven't proofread your code.\" --> indicates an auto formatter was not used. Better to auto-format that spend valuable time manual formating."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T02:41:23.827",
"Id": "416760",
"Score": "1",
"body": "\"you should get back EINVAL\" --> `EINVAL, EPERM` are not specified in the C spec."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T02:37:54.120",
"Id": "215314",
"ParentId": "215309",
"Score": "3"
}
},
{
"body": "<h1>Warning messages</h1>\n<p>When we print fixed strings, it's better to use plain <code>fputs()</code> rather than the much more complex <code>fprintf()</code>.</p>\n<p>However, in this case, the diagnostic output should be removed: such side-effects are not part of the contract of <code>memset_s()</code>, and are actively harmful (because the whole point of the checks is to report errors to the calling program, which <em>knows better than the library</em> what a user needs to be told).</p>\n<h1>Don't write <code>for</code> loops as <code>while</code></h1>\n<p>Either</p>\n<pre><code> for (rsize_t i = 0u; i < smax; ++i)\n {\n *v++ = (unsigned char)c;\n }\n</code></pre>\n<p>or</p>\n<pre><code> while (smax-- > 0)\n {\n *v++ = (unsigned char)c;\n }\n</code></pre>\n<p>(I removed the unnecessary <code>v_p</code> variable).</p>\n<h1>Unnecessary duplication</h1>\n<p>Instead of writing the loop twice, we can simply adjust <code>n</code>:</p>\n<pre><code>if ( n > smax )\n{\n n = smax;\n violation_present = EINVAL;\n}\n</code></pre>\n<p>This gives us an improved and much shorter <code>memset_s()</code>:</p>\n<pre><code>#include <errno.h>\n#include <stdint.h>\n#include <string.h>\n\nerrno_t memset_s(void *s, rsize_t smax, int c, rsize_t n)\n{ \n if (!s || smax > RSIZE_MAX) {\n return EINVAL;\n }\n\n errno_t violation_present = 0;\n if (n > smax) {\n n = smax;\n violation_present = EINVAL;\n }\n\n volatile unsigned char *v = s;\n for (rsize_t i = 0u; i < n; ++i) {\n *v++ = (unsigned char)c;\n }\n\n return violation_present;\n}\n</code></pre>\n<p>Alternatively, re-entering the function instead of tracking <code>violation_present</code>:</p>\n<pre><code>errno_t memset_s(void *s, rsize_t smax, int c, rsize_t n)\n{\n if (!s || smax > RSIZE_MAX) {\n return EINVAL;\n }\n\n if (n > smax) {\n memset_s(s, smax, c, smax);\n return EINVAL;\n }\n\n volatile unsigned char *v = s;\n for (rsize_t i = 0u; i < n; ++i) {\n *v++ = (unsigned char)c;\n }\n\n return 0;\n}\n</code></pre>\n<h1>Constraint handlers</h1>\n<p>I'm going to assume that the lack of support for constraint handlers (<a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf#%5B%7B%22num%22%3A1319%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C0%2C792%2C0%5D\" rel=\"nofollow noreferrer\">section K.3.6.1</a>) is intentional, and that you don't intend to set a constraint handler in your calling code.</p>\n<hr />\n<h1>Test program</h1>\n<p>It's a serious error to format <code>errno_t</code> values (which are <code>int</code> according to the definition) as if they were <code>long long unsigned int</code>. All those <code>%llu</code> must be changed to <code>%d</code> or <code>%i</code>.</p>\n<p>The pointer values printed using <code>%p</code> format need to be cast to <code>void*</code> (remember, a varargs function has no way of passing other pointer types).</p>\n<p><code>sizeof (char)</code> is one by definition, since the result is in units of <code>char</code>.</p>\n<p>The most serious problem is that <code>node</code> and <code>node_two</code> are used without initializing them to anything. This causes a crash for me, but if you're unlucky you might get a program that runs successfully. Suitable compiler warnings should alert you to this problem (and the format string mismatches I mentioned).</p>\n<p>The test program should be self-checking: instead of producing a stream of output that must be inspected, report only the failures, and use the exit status to indicate whether the entire test was successful.</p>\n<p>Here's a version that does that:</p>\n<pre><code>#include <stdio.h>\n#include <stdint.h>\n\n/* returns error count: 0 on success and 1 on failure */\nint test_memset(const char *message, const char *file, unsigned int line,\n errno_t expected,\n void *s, rsize_t smax, int c, rsize_t n)\n{\n if (memset_s(s, smax, c, n) == expected) {\n return 0;\n }\n fprintf(stderr, "%s:%u: %s\\n", file, line, message);\n return 1;\n}\n\n\nint main(void)\n{\n char test[8] = "abcdefgh";\n int error_count = 0;\n\n error_count += test_memset("s==NULL should return error", __FILE__, __LINE__, EINVAL,\n NULL, sizeof test, 0, sizeof test);\n\n#if RSIZE_MAX+1 > RSIZE_MAX\n error_count += test_memset("smax > RSIZE_MAX should return error", __FILE__, __LINE__, EINVAL,\n test, RSIZE_MAX+1, 0, sizeof test);\n\n /* should still have cleared the data */\n for (size_t i = 0; i < sizeof test; ++i) {\n if (test[i] == '\\0') {\n fputs("smax > RSIZE_MAX prevent writing\\n", stderr);\n ++error_count;\n break;\n }\n }\n#endif /* else, RSIZE_MAX==SIZE_MAX, and no caller can provide an out-of-range value */\n\n\n error_count += test_memset("When runtime constraints satisfied, should return success", __FILE__, __LINE__, 0,\n test, sizeof test, '*', 4);\n\n /* should have written the first 4 chars */\n for (size_t i = 0; i < 4; ++i) {\n if (test[i] != '*') {\n fprintf(stderr, "%s:%u: Should have written * at position %zu\\n", __FILE__, __LINE__, i);\n ++error_count;\n break;\n }\n }\n\n /* should not have written after the first 4 chars */\n for (size_t i = 4; i < sizeof test; ++i) {\n if (test[i] == '*') {\n fprintf(stderr, "%s:%u: Should not have written '%c' at position %zu\\n", __FILE__, __LINE__, test[i], i);\n ++error_count;\n break;\n }\n }\n\n memset(test, '\\0', sizeof test);\n\n error_count += test_memset("n > smax should set first smax chars and return error", __FILE__, __LINE__, EINVAL,\n test, 4, '*', 8);\n\n /* should have written the first 4 chars */\n for (size_t i = 0; i < 4; ++i) {\n if (test[i] != '*') {\n fprintf(stderr, "%s:%u: Should have written * at position %zu\\n", __FILE__, __LINE__, i);\n ++error_count;\n break;\n }\n }\n\n /* should not have written after the first 4 chars */\n for (size_t i = 4; i < sizeof test; ++i) {\n if (test[i]) {\n fprintf(stderr, "%s:%u: Should not have written '%c' at position %zu\\n", __FILE__, __LINE__, test[i], i);\n ++error_count;\n break;\n }\n }\n\n return error_count;\n}\n</code></pre>\n<p>I took out the tests that had dangling <code>Node</code> pointers; it wasn't clear what they are supposed to achieve.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T11:39:43.153",
"Id": "416465",
"Score": "0",
"body": "I haven't mentioned anything here about performance in this review - it's probably sufficient to say that better implementations don't use a char-by-char loop like that, but write in chunks of the platform's largest addressable units as much as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T23:32:49.400",
"Id": "416561",
"Score": "0",
"body": "Well Toby, I think your while loop fix for copy data and ideas for program testing are indeed correct!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:34:51.677",
"Id": "416596",
"Score": "0",
"body": "@Tanveer - I made a serious oversight: `n > RSIZE_MAX `shouldn't inhibit writing if `s` and `smax` are both valid. See latest edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T02:17:39.313",
"Id": "416757",
"Score": "0",
"body": "\"it's better to use plain fputs() rather than the much more complex fprintf().\" --> is of reduced value as good compilers will analyze known functions and emit efficient code either way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T02:31:39.857",
"Id": "416758",
"Score": "1",
"body": "`RSIZE_MAX+1` could be 0 and render the test ineffective."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T02:59:27.930",
"Id": "416761",
"Score": "1",
"body": "`EINVAL` is not in the C spec. Could do something like `#ifdef EINVAL #define my_EINVAL #else #define my_EINVAL 1` and return that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T03:01:42.037",
"Id": "416762",
"Score": "0",
"body": "Answer well uses `volatile`, yet I did not see \"why\" explained."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T08:28:16.947",
"Id": "416778",
"Score": "0",
"body": "@chux - no need to explain why the `volatile` is important, since it was perfectly fine in the original code. I suppose it could have been worth a brief \"this is good\" comment, but I was focusing more on what could be improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T08:36:09.283",
"Id": "416782",
"Score": "0",
"body": "`RSIZE_MAX+1` can indeed be zero, although \"*For implementations targeting machines with large address spaces,\nit is recommended that\n`RSIZE_MAX`\nbe defined as the smaller of the size of the largest\nobject supported or\n`(SIZE_MAX >> 1)`*\". We can conditionalize that test. Plain `fputs()` is still a good habit for fixed strings - it means we don't need to look for embedded `%` characters and/or write a `\"%s\"` format string."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T11:35:12.997",
"Id": "215345",
"ParentId": "215309",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215345",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T23:34:25.167",
"Id": "215309",
"Score": "5",
"Tags": [
"c",
"memory-management",
"c11"
],
"Title": "Implementation of memset_s based on C11 standard"
} | 215309 |
<p>This program allows users to create and log into their account. The database is created using SQLite3 and the GUI is just simple tkinter boxes. I just want to know how to improve my code, organise it, make it more efficient.</p>
<pre><code>import sqlite3
from tkinter import ttk
import tkinter
from tkinter import messagebox
with sqlite3.connect("User.db") as db:
cursor = db.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS user (
userID INTEGER PRIMARY KEY,
username VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL
)""")
def login(usernameLogin, passwordLogin):
while True:
username = usernameLogin.get()#Asks for username
password = passwordLogin.get()#Asks for password
with sqlite3.connect("User.db") as db:#Creates a connection to database
c = db.cursor()
find_user = ("SELECT * FROM user WHERE username = ? AND password = ?")#Validates inputs for account
c.execute(find_user,[(username),(password)])
results = c.fetchall()#Fetches values from database
if results:#Validates if the username/password is recognised
for i in results:
messagebox.showinfo("", "Welcome "+i[1]+"!")
break
else:
messagebox.showinfo("", "Password and username is not recognised")
break
def newUser(username1, password1):
found = 0
while found == 0:
username = username1.get()
with sqlite3.connect("User.db") as db:
c = db.cursor()
findUser = ("SELECT * FROM user WHERE username = ?")
c.execute(findUser, [(username)])#Checks existence of username in database
if c.fetchall():
messagebox.showinfo("Username", "Username taken please try again.")
break
else:
messagebox.showinfo("", "Account has been created!")
found = 1
password = password1.get()
insertData = '''INSERT INTO user(username, password)
VALUES(?,?)'''#Inserts new account into databse
c.execute(insertData, [(username),(password)])
db.commit()
def newUserTkinter():
window = tkinter.Tk()
window.title("Create new account")
labelOne = ttk.Label(window, text = "Enter a username:")
labelOne.grid(row = 0, column = 0)
username1 = tkinter.StringVar(window)#value type is classified as a string
usernameEntry = ttk.Entry(window, width = 30, textvariable = username1)
usernameEntry.grid(row = 1, column = 0)
labelTwo = ttk.Label(window, text = "Enter a password:")
labelTwo.grid(row = 2, column = 0)
password1 = tkinter.StringVar(window)#value type is classified as a string
passwordEntry = ttk.Entry(window, width = 30, textvariable = password1)
passwordEntry.grid(row = 3, column = 0)
btn = ttk.Button(window, text="Submit", command=lambda: newUser(username1, password1))
btn.grid(row = 3, column = 1)
def menu():
with sqlite3.connect("User.db") as db:
c = db.cursor()
c.execute("SELECT * FROM user")
print(c.fetchall())
window = tkinter.Tk()
window.title("Treasure Hunt Game!")
labelOne = ttk.Label(window, text = """ ~~~~~~~~~~~~~ USER MENU ~~~~~~~~~~~~~
""")#label displays instruction
labelOne.grid(row = 0, column = 0)#places label in a grid
btn = ttk.Button(window, text = "Create account", command = newUserTkinter)
btn.grid(row = 1, column = 0)#places button in a grid
labelTwo = ttk.Label(window, text = "Login to your account:")
labelTwo.grid(row = 2, column = 0)
usernameLogin = tkinter.StringVar(window)#value type is classified as a string
usernameEntry = ttk.Entry(window, width = 30, textvariable = usernameLogin)
usernameEntry.grid(row = 4, column = 0)
labelTwo = ttk.Label(window, text = "Username")
labelTwo.grid(row = 3, column = 0)
passwordLogin = tkinter.StringVar(window)#value type is classified as a string
passwordEntry = ttk.Entry(window, width = 30, textvariable = passwordLogin)
passwordEntry.grid(row = 6, column = 0)
labelTwo = ttk.Label(window, text = "Password")
labelTwo.grid(row = 5, column = 0)
btn = ttk.Button(window, text="Submit", command=lambda: login(usernameLogin, passwordLogin))
btn.grid(row = 6, column = 1)
menu()
</code></pre>
| [] | [
{
"body": "<h2>Review</h2>\n\n<ul>\n<li><p>Read PEP8 the python style guide, you have some style issues</p>\n\n<ol>\n<li>functions and variables should be <code>snake_case</code></li>\n<li>Group your imports</li>\n</ol></li>\n<li><p>You can import multiple items from the same module on 1 line => <code>from x import y, z</code></p></li>\n<li><p>Some comments are irrelevant and only add noise to the code</p>\n\n<p><code>username = usernameLogin.get()#Asks for username</code></p>\n\n<p>This line is perfectly self-explanatory and there is no need for that comment</p></li>\n<li><p>Secondly I find <code>code#commentblock</code> hard to read</p>\n\n<p>Instead I would add a docstring, or at least put the comment above the code for clarity</p></li>\n<li><p>As you do with the <code>connection</code> you can use the <code>cursor</code> as a <a href=\"https://docs.python.org/3/library/sqlite3.html#using-the-connection-as-a-context-manager\" rel=\"nofollow noreferrer\">context manager</a></p></li>\n</ul>\n\n<h2>Hashing</h2>\n\n<p>When handling passwords you should <em>at least</em> <a href=\"https://docs.python.org/3/library/hashlib.html\" rel=\"nofollow noreferrer\">hash</a> them,</p>\n\n<p>preferably with a well tested hashing algorithm such as <a href=\"https://pypi.org/project/bcrypt/\" rel=\"nofollow noreferrer\">bcrypt</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T09:11:40.843",
"Id": "215332",
"ParentId": "215310",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T23:51:27.103",
"Id": "215310",
"Score": "2",
"Tags": [
"python",
"tkinter",
"sqlite"
],
"Title": "SQLite3 account creator"
} | 215310 |
<p>So the problem of verifying if a list is a subsequence of another came up in a discussion, and I wrote code that seems to work (I haven't rigorously tested it). </p>
<p><strong>IsSubequence.py</strong> </p>
<pre class="lang-py prettyprint-override"><code>def is_subsequence(lst1, lst2):
"""
* Finds if a list is a subsequence of another.
* Params:
* `lst1` (`list`): The candidate subsequence.
* `lst2` (`list`): The parent list.
* Return:
* (`bool`): A boolean variable indicating whether `lst1` is a subsequence of `lst2`.
"""
l1, l2 = len(lst1), len(lst2)
if l1 > l2: #`l1` must be <= `l2` for `lst1` to be a subsequence of `lst2`.
return False
i = j = 0
d1, d2 = l1, l2
while i < l1 and j < l2:
while lst1[i] != lst2[j]:
j += 1
d2 -= 1
if d1 > d2: #At this point, `lst1` cannot a subsequence of `lst2`.
return False
i, j, d1, d2 = i+1, j+1, d1-1, d2-1
if d1 > d2:
return False
return True
</code></pre>
<p>I'm primarily concerned about performance. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T00:01:36.683",
"Id": "416564",
"Score": "0",
"body": "Specify what do you mean by \"subsequence\". Is `[1,1]` a subsequence of `[1,0,1]`? According to your code, it is. If you only want to consider continuous subsequences (eg. `[1,1]` is _not_ a subsequence of `[1,0,1]`), you can use a [string matching algorithm](https://en.wikipedia.org/wiki/String-searching_algorithm#Single-pattern_algorithms). The items of the two lists can be viewed as characters of two strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:56:11.920",
"Id": "416839",
"Score": "0",
"body": "`[1, 1]` is supposed to be a subsequence of `[1, 0, 1]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:42:51.860",
"Id": "416873",
"Score": "0",
"body": "In that case, the complexity of your code is optimal. Some optimizations are admissible in specific cases, such as when repeatedly checking the same haystack. Then you might do some preprocessing and save the result, to be able to quickly check whether the needle can possibly be a subsequence or not. For example, make a set of elements of the haystack, and when the needle contains an element which is not in the set, it cannot be a subsequence of the haystack. This would be especially helpful if the haystack is long but contains few unique elements (many repeated elements)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T07:26:12.043",
"Id": "416993",
"Score": "0",
"body": "Aah, thanks for the suggestion."
}
] | [
{
"body": "<h1>Review</h1>\n\n<ul>\n<li><p>Testing</p>\n\n<blockquote>\n <p>(I haven't rigorously tested it).</p>\n</blockquote>\n\n<p>Well you should write some test to ensure validity of the function. So even after changes you can be sure it will still work. <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\"><code>doctest</code></a> is a pretty nice module to use, and is a nice extension of your docstring</p></li>\n<li><p>Naming</p>\n\n<p>Variables should have descriptive names!</p>\n\n<p><code>lst1</code>, <code>lst2</code> if it wasn't for that docstring I would not have known what is the subseq and the parent, so instead I propose to rename them to <code>needle</code> and <code>haystack</code> here the intent is more clear</p>\n\n<p>Same goes for <code>d1</code>, <code>d2</code>... I can see that they are the remaining length of the list, but it is hard to tell from the variable name.</p></li>\n<li><p><code>for</code> is considered more Pythonic vs <code>while</code></p>\n\n<p>For loops are Pythons greatest feature IMHO, they are easy to read and short to write</p>\n\n<p>You should start writing for loops instead of a while, \"Loop like a native\" might be an interesting talk to view</p></li>\n<li><p>Too many assignments in a line</p>\n\n<p>Might be preference, but I find this line hard to read:</p>\n\n<p><code>i, j, d1, d2 = i+1, j+1, d1-1, d2-1</code> </p>\n\n<p>There are too many values with not enough descriptive names on this line</p></li>\n</ul>\n\n<h1>Alternative</h1>\n\n<p>We can instead loop over the <code>haystack</code> and use slicing to compare the sliced <code>haystack</code> with the <code>needle</code>, lastly top it off with the <code>any</code> keyword and write some tests with the doctest module</p>\n\n<pre><code>import doctest\n\ndef is_subsequence(needle, haystack):\n \"\"\"\n Finds if a list is a subsequence of another.\n\n * args\n needle: the candidate subsequence\n haystack: the parent list\n\n * returns\n boolean\n\n >>> is_subsequence([1, 2, 3, 4], [1, 2, 3, 4, 5, 6])\n True\n >>> is_subsequence([1, 2, 3, 4], [1, 2, 3, 5, 6])\n False\n >>> is_subsequence([6], [1, 2, 3, 5, 6])\n True\n >>> is_subsequence([5, 6], [1, 2, 3, 5, 6])\n True\n >>> is_subsequence([[5, 6], 7], [1, 2, 3, [5, 6], 7])\n True\n >>> is_subsequence([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, [5, 6], 7])\n False\n \"\"\"\n return any(\n haystack[i:i+len(needle)] == needle\n for i in range(len(haystack) - len(needle) + 1)\n )\n\nif __name__ == '__main__':\n doctest.testmod()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T14:03:19.207",
"Id": "416840",
"Score": "1",
"body": "Thanks for the suggestions. I don't think `while` is compatible with the algorithm I chose. Also, the algorithm you used is **wrong**; it tests if the needle is a contiguous subsequence of the haystack, and that's not what I'm trying to do (my use case doesn't require the needle to be contiguous. e.g `[1, 1]` is a subsequence of `[1, 0, 1]`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T15:08:21.003",
"Id": "416854",
"Score": "0",
"body": "You should have clarified the problem statement in the Question, and if there were any tests, it would have been more obvious ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T08:34:03.437",
"Id": "215329",
"ParentId": "215324",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T07:40:18.817",
"Id": "215324",
"Score": "5",
"Tags": [
"python",
"performance",
"beginner",
"algorithm",
"array"
],
"Title": "Find if one list is a subsequence of another"
} | 215324 |
<p>I have a Db table:</p>
<pre><code>'aid' INTEGER,
'tid' INTEGER,
</code></pre>
<p>Which represents connection between activity and task, so multiple tasks could be connected to one activity using their ids:</p>
<pre><code>aid tid
1 5
1 9
1 11
</code></pre>
<p>So activity with <code>id=1</code> is connected with tasks with <code>ids=5,9,11</code>.</p>
<p>I load all this data during the launch of the app and put it in <code>SparseArray</code>, where keys of this array are activity ids (<code>aid</code>), and values of this array are arrays with task ids (<code>long[]</code>).</p>
<p>The function looks like this:</p>
<pre><code>public final void setRawCursor(final Cursor cursor) {
if (cursor != null) {
long aid, aidPrev = INVALID;
final FastLongKeySparseArray<long[]> map = mTaskPinMap.getMap();
final FastLongStack stack = new FastLongStack(25);
try {
while (cursor.moveToNext()) {
aid = cursor.getLong(TaskPin.AID_);
if (aidPrev != INVALID
&& aid != aidPrev) {
map.append(aidPrev, stack.toArray(new long[stack.size()]));
stack.clear();
}
stack.push(cursor.getLong(TaskPin.TID_));
aidPrev = aid;
}
if (aidPrev != INVALID) map.append(aidPrev, stack.toArray(new long[stack.size()]));
} finally {
cursor.close();
}
}
mIsDataReady = true;
}
</code></pre>
<p>My purpose to save as much memories as possible, and do not make pressure on GC. I use <code>long[]</code> instead of <code>ArrayList</code> because this data could be modified in rear cases, so it is not hard to add new ids to <code>long[]</code> by coping the array, and I think to save memory with such turn.</p>
<p>What do you think? Is it possible to eliminate put to the map after the loop?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T07:57:15.343",
"Id": "215325",
"Score": "3",
"Tags": [
"java",
"android"
],
"Title": "Load all data from cursor"
} | 215325 |
<p>I have an array of some elements that I need to loop through (i.e. execute some block <code>A</code> on each element) but between them I have also to "clean up" (block <code>B</code>) from the previous iteration and that I don't need to clean after the last iteration because <code>B</code> is slow and it is done somewhere further in more efficient way like process exit or whatever. If the array is <code>[1,2,3]</code> the flow should be like:</p>
<pre><code>[1, :IN]
[1, :OUT]
[2, :IN]
[2, :OUT]
[3, :IN]
</code></pre>
<p>It is similar to <a href="https://reference.wolfram.com/language/ref/Riffle.html" rel="nofollow noreferrer">Mathematica Riffle[]</a> function. I already <a href="https://github.com/Nakilon/mll/blob/77abd45d5b8e03133c6df018aa92218856133a3b/lib/mll.rb#L215-L241" rel="nofollow noreferrer">implemented it in Ruby three years ago</a> but that implementation is complex and there is a place only for <code>B</code>, not for <code>A</code>. So I rewrote it for my current case:</p>
<pre><code>riffle = lambda do |enumerable, &block|
prev = nil
enumerable.each_with_index do |e, i|
block.call prev unless i.zero?
prev = e
end
end
riffle.call( Enumerator.new do |e|
[1,2,3].each do |i|
e << i
# start block A
p [i, :IN]
# end
end
end ) do |i|
# start block B
p [i, :OUT]
# end
end
</code></pre>
<p>Is there a way to make less code and maybe not use <code>Enumerator.new</code>? I tried to use <code>.to_enum</code> and <code>.lazy.map(&A)</code> but had no success.</p>
| [] | [
{
"body": "<p>There's not too much to say about your implementation, though I'm not sure declaring <code>riffle</code> as a lambda provides any benefit instead of just defining it as a standard function.</p>\n\n<p>Instead of storing the previous element of the iteration and using it to call the block, you should check only call the block if you are not on the last element of the enumerable (if possible, of course, there are some cases when it isn't).</p>\n\n<p>While you can use a mixture of a custom enumerator and a block, it's not the nicest way to do things. I'd recommend instead passing in two lambdas (or a lambda and a block) so that it is immediately clear that the first block follows the second.</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>def riffle(enumerable, a, b)\n enumerable.each_with_index do |x, i|\n a.call x\n b.call x unless i + 1 == enumerable.size\n end\nend\n\nriffle [1, 2, 3],\n -> i { p [i, :IN] },\n -> i { p [i, :OUT] }\n</code></pre>\n\n<p>This gives the output:</p>\n\n<pre><code>[1, :IN]\n[1, :OUT]\n[2, :IN]\n[2, :OUT]\n[3, :IN]\n=> [1, 2, 3]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T09:25:16.467",
"Id": "419318",
"Score": "0",
"body": "It is a habit to use `lambda` instead of `def` whenever possible to avoid outer scope pollution and have a benefit of access to local variables if needed. Seems like using lambda+lambda instead of Enumerator+block looks clearer inside because you call both in the same way -- with `.call`. Have an upvote, I'll accept later."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T23:47:20.413",
"Id": "215384",
"ParentId": "215327",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T08:06:21.200",
"Id": "215327",
"Score": "2",
"Tags": [
"ruby",
"iterator"
],
"Title": "Short analogue of Riffle[] accepting two blocks"
} | 215327 |
<p>I've written a module whose purpose is to allow a user to simply add their email and click 'Save Search'. The details of the search are stored in two straight MySql tables which are not in any way related to the rest of the tables which are used by Drupal.</p>
<p>The class is close to complete (Dotmailer API integration needs to be done) and I've been applying PSR-2 standards as best as possible but my question regarding the class are:</p>
<p>1) Over all, am I doing anything drastically wrong and or what bad practices exist that I can correct?</p>
<p>I simply want to improve my overall PHP coding and any tips/constructive crit would be welcomed.</p>
<p>Latest PHP version is been used, all SQL queries use the Drupal 8 DB API.</p>
<p>Many thanks</p>
<pre><code><?php
declare(strict_types=1);
namespace Drupal\lrg_search_saves;
use Drupal;
use Drupal\Core\Database\Database;
use Drupal\lrg_search_form\PropertyCard;
use Drupal\lrg_search_form\PropertySearch;
use Drupal\lrg_search_form\PropertyTypes;
use Drupal\node\Entity\Node;
use Drupal\lrg_search_form\Validators\{
Validator,
Integer,
Options,
NoValidation
};
use InvalidArgumentException;
class SearchesSaved
{
private $db;
private $searchParam;
private $debugDrush;
private $dotMailerSearchPackets;
private $base_url;
private function __construct()
{
$this->db = Database::getConnection();
$this->searchParam = self::initSearchParamsArray();
$this->debugDrush = false;
$this->dotMailerSearchPackets = [];
$this->base_url = \Drupal::request()->getHost();
// For localhost testing, force port number used by docker container
if ($this->base_url === 'localhost') {
$this->base_url = 'http://localhost:81';
}
}
/**
* Factory method
* -----------------------------------------------------------------------------------------------------------------
* @return SearchesSaved
*/
public static function create(): SearchesSaved
{
return new SearchesSaved();
}
/**
* Init the search parameters array
* -----------------------------------------------------------------------------------------------------------------
* @return array
*/
private function initSearchParamsArray(): array
{
return [
'search_type' => new Options('buy', 'rent'),
'search_location_key' => new NoValidation(),
'search_location' => new NoValidation(),
'buying_min_price' => new Integer(0, 0),
'buying_max_price' => new Integer(0, 0),
'renting_min_price' => new Integer(0, 0),
'renting_max_price' => new Integer(0, 0),
'min_bedrooms' => new Integer(0, 6),
'property_type' => new Options('Any', 'Terraced House', 'Semi Detached House', 'Detached House',
'Flat / Apartment', 'Bungalow'),
'filter_options' => new Options('Any', 'INVESTMENT', 'AUCTION', 'NEW_HOMES', 'COMMERCIAL',
'SHARED_OWNERSHIP')
];
}
/**
* Set a specific search parameter
* -----------------------------------------------------------------------------------------------------------------
* @param $paramName
* @param $paramValue
*/
private function setInitSearchParam($paramName, $paramValue)
{
if (array_key_exists($paramName, $this->searchParam)) {
$this->searchParam[$paramName] = $paramValue;
}
}
/**
* Get the search parameters from the querystring and validate them and store
* -----------------------------------------------------------------------------------------------------------------
* @return array
*/
public function setSearchParams(): void
{
$queryArgs = [
'search_type' => new Options('buy', 'rent'),
'search_location_key' => new NoValidation(),
'search_location' => new NoValidation(),
'buying_min_price' => new Integer(0, 9000000),
'buying_max_price' => new Integer(0, 9000000),
'renting_min_price' => new Integer(0, 8000),
'renting_max_price' => new Integer(0, 8000),
'min_bedrooms' => new Integer(0, 6),
'property_type' => new Options('Any', 'Terraced House', 'Semi Detached House', 'Detached House',
'Flat / Apartment', 'Bungalow'),
'filter_options' => new Options('Any', 'INVESTMENT', 'AUCTION', 'NEW_HOMES', 'COMMERCIAL',
'SHARED_OWNERSHIP'),
];
$args = [];
foreach ($queryArgs as $arg => $validator) {
$args[$arg] = $validator->sanitise(Drupal::request()->query->get($arg));
}
$this->searchParam = $args;
}
/**
* Check the search parameters are within specifications
* -----------------------------------------------------------------------------------------------------------------
* @return bool
*/
private function validateSearchParams(): bool
{
if (is_null($this->searchParam['search_location'])) {
return false;
}
if (!is_string($this->searchParam['search_location'])) {
return false;
}
if (strlen($this->searchParam['search_location']) <= 0) {
return false;
}
return true;
}
/**
* Unsubscribe based upon hash and email address
* -----------------------------------------------------------------------------------------------------------------
* @param string $hash
* @param string $email_address
* @return int
*/
public function unsubscribe(string $hash, string $email_address): ?int
{
$searchUser = null;
$status = 0;
try {
$searchUser = $this->dbGetSearchUserByEmail($email_address);
} catch (\Exception $ex) {
$status = 5;
}
if (isset($searchUser)) {
$unsubscribeAllSavedSearches = ($searchUser['unique_hash'] === $hash);
$status = $this->dbDeleteSearch($hash, $email_address, $unsubscribeAllSavedSearches);
}
return $status;
}
/**
* Conduct a search against DB
* -----------------------------------------------------------------------------------------------------------------
* @param string $hash
* @param string $email
* @return array|null
*/
public function runSearchByHash(string $hash): ?array
{
$propertyTypes = new PropertyTypes();
$savedSearchData = $this->dbGetSearchDataForHash($hash);
$paramArgs = [
'search_type' => $savedSearchData['param_search_type'],
'search_location_key' => $savedSearchData['param_search_location_key'],
'search_location' => $savedSearchData['param_search_location'],
'buying_min_price' => (int)$savedSearchData['param_buying_min_price'],
'buying_max_price' => $savedSearchData['param_buying_max_price'] ? (int)$savedSearchData['param_buying_max_price'] : null,
'renting_min_price' => $savedSearchData['param_renting_min_price'] ? (int)$savedSearchData['param_renting_min_price'] : null,
'renting_max_price' => $savedSearchData['param_renting_max_price'] ? (int)$savedSearchData['param_renting_max_price'] : null,
'min_bedrooms' => $savedSearchData['param_min_bedrooms'] ? (int)$savedSearchData['param_min_bedrooms'] : null,
'property_type' => $savedSearchData['param_property_type'],
'filter_options' => $savedSearchData['param_filter_options'],
'radius' => 0,
];
$searchEngine = new PropertySearch($this->db, $paramArgs, $propertyTypes);
$returnedResults = $searchEngine->entityQuery();
return (count($returnedResults) > 0) ? $returnedResults : null;
}
/**
* Save search to database
* -----------------------------------------------------------------------------------------------------------------
* @param string $email_address
*/
public function saveSearch(string $email_address): void
{
$searchIsValid = false;
$uniqueHash = null;
$searchUserData = self::dbGetSearchUserByEmail($email_address);
if ($searchUserData == null) {
self::dbInsertSearchUser($email_address);
}
$searchUserData = self::dbGetSearchUserByEmail($email_address);
if (self::validateSearchParams()) {
$searchIsValid = true;
}
if ($searchIsValid) {
$uniqueHash = $this->generateMD5Hash($email_address);
if (!is_string($uniqueHash) || self::dbIsHashUsed($uniqueHash)) {
$searchIsValid = false;
}
}
if ($searchIsValid && !is_null($searchUserData)) {
$this->dbInsertSearch($email_address, $uniqueHash, $searchUserData);
}
}
/**
* Loop through each saved search and process it
* -----------------------------------------------------------------------------------------------------------------
* @return int
*/
private function processAllSavedSearches(): void
{
$allSearches = null;
$allSearches = $this->dbGetAllSearchesToProcess(); // Return array(array(email, hash), array(email, hash))
foreach ($allSearches as $search) {
$searchResultData = $this->runSearchByHash($search['unique_hash']);
if (count($searchResultData) > 0) {
$packet = $this->buildDotmailerPacket($searchResultData, $search);
if (!is_null($packet)) {
$this->dotMailerSearchPackets[] = $packet;
}
}
}
foreach ($this->dotMailerSearchPackets as $packet) {
$this->triggerDotmailerEmail($packet);
}
}
/**
* Build the email HTML and send to dotmailer via Transactional email API call
* -----------------------------------------------------------------------------------------------------------------
* @param array $savedSearchPacket
*/
private function triggerDotmailerEmail(array $savedSearchPacket): void
{
$this->drushDebug('Packet sent to dotMailer: ');
$this->drushDebug(json_encode($savedSearchPacket, JSON_PRETTY_PRINT));
}
/**
* Prepare the data to be sent to the dotMailer system.
* -----------------------------------------------------------------------------------------------------------------
* @param array $srchResult
* @param array $srchParam
* @return array
*/
private function buildDotmailerPacket(array $srchResult, array $srchParam): ?array
{
$propIdsUsed = explode(",", $srchParam['log_property_ids_used']);
$propIdsToGet = [];
$searchUser = $this->dbGetSearchUserByEmail($srchParam['email']);
$hashUnsubscribeAll = $searchUser['unique_hash'];
$dotMailerPacket = [
'replyEmailAddress' => '',
'recipientEmailAddress' => $srchParam['email'],
'searchLocation' => $srchParam['search_location'],
'url_unsubscribe' => $this->base_url . '/property-search/unsubscribe/' . $srchParam['unique_hash'] . '/' . $srchParam['email'],
'url_unsubscribe_all' => $this->base_url . '/property-search/unsubscribe/' . $hashUnsubscribeAll . '/' . $srchParam['email'],
];
$propertyTypes = new PropertyTypes();
$propertyMaxCount = 5;
$propertyCounter = 0;
foreach ($srchResult as $propertyId) {
if (!in_array($propertyId, $propIdsUsed) && ($propertyCounter < $propertyMaxCount)) {
$propIdsToGet[] = $propertyId;
$propIdsUsed[] = $propertyId;
$nodeLoaded = Node::load($propertyId);
if (isset($nodeLoaded)) {
$property = new PropertyCard((int)$propertyId, $propertyTypes);
$dotMailerPacket['properties'][] = [
'nid' => $propertyId,
'title' => $nodeLoaded->getTitle(),
'thumbnail' => $this->base_url . $property->mainImageThumbnailURL,
'url' => $this->base_url . $property->mainPropertyURL,
'displayAddress' => $property->displayAddress,
'price' => $property->price,
'formattedDeposit' => $property->formattedDeposit,
'buyorlet' => $property->isSale ? 'buy' : 'let',
'features' => $property->features,
];
$propertyCounter++;
}
}
}
$this->dbUpdatePropertiesUsed($srchParam['unique_hash'], implode(",", array_filter($propIdsUsed)));
// if(is_array($dotMailerPacket['properties'])){
return (is_array($dotMailerPacket['properties']) && count($dotMailerPacket['properties']) > 0) ? $dotMailerPacket : null;
// }else{
//
// }
//return $dotMailerPacket;
}
/**
* Output a given message for debugging if debug parameter was passed via drush
* -----------------------------------------------------------------------------------------------------------------
* @param $msg
*/
private function drushDebug($msg)
{
if ($this->debugDrush) {
drush_print($msg);
}
}
/**
* Entry point for the drush command to process all saved searches
* -----------------------------------------------------------------------------------------------------------------
* @return bool|int
*/
public function drushProcessSearches(?string $debug): void
{
if ($debug === 'debug') {
$this->debugDrush = true;
}
$this->drushDebug('Attempting to process all saved searches');
$drushProcessStatus = null;
try {
$this->processAllSavedSearches();
} catch (\Exception $ex) {
\Drupal::logger('lrg_search_saves')
->error('processAllSavedSearches failed when calling processAllSavedSearches: Exception: ' . $ex->getMessage());
}
}
/**
* Create MD5 hash
* -----------------------------------------------------------------------------------------------------------------
* @param string $email_address
* @param string|null $additionalSalt
* @param string $forTable
* @return string
*/
private function generateMD5Hash(
string $email_address,
string $additionalSalt = null,
string $forTable = 'SAVED_SEARCHES'
): string {
$salt = microtime();
$salt2 = (!is_null($additionalSalt)) ? $additionalSalt : '';
$stringToHash = $salt . $salt2 . $email_address;
return md5($stringToHash);
}
/**
* Return true if the search parameters already exist for this email address
* -----------------------------------------------------------------------------------------------------------------
* @param string $email_address
* @param array $searchUserData
* @return bool
*/
private function searchExists(string $email_address): bool
{
$sqlStatement = "SELECT `lrg_saved_searches`.`unique_hash`, `lrg_savedSearchUsers`.`id`
FROM `lrg_saved_searches`
INNER JOIN `lrg_savedSearchUsers`
ON `lrg_savedSearchUsers`.`id` = `lrg_saved_searches`.`refid_unsuball`
WHERE
`lrg_saved_searches`.`param_search_type` = :p_st AND
`lrg_saved_searches`.`param_search_location_key` = :p_slk AND
`lrg_saved_searches`.`param_search_location` = :p_sl AND
`lrg_saved_searches`.`param_buying_min_price` = :p_bminp AND
`lrg_saved_searches`.`param_buying_max_price` = :p_bmaxp AND
`lrg_saved_searches`.`param_renting_min_price` = :p_rminp AND
`lrg_saved_searches`.`param_renting_max_price` = :p_rmaxp AND
`lrg_saved_searches`.`param_min_bedrooms` = :p_mb AND
`lrg_saved_searches`.`param_property_type` = :p_pt AND
`lrg_saved_searches`.`param_filter_options` = :p_fo AND
`lrg_savedSearchUsers`.`email_address` = :email;";
$args = [
':p_st' => $this->searchParam['search_type'],
':p_slk' => $this->searchParam['search_type'],
':p_sl' => $this->searchParam['search_type'],
':p_bminp' => $this->searchParam['search_type'],
':p_bmaxp' => $this->searchParam['search_type'],
':p_rminp' => $this->searchParam['search_type'],
':p_rmaxp' => $this->searchParam['search_type'],
':p_mb' => $this->searchParam['search_type'],
':p_pt' => $this->searchParam['search_type'],
':p_fo' => $this->searchParam['search_type'],
':email' => $this->searchParam['search_type'],
];
$query = $this->db->query($sqlStatement, $args);
$status = $query->fetchAssoc() ? true : false;
return $status;
}
/**
* Is hash in use
* -----------------------------------------------------------------------------------------------------------------
* @param string $hash
* @param string $tableToCheck
* @return bool
*/
private function dbIsHashUsed(string $hash, string $tableToCheck = 'SAVED_SEARCHES'): bool
{
$result = null;
$tbl = ($tableToCheck === 'SAVED_SEARCHES') ? 'lrg_saved_searches' : 'lrg_savedSearchUsers';
$queryStatement = "SELECT COUNT(`id`) as `HashNumCount`
FROM $tbl WHERE `unique_hash` LIKE :unique_hash;";
$args = [
':unique_hash' => $hash,
];
try {
$query = $this->db->query($queryStatement, $args);
$result = $query->fetchAssoc();
} catch (\Exception $ex) {
\Drupal::logger('SearchesSaved Class')->error('dbIsHashUsed() Exception: ' . $ex->getMessage());
}
if ($result) {
$numTimesUsed = $result['HashNumCount'];
if ($numTimesUsed > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Find user by email from `lrg_savedSearchUsers` table
* -----------------------------------------------------------------------------------------------------------------
* @param string $email_address
* @return array|null
*/
private function dbGetSearchUserByEmail(string $email_address): ?array
{
$result = null;
$queryStatement = "SELECT * FROM `lrg_savedSearchUsers`
WHERE `email_address` = :email";
try {
$query = $this->db->query($queryStatement, array(':email' => $email_address));
$result = $query->fetchAssoc();
} catch (\Exception $ex) {
\Drupal::logger('SearchesSaved Class')->error('dbGetSearchUserByEmail() Exception: ' . $ex->getMessage());
}
if ($result) {
return $result;
}
return null;
}
/**
* Search for a specific saved search
* -----------------------------------------------------------------------------------------------------------------
* @param string $hash
* @return array
*/
private function dbGetSearchDataForHash(string $hash): ?array
{
$result = null;
$sqlGetSearchData = "SELECT `lrg_saved_searches`.* FROM `lrg_saved_searches`
INNER JOIN `lrg_savedSearchUsers` ON `lrg_savedSearchUsers`.`id` = `lrg_saved_searches`.`refid_unsuball`
WHERE `lrg_saved_searches`.`unique_hash` = :unique_hash";
try {
$query = $this->db->query($sqlGetSearchData, array(':unique_hash' => $hash));
$result = $query->fetchAssoc();
} catch (\Exception $ex) {
\Drupal::logger('SearchesSaved Class')->error('dbGetSearchDataForHash() Exception: ' . $ex->getMessage());
}
if ($result) {
return $result;
} else {
return null;
}
}
/**
* Return array of emails and hashes of searches to conduct
* -----------------------------------------------------------------------------------------------------------------
* @return array|null
*/
private function dbGetAllSearchesToProcess(): ?array
{
$searchCollection = null;
$sqlGetAllSearches = "SELECT `lrg_saved_searches`.*,
`lrg_savedSearchUsers`.`email_address` as `email`
FROM `lrg_saved_searches`
INNER JOIN `lrg_savedSearchUsers` ON
`lrg_savedSearchUsers`.`id` = `lrg_saved_searches`.`refid_unsuball`";
try {
$query = $this->db->query($sqlGetAllSearches);
while ($result = $query->fetchAssoc()) {
$searchCollection[] = $result;
}
} catch (\Exception $ex) {
\Drupal::logger('SearchesSaved Class')->error('dbGetAllSearchesToProcess() Exception: ' . $ex->getMessage());
}
if (count($searchCollection) > 0) {
return $searchCollection;
} else {
return null;
}
}
/**
* Delete a single search or delete all searches and the user owning them
* -----------------------------------------------------------------------------------------------------------------
* @param string $hash
* @param string $email_address
* @param bool $deleteAllSearches
* @return int
*/
private function dbDeleteSearch(string $hash, string $email_address, $deleteAllSearches = false): int
{
if ($deleteAllSearches) {
$queryStatement = "DELETE `lrg_savedSearchUsers`, `lrg_saved_searches` FROM `lrg_saved_searches`
RIGHT JOIN `lrg_savedSearchUsers`
ON `lrg_saved_searches`.`refid_unsuball` = `lrg_savedSearchUsers`.`id`
WHERE `lrg_savedSearchUsers`.`email_address` = :email AND
`lrg_savedSearchUsers`.`unique_hash` = :unique_hash";
$args = [
':email' => $email_address,
':unique_hash' => $hash,
];
try {
$this->db->query($queryStatement, $args);
return 1;
} catch (\Exception $ex) {
return 3;
}
} else {
$queryStatement = "DELETE FROM `lrg_saved_searches` WHERE `unique_hash` = :unique_hash";
try {
$this->db->query($queryStatement, array(':unique_hash' => $hash));
return 2;
} catch (\Exception $ex) {
return 4;
}
}
}
/**
* Update a searches' list of properties that were previously sent.
* -----------------------------------------------------------------------------------------------------------------
* @param string $hash
* @param string $propIds
*/
private function dbUpdatePropertiesUsed(string $hash, string $propIds): void
{
$sqlUpdate = "UPDATE `lrg_saved_searches`
SET `log_property_ids_used` = :propIds,
`date_updated` = NOW()
WHERE `unique_hash` = :unique_hash";
$args = [
':propIds' => $propIds,
':unique_hash' => $hash,
];
try {
$this->db->query($sqlUpdate, $args);
} catch (\Exception $ex) {
\Drupal::logger('SearchesSaved Class')->error('dbUpdatePropertiesUsed() Exception: ' . $ex->getMessage());
}
}
/**
* Insert Search into database
* -----------------------------------------------------------------------------------------------------------------
* @param string $emailAddress
* @param string $uniqueHash
* @param array $searchUserData
*/
private function dbInsertSearch(
string $emailAddress,
string $uniqueHash,
array $searchUserData
): void {
if ($this->searchExists($emailAddress)) {
return;
}
$sqlInsertStatement = "INSERT INTO `lrg_saved_searches`
(
`id`, `unique_hash`, `refid_unsuball`, `date_created`,
`date_updated`, `param_search_type`, `param_search_location_key`, `param_search_location`,
`param_buying_min_price`, `param_buying_max_price`, `param_renting_min_price`, `param_renting_max_price`,
`param_min_bedrooms`, `param_property_type`, `param_filter_options`, `log_property_ids_used`
)VALUES(
NULL, :uhash, :refid, NOW(),
NOW(), :p_st, :p_slk, :p_sl,
:p_bminp, :p_bmaxp, :p_rminp, :p_rmaxp,
:p_mb, :p_pt, :p_fo, ''
);";
$sqlArgs = [
":uhash" => $uniqueHash,
":refid" => $searchUserData['id'],
":p_st" => $this->searchParam['search_type'],
":p_slk" => $this->searchParam['search_location_key'],
":p_sl" => $this->searchParam['search_location'],
":p_bminp" => $this->searchParam['buying_min_price'],
":p_bmaxp" => $this->searchParam['buying_max_price'],
":p_rminp" => $this->searchParam['renting_min_price'],
":p_rmaxp" => $this->searchParam['renting_max_price'],
":p_mb" => $this->searchParam['min_bedrooms'],
":p_pt" => $this->searchParam['property_type'],
":p_fo" => $this->searchParam['filter_options'],
];
try {
$this->db->query($sqlInsertStatement, $sqlArgs);
\Drupal::logger('SearchesSaved Class')->notice('Search successfully saved, parameters were: ' . json_encode($this->searchParam));
} catch (InvalidArgumentException $ex) {
\Drupal::logger('SearchesSaved Class')->error('dbInsertSearch() InvalidArgumentException: ' . $ex->getMessage());
} catch (\Exception $ex) {
\Drupal::logger('SearchesSaved Class')->error('dbInsertSearch() Exception: ' . $ex->getMessage());
}
}
/**
* Save a new entry in the `lrg_savedSearchUsers` table. Used for tracking user emails and also for
* un-subscribing ALL searches
* -----------------------------------------------------------------------------------------------------------------
* @param string $email_address
*/
private function dbInsertSearchUser(string $email_address): void
{
$uniqueHash = $this->generateMD5Hash($email_address, 'NOTSAVEDSEARCHES');
$sqlStatement = "INSERT INTO `lrg_savedSearchUsers` (`id`, `email_address`, `unique_hash`)
VALUES (NULL, :email, ':unique_hash');";
try {
$this->db->query($sqlStatement, array(':email' => $email_address, ':unique_hash' => $uniqueHash));
} catch (\Exception $ex) {
\Drupal::logger('SearchesSaved Class')->error('dbInsertSearchUser() Exception: ' . $ex->getMessage());
}
}
}
</code></pre>
| [] | [
{
"body": "<p>You'll have to take some of these at face value as I don't use Drupal.</p>\n\n<p>I looked at this purely from a logical and structural view point, So there are probably a few things going on here i may not realize. So make sure to review my suggestions closely.</p>\n\n<p>For example I don't know what a lot of the inputs are I may have suggested changing a few to constants such as this <code>$tableToCheck = 'SAVED_SEARCHES'</code> to <code>$tbl = self::TBL_SAVED_USERS</code> in <code>dbIsHashUsed</code> what I used was the tbl name.</p>\n\n<p>Some of them I had to extensively rework, so pay attention to them. Most of it is simplification, removing some local variables etc.</p>\n\n<p>Oh and I found a bug (I think) in <code>generateMD5Hash</code> the table name is not used <code>$forTable</code> the third argument.</p>\n\n<p>etc..</p>\n\n<pre><code>private function __construct()\n{\n //...\n //use static instead of self if you plan on extending this (Late static binding) - something to consider for all static calls\n $this->searchParam = self::initSearchParamsArray();\n //...\n}\n\npublic static function create(): SearchesSaved\n{\n return new SearchesSaved; //the () are not required here \n //you can leave them for readability\n //but I find a lot of programmers don't know this\n}\n\nprivate function setInitSearchParam($paramName, $paramValue)\n{\n //...\n if (isset($this->searchParam[$paramName]))\n //isset is much faster then array_key_exists (Language construct vs function call)\n //...\n}\n\n//use dependency injection if possible\n//this is not called internally (that i could find) so it may be a good choice for it\npublic function setSearchParams(\\WhateverClass $Query): void\n{\n\n //...\n $args[$arg] = $validator->sanitise($Query->get($arg));\n //...\n}\n\nprivate function validateSearchParams(): bool\n{\n //simplify\n return (\n is_null($this->searchParam['search_location']) || \n !is_string($this->searchParam['search_location']) || \n strlen($this->searchParam['search_location']) <= 0) \n );\n}\n\n//combine and simplify\npublic function unsubscribe(string $hash, string $email_address): ?int\n{\n\n try {\n $searchUser = $this->dbGetSearchUserByEmail($email_address);\n\n $status = $this->dbDeleteSearch(\n $hash,\n $email_address,\n ($searchUser['unique_hash'] === $hash)\n );\n } catch (\\Exception $ex) {\n $status = 5;\n }\n\n return $status;\n}\n\n\n//Make sure to test this one I had to change a lot \npublic function saveSearch(string $email_address): void\n{\n if (self::validateSearchParams()) {\n if (is_null(self::dbGetSearchUserByEmail($email_address)) {\n //insert if no users\n self::dbInsertSearchUser($email_address); //1\n }\n\n //generate this\n $uniqueHash = $this->generateMD5Hash($email_address);\n\n //if uniqueHash is a string AND it's not used AND a user exists\n if (\n is_string($uniqueHash) &&\n !self::dbIsHashUsed($uniqueHash) &&\n !is_null($searchUserData = self::dbGetSearchUserByEmail($email_address)) //assignment\n ) {\n $this->dbInsertSearch($email_address, $uniqueHash, $searchUserData);\n }\n }\n}\n\nprivate function processAllSavedSearches(): void\n{\n //allSearches can be removed\n\n foreach ($this->dbGetAllSearchesToProcess() as $search) {\n $searchResultData = $this->runSearchByHash($search['unique_hash']);\n\n //you can just use if it's not empty insted of count which is faster\n if (!empty($searchResultData)) { \n $packet = $this->buildDotmailerPacket($searchResultData, $search);\n if (!is_null($packet)) {\n $this->dotMailerSearchPackets[] = $packet;\n }\n }\n }\n\n foreach ($this->dotMailerSearchPackets as $packet) {\n $this->triggerDotmailerEmail($packet);\n }\n}\n\n//Not sure about this - it looks like it should be broken down some but not sure how\n//private function buildDotmailerPacket(array $srchResult, array $srchParam)\n\n//add this constant\nconst DEBUG_MODE = 'debug';\n\n//this looks like a good place for a constant\n//consider - $SearchesSaved->drushProcessSearches(SearchesSaved::DEBUG_MODE)\n//less error prone, eg. did I do \"debug\" or \"debuging\" - you wonder 18 months from now?\npublic function drushProcessSearches(?string $debug): void\n{\n if ($debug === self::DEBUG_MODE) {\n $this->debugDrush = true;\n }\n $this->drushDebug('Attempting to process all saved searches');\n\n //remove this -> $drushProcessStatus = null; Unused\n\n //..\n}\n\nprivate function generateMD5Hash(\n string $email_address,\n string $additionalSalt = null,\n string $forTable = 'SAVED_SEARCHES' //<--- unused {BUG} ? - this should be a constant as well\n): string {\n //unchanged\n $salt = microtime();\n $salt2 = (!is_null($additionalSalt)) ? $additionalSalt : '';\n $stringToHash = $salt . $salt2 . $email_address;\n\n return md5($stringToHash);\n}\n\n//add these constants\nconst TBL_SAVED_SEARCHES = 'lrg_saved_searches';\nconst TBL_SAVED_USERS = 'lrg_savedSearchUsers';\n\nprivate function dbIsHashUsed(string $hash, string $tbl = self::TBL_SAVED_USERS): bool\n{ \n if($tableToCheck !== self::TBL_SAVED_SEARCHES){\n $tbl = self::TBL_SAVED_USERS;\n }\n\n $args = [\n ':unique_hash' => $hash,\n ];\n\n try {\n $query = $this->db->query(\n \"SELECT COUNT(`id`) as `HashNumCount` FROM $tbl WHERE `unique_hash` LIKE :unique_hash;\"\n , [':unique_hash' => $hash]\n );\n $result = $query->fetchAssoc(); //could do fetchColumn or however you Drupal guys do it\n\n return ( $result && $result['HashNumCount'] > 0 );\n\n } catch (\\Exception $ex) {\n \\Drupal::logger('SearchesSaved Class')->error('dbIsHashUsed() Exception: ' . $ex->getMessage());\n }\n}\n\n//there are a few like this one\nprivate function dbGetSearchUserByEmail(string $email_address): ?array\n{\n try {\n $query = $this->db->query(\"SELECT * FROM `lrg_savedSearchUsers` WHERE `email_address` = :email\", [':email' => $email_address]); //consstancy\n return $query->fetchAssoc();\n } catch (\\Exception $ex) {\n \\Drupal::logger('SearchesSaved Class')->error('dbGetSearchUserByEmail() Exception: ' . $ex->getMessage());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T09:08:18.600",
"Id": "417423",
"Score": "0",
"body": "Cheers @ArtisticPhoenix appreciated. Wasn't concerned with the Drupal stuff, more the structure and general PHP stuff. Your rework has all been helpful and have applied some of the changes you showed to my other classes also. I appreciate your time and effort."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T20:25:42.303",
"Id": "215529",
"ParentId": "215331",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215529",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T08:59:35.103",
"Id": "215331",
"Score": "2",
"Tags": [
"php",
"drupal"
],
"Title": "PHP Class used in Drupal 8 module"
} | 215331 |
<p>I have created a method that is responsible for the creation and the saving of memes. This is a huge mistake because now I need to use 1 of those functionalities (creating) for a different purpose. I tried to divide them into different methods but the code is tightly chained together. For example, when I removed all the code responsible for creating the meme, I noticed that my mutableBitmap object is also used in the block of code responsible for saving the meme.</p>
<p>This is the method I want to divide with detailed comments</p>
<pre><code>public void createBitmapAndSave(ImageView img) {
//Gets the image from ImageView and turns its into a mutable bitmap
BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
Bitmap bitmap = bitmapDrawable.getBitmap();
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
//Gets the texts from the textviews to draw on the bitmap
String topText = topTextView.getText().toString();
String bottomText = bottomTextView.getText().toString();
//Text becomes all caps
topText = topText.toUpperCase();
bottomText = bottomText.toUpperCase();
//Canvas created and takes mutableBitmap as its parameter
Canvas canvas = new Canvas(mutableBitmap);
//Creating 4 TextPaint objects for the outlined Impact meme custom font
TextPaint topFillPaint = new TextPaint();
TextPaint bottomFillPaint = new TextPaint();
TextPaint topStrokePaint = new TextPaint();
TextPaint bottomStrokePaint = new TextPaint();
//Typeface for the impact font
Typeface typeface = getResources().getFont(R.font.impact);
//Setting the attributes of the custom font
topFillPaint.setColor(Color.WHITE);
topFillPaint.setTextSize(topTextView.getTextSize());
topFillPaint.setTypeface(typeface);
topStrokePaint.setStyle(Paint.Style.STROKE);
topStrokePaint.setStrokeWidth(8);
topStrokePaint.setColor(Color.BLACK);
topStrokePaint.setTextSize(topTextView.getTextSize());
topStrokePaint.setTypeface(typeface);
bottomFillPaint.setColor(Color.WHITE);
bottomFillPaint.setTextSize(bottomTextView.getTextSize());
bottomFillPaint.setTypeface(typeface);
bottomStrokePaint.setStyle(Paint.Style.STROKE);
bottomStrokePaint.setStrokeWidth(8);
bottomStrokePaint.setColor(Color.BLACK);
bottomStrokePaint.setTextSize(bottomTextView.getTextSize());
bottomStrokePaint.setTypeface(typeface);
//Using StaticLayout because the text could potentially be multiline. Made 4 StaticLayout objects for the custom font
StaticLayout topFillLayout = new StaticLayout(topText, topFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
1.0f, 0.0f, false);
StaticLayout topStrokeLayout = new StaticLayout(topText, topStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
1.0f, 0.0f, false);
StaticLayout bottomFillLayout = new StaticLayout(bottomText, bottomFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
1.0f, 0.0f, false);
StaticLayout bottomStrokeLayout = new StaticLayout(bottomText, bottomStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
1.0f, 0.0f, false);
//Drawing the text on the canvas using the StaticLayout.draw() method
topFillLayout.draw(canvas);
topStrokeLayout.draw(canvas);
canvas.translate(0, canvas.getHeight() - 210);
bottomFillLayout.draw(canvas);
bottomStrokeLayout.draw(canvas);
//Used to add an integer after the timestamp to ensure uniqueness
counter++;
//The remaining block of code deals with saving the meme to the device
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/SimpliMeme/" + timeStamp + "-" + counter + ".jpg");
file.getParentFile().mkdir();
try {
OutputStream stream = new FileOutputStream(file);
mutableBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
}
</code></pre>
<p>Now I want to divide this code into these 2 methods:</p>
<pre><code>public void createMeme(){returns the mutable bitmap with the text drawn}
public void saveMeme(){}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T11:44:21.783",
"Id": "416466",
"Score": "2",
"body": "It appears that you haven't yet finished the code to your own satisfaction. Please complete the work that you outlined, and then edit to put the finished code in your review request."
}
] | [
{
"body": "<p>Instead of <code>createMeme()</code> being a void function, you could have it return the created meme, <code>mutableBitmap</code>.<br>\nThen, set up your <code>saveMeme</code> function to accept a <code>mutableBitmap</code> as a parameter.</p>\n\n<p>That way, when you want to create AND save, as you originally intended when you created the large function, you might call <code>saveMeme</code> like this: <code>saveMeme(createMeme())</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T00:09:41.223",
"Id": "416565",
"Score": "0",
"body": "And is `saveMeme(createMeme())` what I call in the `onReceive()` of my `LocalBroadcastManager`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:22:15.190",
"Id": "215350",
"ParentId": "215335",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215350",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T10:02:47.977",
"Id": "215335",
"Score": "-1",
"Tags": [
"java",
"android",
"extension-methods"
],
"Title": "How to divide a large method into 2 smaller methods"
} | 215335 |
<p>I created a little function that returns the elementary values from a flagged enum. By "elementary" I mean the values that are powers of 2, excluding any combined enum values. I was a bit surprised I couldn't find a buit-in method for this in .Net (or I missed it).</p>
<p>Let's take this flagged enum:</p>
<pre><code>[Flags]
public enum WeekDay
{
Monday = 1 << 0,
Tuesday = 1 << 1,
Wednesday = 1 << 2,
Thursday = 1 << 3,
Friday = 1 << 4,
Saturday = 1 << 5,
Sunday = 1 << 6,
WeekendDay = Saturday | Sunday,
BusinessDay = Monday | Tuesday | Wednesday | Thursday | Friday
}
</code></pre>
<p>Since the binary representation of its values looks as follows...</p>
<pre><code>1
10
100
1000
10000
100000
1000000
1100000
11111
</code></pre>
<p>...I came up with this function to extract the elementary values:</p>
<pre><code>public IEnumerable<TEnum> GetElementaryValues<TEnum>()
where TEnum: Enum
{
return Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Where(v =>
{
var intValue = Convert.ToInt64(v);
var binary = Convert.ToString(intValue, 2);
return !binary.Skip(1).Any(c => c == '1');
});
}
</code></pre>
<p>Which basically says: return each value that hasn't got a <code>1</code> beyond its first character.</p>
<p>Doest this look OK? Can it be improved? My feeling is that it's a lot of expensive code for such a simple task.</p>
| [] | [
{
"body": "<p>The way to test for a power of two, where x is an unsigned integer type is</p>\n\n<pre><code>( x != 0 ) && ( ( x & ( x - 1 ) ) == 0 )\n</code></pre>\n\n<p>To understand why this works, it's fairly easy to see that if x is a power of two, then x & (x -1 ) is zero.</p>\n\n<p>If x is not a power of two, then only the bits up to the first non-zero bit are changed when you subtract one, and that is not the most significant bit, so the most significant bit is not cleared, and so x & (x - 1 ) is non-zero, as required.</p>\n\n<p>Zero is a special case - it's not a power of two, so an extra test is needed, also ( x - 1 ) overflows if x is zero.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:17:47.380",
"Id": "416486",
"Score": "0",
"body": "I knew \"something\" with bits should be possible, but didn't figure out this one. Perfect, thanks! Excluding `0` is in line with flagged enum best practices, so that's OK."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T11:56:37.390",
"Id": "215346",
"ParentId": "215341",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "215346",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T11:15:45.027",
"Id": "215341",
"Score": "6",
"Tags": [
"c#",
"enum"
],
"Title": "Get elementary values from a flagged enum"
} | 215341 |
<p>This is a pre version of my program. This program is about solving exercises. Because this is one of my first graphical applications, I want to know, what can be improved. To this point I usually created command line programs.</p>
<p><a href="https://www.dropbox.com/s/xhgx9tbnyapydu0/Mathematician%20FX.jar?dl=0" rel="nofollow noreferrer">You can download the executable here</a></p>
<p><strong>Main.java</strong></p>
<pre><code>import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
/* This class represents a program in which the player has to solve 15
* exercises.
* After he clicks the check button, he can see a summary.
*/
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
int numberOfExercises = 15;
// create exercises
Exercise[] exercises = new Exercise[numberOfExercises];
for (int i = 0; i < numberOfExercises; i++) {
exercises[i] = Exercise.getRandomExercise();
}
// store text fields for later use in an array
TextField textFields[] = new TextField[numberOfExercises];
// display exercises graphically
VBox content = new VBox(numberOfExercises + 1);
for (int i = 0; i < numberOfExercises; i++) {
Label exerciseDescription = new Label(exercises[i]
.toString());
exerciseDescription.setPrefWidth(100);
textFields[i] = new TextField();
textFields[i].setPrefWidth(70);
HBox exerciseBox = new HBox(2);
exerciseBox.getChildren().addAll(exerciseDescription,
textFields[i]);
content.getChildren().add(exerciseBox);
}
Button button = new Button("Check results");
button.setOnAction(event -> {
// check if exercises are solved correctly
int correctExercises = 0;
for (int i = 0; i < exercises.length; i++) {
int guess = 0;
try {
guess = Integer.parseInt(textFields[i].getText());
} catch (Exception e) {
e.printStackTrace();
}
if (exercises[i].compare(guess)) {
correctExercises++;
}
}
// display a message
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Congratulations!");
alert.setHeaderText(null);
String message = "You solved " + correctExercises +
" of " + numberOfExercises + " exercises correctly!";
alert.setContentText(message);
alert.showAndWait();
});
content.getChildren().add(button);
primaryStage.setScene(new Scene(content));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p><strong>Exercise.java</strong></p>
<pre><code>import java.util.Random;
public class Exercise {
private int number1;
private int number2;
private int solution;
private String operationSymbol;
private Exercise(int number1, int number2, int solution,
String operationSymbol) {
this.number1 = number1;
this.number2 = number2;
this.solution = solution;
this.operationSymbol = operationSymbol;
}
public static Exercise getRandomExercise() {
Random random = new Random();
int choice = random.nextInt(4);
int number1;
int number2;
int solution;
String operationSymbol;
if (choice == 0) {
number1 = random.nextInt(26);
number2 = random.nextInt(26);
solution = number1 + number2;
operationSymbol = "+";
} else if (choice == 1) {
number1 = random.nextInt(16) + 10;
number2 = random.nextInt(26);
solution = number1 - number2;
operationSymbol = "-";
} else if (choice == 2) {
number1 = random.nextInt(15) + 1;
number2 = random.nextInt(15) + 1;
solution = number1 * number2;
operationSymbol = "*";
} else {
number1 = random.nextInt(151);
number2 = random.nextInt(15) + 1;
solution = number1 / number2;
operationSymbol = "/";
}
return new Exercise(number1, number2, solution,
operationSymbol);
}
public boolean compare(int guess) {
return guess == solution;
}
@Override
public String toString() {
return number1 + " " + operationSymbol + " " + number2 + " = ";
}
}
</code></pre>
| [] | [
{
"body": "<h3>Separation of concerns</h3>\n\n<p>The <code>start</code> method of an application should be responsible for initializing application-wide basic functionality and trigger the entry point of the application. This means it should deal with Dependency Injection, Application Resource Reservation and similar \"global\" concerns. Setting up the GUI is not the primary concern of that method.</p>\n\n<p>Instead you'll want it to be something like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Override\npublic void start(Stage primaryStage) {\n MainView view = new MainView();\n primaryStage.setScene(view.getScene());\n primaryStage.show();\n}\n</code></pre>\n\n<p>This allows you to encapsulate the View into it's <strong>own</strong> proper class only responsible for the view.</p>\n\n<h3>Setting up the View</h3>\n\n<p>Your View setup intermingles domain logic (what's an Excercise?) with View logic (How are components laid out?). In addition there's a handful of simplifications to be had there.</p>\n\n<ul>\n<li><code>numberOfExercises</code> is a constant, treat it as one.</li>\n<li>The <code>HBox</code> containing all the information about a single exercise <em>could</em> be extracted into a separate component that takes an <code>Exercise</code> as constructor argument and correctly deals with setting up description, solution and encapsulates the correctness checking.</li>\n<li>Your <code>setOnAction</code> for the button seems rather complex. It could benefit a lot from being extracted into a separate method.</li>\n</ul>\n\n<h3>Formatting</h3>\n\n<p>You seem to be following the old school of line-length considerations. Lines in this day and age can (and should) be longer than 80 characters. For one you're using 4 spaces for indentation, and secondly nowadays even the smaller screens are able to support 100-120 characters in width with relative ease.</p>\n\n<p>Forcing the code to adhere to outdated styling regulations makes it hard to read that code.</p>\n\n<h3>ToString is not a user-level representation</h3>\n\n<p>Your code is currently using <code>toString</code> to display a domain object to the user. That's not how this should work. A user representation is usually one that contains less information than the whole object. In general you want to be able to <code>toString</code> an object for logging purposes, incorporating all information available in the object.</p>\n\n<p>Note also that polymorphism makes it nearly trivial to make the code you've written display nonsensical data:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class SpecialExercise extends Exercise {\n public SpecialExercise() {\n super(0, 0, 0, \"\");\n }\n @Override\n public String toString() {\n // basically Object.toString()`\n return super.super.toString();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T11:56:49.320",
"Id": "417457",
"Score": "0",
"body": "Do you know good literature that deals with the question of how to write GUI applications well and professionally? Most of the literature that I have found so far is only concerned with how this and that basically works, but does not bother with the question of what it should look like so that the program is even maintainable when it's bigger."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T12:50:17.757",
"Id": "417463",
"Score": "0",
"body": "@Vengeancos I'm unfortunately not a book person at all, so no literature recommendations from me :/ The general principles of \"Clean Code\" by Bob Martin apply, though. To some extent they need to be mellowed to work with a lot of GUI frameworks, though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T16:29:18.277",
"Id": "215614",
"ParentId": "215342",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "215614",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T11:16:20.777",
"Id": "215342",
"Score": "1",
"Tags": [
"java",
"javafx"
],
"Title": "JavaFX Exercise Application"
} | 215342 |
<p>I am coding a game boy disassembler in C++. The program (simplified here) converts a vector of byte into an assembly instruction and print it. </p>
<p>To do so, it iterates through the vector of bytes (char) with an iterator. I noticed that with the <code>it!=char_vect.end()</code> condition, there is the risk that the iterator goes out from the vector. So I have to check that I do not get out of the vector at each iteration and if it occurs, I throw an error.</p>
<pre><code>#include <iostream>
#include <vector>
int disassemble(std::vector<char>::iterator& it){
int opcode = *it;
int opbytes = 1; //number of bytes used by the operator
switch(opcode){
case 0x76 : std::cout<<"HALT "<<std::endl; opbytes = 1; break;
case 0x10 : std::cout<<"STOP $"<<(int)*(it+1)<<std::endl; opbytes =2; break;
//... About 250 different cases
default : std::cout<<"Instruction not implemented yet"<<std::endl;
}
return opbytes;
}
int main(){
std::vector<char> char_vect = {0x76, 0x10, 0x20}; // Fill vector of char
std::vector<char>::iterator it = char_vect.begin();
// First I only did that
//while (it!=char_vect.end()){
// it+=disassemble(it);
//}
// But I have to check that I do not go out of the char_vect
while (it!=char_vect.end()){
try{
it+=disassemble(it);
//check that it do not overpass end
if (size_t(it - char_vect.begin())>char_vect.size()){
throw "Try to disassemble instruction outside of memory bounds";
}
}
catch(const char * c){
std::cerr << "Fatal error: " << c << std::endl;
return 1;
}
}
return 1;
}
</code></pre>
<p>This code works fine. Now I wonder, I have a possible exception case which is the iterator going further than <code>vect_char.end()</code>. <strong>Is a <code>try / catch</code> an appropriate way to handle this case</strong> knowing that:</p>
<ol>
<li><p>The reason for the iterator to go out of bounds could be either:</p>
<ul>
<li>A non valid input byte sequence, for example {0x76, 0x20, 0x10} since the instruction 0x10 expects an argument. This should not append.</li>
<li>A mistake in the disassemble function. For exemple with the valid input {0x76, 0x10, 0x20}, if I code by mistake that 0x10 uses 3 opbytes instead of 2, the iterator will go out of bounds. This should not append either.</li>
</ul></li>
<li><p>If I iterated through the <code>vect_char</code> with an index, I would not have this issue and the code would be more compact</p></li>
</ol>
<p>I never really used try/catch before and I do not know if it is intented for such situations, so I would like to know, <strong>how would you have handled this unexpected case?</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:14:02.380",
"Id": "416484",
"Score": "3",
"body": "This question might be more on-topic over at https://SoftwareEngineering.StackExchange.com/ . However, **before posting please [follow their tour](https://SoftwareEngineering.StackExchange.com/tour) and read [\"How do I ask a good question?\"](https://SoftwareEngineering.StackExchange.com/help/how-to-ask), [\"What topics can I ask about here?\"](https://SoftwareEngineering.StackExchange.com/help/on-topic) and [\"What types of questions should I avoid asking?\"](https://SoftwareEngineering.StackExchange.com/help/dont-ask).**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:35:12.670",
"Id": "416490",
"Score": "0",
"body": "Does or doesn't the current code work as intended? I assume you've tested it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:38:37.257",
"Id": "416491",
"Score": "1",
"body": "@Mast Yes it does work as intended, I just tested it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T14:24:26.563",
"Id": "416495",
"Score": "2",
"body": "Your error is simply passing insufficient Information to `disassemble()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:28:23.827",
"Id": "416506",
"Score": "3",
"body": "I reformulated my demand because I think it was not clear enough. This question is mainly about validating my design choices, i.e. the use of iterators and try/catch."
}
] | [
{
"body": "<p>Your code's division into functions isn't very natural. The objective is to have each function performing one specific task, which should also be as orthogonal as possible to the tasks performed by the other functions. For instance, your <code>disassemble</code> function performs three different functions: it reads from the instruction stream, it interprets assembly code and returns the number of bytes that should be skipped to get to the next instruction. That's a not-so-coherent mix of responsibilities.</p>\n\n<p>There's also a bug in your code, because <code>it+=disassemble(it);</code> could point beyond <code>char_vect.end()</code> which is in itself undefined behavior, even if you don't dereference the iterator.</p>\n\n<p>I would build my disassembler around an iterator, or better even a range (if you don't mind external libraries or anticipating the next standard):</p>\n\n<pre><code>#include <algorithm>\n#include <vector>\n#include <iostream>\n#include <range/v3/view.hpp>\n\nusing iterator = std::vector<char>::const_iterator;\nstruct truncated_instruction {};\n\n// one function to interpret the instruction\nvoid interpret(char instruction) { \n if (instruction == 'x' throw bad_instruction();\n std::cout << (int) instruction << ' ';\n}\n\n// one function to get the number of bytes to skip\nint nb_bytes(char c) { return 1; } \n\nclass disassembled\n : public ranges::view_facade<disassembled>\n{\n friend ranges::range_access;\n iterator first, last;\n char const & read() const { return *first; }\n bool equal(ranges::default_sentinel) const { return first == last; }\n void next() { \n // one function to get to the next instruction\n auto bytes_to_skip = nb_bytes(*first); \n if (std::distance(first, last) < bytes_to_skip) throw truncated_instruction();\n // check if there's enough space left to advance before advancing\n std::advance(first, bytes_to_skip);\n }\npublic:\n disassembled() = default;\n explicit disassembled(const std::vector<char>& v) : first(v.begin()), last(v.end()) {}\n};\n\nint main() {\n std::vector<char> char_vect = {0x76, 0x10, 0x20, 0x30};\n try {\n for (auto instruction : disassembled(char_vect)) interpret(instruction);\n }\n catch // ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:30:34.817",
"Id": "215353",
"ParentId": "215349",
"Score": "3"
}
},
{
"body": "<p>I have some ideas about how you might be able to improve your program.</p>\n\n<h2>Avoid problems</h2>\n\n<p>Rather than trying to deal with the problem for every instruction, one approach is avoiding it entirely. One way to do that is to simply append a number of bytes to the end of the <code>vector</code>. If the maximum bytes for an instruction is <span class=\"math-container\">\\$n\\$</span>, then append <span class=\"math-container\">\\$n-1\\$</span> bytes to the end and stop when you've advanced into the padded area. </p>\n\n<h2>Check before advancing</h2>\n\n<p>One could also pass the number of remaining bytes to the <code>disassemble</code> function. However, the mechanism I'd suggest would be to pass a range, e.g.:</p>\n\n<pre><code>int diassembleOne(std::vector<char>::iterator& it, std::vector<char>::iterator& end) {\n // figure out number of bytes for this opcode\n if (std::distance(it, end) > opbytes) {\n it = end;\n // throw or return 0\n }\n // disassemble the instruction thoroughly\n std::advance(it, opbytes);\n return opbytes;\n}\n</code></pre>\n\n<h2>Use <code>const</code> iterators</h2>\n\n<p>If all the code is doing is disassembling, then it shouldn't alter the underlying <code>vector</code>. For that reason, I'd recommend passing a <code>std::vector<char>::const_iterator &</code>.</p>\n\n<h2>Use classes</h2>\n\n<p>I'd suggest using an <code>Opcode</code> class like this:</p>\n\n<pre><code>class Opcode {\n char code;\n short int bytes;\n std::string_view name;\n bool operator==(char opcode) const { return code == opcode; }\n int decode(std::vector<char>::const_iterator& it, std::ostream& out=std::cout) const {\n out << name; \n ++it;\n for (int i{bytes-1}; i; --i) {\n out << static_cast<unsigned>(*it++);\n }\n out << '\\n';\n return bytes;\n }\n};\n\nconstexpr std::array<Opcode,2> instructions {\n { 0x10, 2, \"STOP $\" },\n { 0x76, 2, \"HALT \" },\n};\n</code></pre>\n\n<h2>Pass a pair of iterators to the dissemble function</h2>\n\n<p>As mentioned before, you can pass a pair of iterators to the <code>disassemble</code> function. Using that plus the class above:</p>\n\n<pre><code>int disassembleOne(std::vector<char>::const_iterator& it, std::vector<char>::const_iterator& end){\n auto op{std::find(instructions.begin(), instructions.end(), *it)};\n if (op == instructions.end()) {\n std::cout << \"Instruction not found\\n\";\n it = end;\n return 0; // instruction not found or off the end of the passed array\n }\n if (std::distance(it, end) < op->bytes) {\n std::cout << \"Not enough bytes left to decode \" << op->name << '\\n';\n it = end;\n return 0; // instruction not found or off the end of the passed array\n }\n return op->decode(it);\n}\n</code></pre>\n\n<p>Now <code>main</code> becomes very simple:</p>\n\n<pre><code>int main(){\n const std::vector<char> char_vect = {0x76, 0x10, 0x20, 0x10}; // Fill vector of char\n auto end{char_vect.cend()};\n\n for (auto it{char_vect.cbegin()}; it != end; disassembleOne(it, end)) {\n }\n}\n</code></pre>\n\n<p>Another way to do this would be to put more of the processing in the <code>Opcode</code> itself -- it would make sense that each opcode would know how to decode itself.</p>\n\n<h2>Be clear about caller expectations</h2>\n\n<p>This code, as with the original code, expects that the <code>it</code> being passed is a valid iterator that is not the end. It is good to document that in comments in the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T19:17:34.697",
"Id": "416546",
"Score": "0",
"body": "The loop in `main` doesn't use the result of the call to `disassembleOne`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T19:32:05.553",
"Id": "416550",
"Score": "0",
"body": "@RolandIllig It doesn't need to use the return value because the iterator, which is passed by reference, is updated within the function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:12:56.343",
"Id": "215358",
"ParentId": "215349",
"Score": "12"
}
},
{
"body": "<p>I think the big <code>switch</code> is a problem. Consider a more data-driven approach where each opcode is described by a struct:</p>\n\n<pre><code>struct OpCode\n{\n unsigned char command_byte;\n unsigned char mask; // if only a subset of bits determine command\n unsigned char length;\n // other members as needed - e.g. a pointer to the \"print\" function\n};\n</code></pre>\n\n<p>Now, the code that reads instructions can determine whether the command is unterminated, without needing to repeat the logic for every multi-byte opcode.</p>\n\n<p>I've included the <code>mask</code> so that we don't encode every single instruction (e.g. <code>ld R1, R2</code> encodes the source and destination registers in the bits of a single-byte command; it would be tedious and error-prone to write them all separately here).</p>\n\n<p><s>The simple <code>length</code> value I've shown isn't quite enough, given that the Game Boy's LR35902 processor supports the 0xCB prefix for extended Z80 instructions - we might want to handle that outside of the normal flow, and use it to switch between different instruction tables.</s><br>\nWe get away with a simple <code>length</code> value here, because the only prefix instruction supported by the Game Boy's LR35902 processor is 0xCB, which is always followed by a single-byte instruction. If we were decoding Z80 instructions (with ED prefix), then we'd need something a little more sophisticated.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:29:34.830",
"Id": "215362",
"ParentId": "215349",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "215358",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:12:57.923",
"Id": "215349",
"Score": "11",
"Tags": [
"c++",
"error-handling",
"iterator",
"assembly",
"serialization"
],
"Title": "Decoding assembly instructions in a Game Boy disassembler"
} | 215349 |
<p>This is not a task, but I want to know what the general consensus is on functional programming. Particularly functional programming in Python.</p>
<p>The two snippets of code I am comparing are the following.</p>
<pre><code>if files:
if isinstance(files, basestring):
pattern_good = check_if_exists(files)
else:
pattern_good = all(map(lambda file_pattern: check_if_exists(file_pattern), files))
</code></pre>
<p>VS</p>
<pre><code>if files:
if isinstance(files, basestring):
pattern_good = check_if_exists(files)
else:
pattern_good = True
for file_pattern in files:
pattern_good = pattern_good and check_if_exists(file_pattern)
</code></pre>
<p>Which is more readable and maintainable? </p>
<p>From a personal preference POV, using functional programming is more fun and convenient IMO. It's less characters to type.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:27:53.917",
"Id": "416505",
"Score": "0",
"body": "Not an answer, but what is `pattern_good = pattern_good and check_if_exists(file_pattern)` meant to do? As soon as `check_if_exists()` returns `False`, `pattern_good` can never become True again (`False and True` = `False`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:31:20.437",
"Id": "416507",
"Score": "0",
"body": "Both of the snippets receive a single file pattern or a list/set/iterable of file patterns and check if all of them are valid. I could breakout of the loop early in the second snippet if one of the file patterns is invalid, but to keep it consistent with the first snippet, I don't(as I don't know how all() is implemented)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:52:51.590",
"Id": "416514",
"Score": "1",
"body": "@Aditya `all` breaks out of the loop (is lazy)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:55:20.943",
"Id": "416525",
"Score": "1",
"body": "The way you have worded the question and the title, it sounds like you are asking for opinions about functional programming in general, with two sketchy code excerpts acting merely as examples. Please reword your question to state in detail what the code accomplishes, so that we can review your solutions rather than giving generic opinions. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:58:16.290",
"Id": "416527",
"Score": "0",
"body": "You didn't provide the complete working code for us to review."
}
] | [
{
"body": "<ol>\n<li><p>You can simplify the function you pass to <code>map</code>.</p>\n\n<pre><code>pattern_good = all(map(check_if_exists, files))\n</code></pre></li>\n<li><p>Neither is better, as <code>map</code> is in a state of pseudo-deprecation and the other code is hard to read.</p>\n\n<p>Instead use iterator based programming, and is what I find to be one of the best parts of Python.</p>\n\n<p>And so I'd use a comprehension instead of either of these.</p></li>\n</ol>\n\n\n\n<pre><code>if files:\n if isinstance(files, basestring):\n files = [files]\n pattern_good = all(check_if_exists(f) for f in files)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:30:43.130",
"Id": "416524",
"Score": "1",
"body": "@Carcigenicate Yes, however since [list comprehensions](https://docs.python.org/3/glossary.html#term-list-comprehension), [dictionary comprehensions](https://www.python.org/dev/peps/pep-0274/) and set comprehensions are called comprehensions I find it easier to call them all comprehensions. And leads to strange cases of what do you call a [async generator comprehension/expression](https://www.python.org/dev/peps/pep-0530/#asynchronous-comprehensions)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:47:21.620",
"Id": "215356",
"ParentId": "215352",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:21:25.250",
"Id": "215352",
"Score": "-2",
"Tags": [
"python",
"python-2.x",
"functional-programming",
"comparative-review"
],
"Title": "Functional vs non functional approach in python"
} | 215352 |
<h1>Summary</h1>
<blockquote>
<p>In a block storage system, new data is written in blocks. We are going to represent the flash memory as one sequential array. We have a list of block writes coming in the form of arrays of size 2: <code>writes[i] = [first_block_written, last_block_written]</code>.</p>
<p>Each block has a rewrite limit. If rewrites on a block reach a certain specified threshold we should run a special diagnostic.</p>
<p>Given <code>blockCount</code> (an integer representing the total number of blocks), <code>writes</code> (the list of block-write arrays of size 2), and <code>threshold</code>, your task is to return the list of disjoint block segments, each consisting of blocks that have reached the rewrite threshold. The list of block segments should be sorted in increasing order by their left ends.</p>
</blockquote>
<h1>Examples</h1>
<blockquote>
<p>For <code>blockCount = 10, writes = [[0, 4], [3, 5], [2, 6]]</code>, and <code>threshold = 2</code>, the output should be <code>blockStorageRewrites(blockCount, writes, threshold) = [[2, 5]]</code>.</p>
<p>After the first write, the blocks <code>0, 1, 2, 3</code> and <code>4</code> were written in once;
After the second write, the blocks 0, 1, 2 and 5 were written in once, and the blocks <code>3</code> and <code>4</code> reached the rewrite threshold;
After the final write, the blocks <code>2</code> and <code>5</code> reached the rewrite threshold as well, so the blocks that should be diagnosed are <code>2, 3, 4</code> and <code>5</code>.
Blocks <code>2, 3, 4</code> and <code>5</code> form one consequent segment <code>[2, 5]</code>.</p>
<p>For <code>blockCount = 10</code>, <code>writes = [[0, 4], [3, 5], [2, 6]]</code>, and <code>threshold = 3</code>, the output should be
<code>blockStorageRewrites(blockCount, writes, threshold) = [[3, 4]]</code></p>
<p>For <code>blockCount = 10</code>, <code>writes = [[3, 4], [0, 1], [6, 6]]</code>, and <code>threshold = 1</code>, the output should be
<code>blockStorageRewrites(blockCount, writes, threshold) = [[0, 1], [3, 4], [6, 6]]</code></p>
</blockquote>
<h1>Constraints</h1>
<ul>
<li><code>1 ≤ blockCount ≤ 10**5</code></li>
<li><code>0 ≤ writes.length ≤ 10**5</code></li>
<li><code>writes[i].length = 2</code></li>
<li><code>0 ≤ writes[i][0] ≤ writes[i][1] < blockCount</code></li>
</ul>
<h1>First try</h1>
<pre><code>from itertools import groupby
def group_blocks(num_writes, threshold):
i = 0
for key, group in groupby(num_writes, lambda x : x >= threshold):
# This is faster compared to len(list(g))
length = sum(1 for _ in group)
if key:
yield [i, i + length - 1]
i += length
def blockStorageRewrites(blockCount, writes, threshold):
num_writes = [0] * blockCount
for lower, upper in writes:
for i in range(lower, upper + 1):
num_writes[i] += 1
return list(group_blocks(num_writes, threshold))
</code></pre>
<p>Here I just do exactly what is asked, I create an array of blockCount size, loop over the writes and lastly group the consecutive ranges with <code>itertoos.groupby</code></p>
<h1>After trying to optimize</h1>
<p>I'm not quite sure what the complexity was, but I tried to lessen the load, yet I still didn't pass the TLE constraints</p>
<pre><code>def get_bad_blocks(blockCount, writes, threshold):
cons = False
u = l = -1
for i in range(blockCount):
count = 0
for lower, upper in writes:
if lower <= i <= upper:
count += 1
if count >= threshold:
if not cons:
cons = True
l = i
u = -1
break
else:
u = i - 1
cons = False
if u != -1 and l != -1:
yield [l, u]
l = -1
if cons:
yield [l, i]
def blockStorageRewrites(blockCount, writes, threshold):
return list(get_bad_blocks(blockCount, writes, threshold))
</code></pre>
<h1>Questions</h1>
<p>You can review any and all, but preferably I'm looking for answers that:</p>
<ul>
<li>Tell me if my first example is readable</li>
<li>I'm less concerned about readability in my second try, and more interested in speed</li>
<li>Please ignore the <code>PEP8</code> naming violations as this is an issue with the programming challenge site</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:47:11.153",
"Id": "416509",
"Score": "1",
"body": "I don't think it's possible to give an \"answer\" addressing the performance issue — your current algorithm is unsalvageable. Consider what would happen in a realistic scenario where `blockCount=1000000`. The very first thing you'd do is loop `for i in range(1000000)`! That *cannot possibly* be part of a valid solution. You need to come up with an algorithm that doesn't take `O(blockCount)` time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:51:24.673",
"Id": "416512",
"Score": "0",
"body": "The comment \"should be faster compared to len(list(g))\" makes me think you should be doing some performance tests :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:52:44.210",
"Id": "416513",
"Score": "0",
"body": "@Quuxplusone probably, but I fail to see how this can be done without looping over the entire blockcounts... hence the asking for a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:53:29.460",
"Id": "416515",
"Score": "0",
"body": "@Peilonrayz I have tested that locally, it should be faster because it doesn't have to construct the list as far as I can tell"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:10:13.580",
"Id": "416517",
"Score": "2",
"body": "I don't have time to check now, but my guess is that you would want to use a (default)dict with only those blocks that are encountered in `writes`. If it is a starting block, add +1, if it's the end block, subtract 1. Then go over the values with `itertool.accumulate` to get the numbers of writes between blocks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:15:16.937",
"Id": "416519",
"Score": "0",
"body": "@Georgy That might be a good approach, but wouldn't it still be O(n**2) for looping over writes and then looping again with accumulate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:17:51.717",
"Id": "416520",
"Score": "0",
"body": "@Ludisposed: You say Georgy's algorithm is `O(n**2)`... but what is `n`? There is no `n` in your problem statement. (This is a real hint, not merely pedantry. You have misled yourself by thinking in terms of an `n` that doesn't exist. Think in terms of variables that *do* exist, and see where it leads you.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:20:47.890",
"Id": "416521",
"Score": "0",
"body": "Also, I should add: two `O(n)` loops (once to loop over writes and once to accumulate) doesn't make an `O(n*n)` algorithm — it makes an `O(n+n) = O(n)` algorithm. Things become quadratic only when the loops are *nested* one inside the other."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:23:51.140",
"Id": "416522",
"Score": "0",
"body": "@Quuxplusone Thnx for that! I am confusing myself thinking in Big O"
}
] | [
{
"body": "<p>First off when you're optimizing code you need to know what to optimize. At first I thought the problem code was not the <code>groupby</code>, but instead the creation of <code>num_writes</code>. And so I changed your code to be able to find the performance of it.</p>\n\n<pre><code>import cProfile\nimport random\n\nfrom itertools import groupby\n\ndef group_blocks(num_writes, threshold):\n i = 0\n for key, group in groupby(num_writes, lambda x : x >= threshold):\n # This is faster compared to len(list(g))\n length = sum(1 for _ in group)\n if key:\n yield [i, i + length - 1]\n i += length\n\n\ndef build_writes(block_count, writes):\n num_writes = [0] * block_count\n for lower, upper in writes:\n for i in range(lower, upper + 1):\n num_writes[i] += 1\n return num_writes\n\n\ndef blockStorageRewrites(blockCount, writes, threshold):\n num_writes = build_writes(blockCount, writes)\n return list(group_blocks(num_writes, threshold))\n\n\nblock_count = 10**5\nwrites = []\nfor _ in range(10**4):\n a = random.randrange(0, block_count)\n b = random.randrange(a, block_count)\n writes.append([a, b])\n\n\ncProfile.run('blockStorageRewrites(block_count, writes, 10**4)')\n</code></pre>\n\n<p>Resulting in the following profile:</p>\n\n<pre><code> 200008 function calls in 25.377 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.002 0.002 25.377 25.377 <string>:1(<module>)\n 100001 0.019 0.000 0.025 0.000 lus.py:10(<genexpr>)\n 1 25.342 25.342 25.342 25.342 lus.py:16(build_writes)\n 1 0.000 0.000 25.375 25.375 lus.py:24(blockStorageRewrites)\n 1 0.000 0.000 0.033 0.033 lus.py:6(group_blocks)\n 100000 0.007 0.000 0.007 0.000 lus.py:8(<lambda>)\n 1 0.000 0.000 25.377 25.377 {built-in method builtins.exec}\n 1 0.007 0.007 0.033 0.033 {built-in method builtins.sum}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n</code></pre>\n\n<p>Changing the code as per <a href=\"https://codereview.stackexchange.com/q/215355/42401#comment416517_215355\">Georgy's comment</a> to:</p>\n\n<pre><code>def build_writes(block_count, writes):\n num_writes = dict(enumerate([0] * block_count))\n for lower, upper in writes:\n num_writes[lower] += 1\n num_writes[upper] -= 1\n return list(accumulate(num_writes))\n</code></pre>\n\n<p>Gets the following profile, which is orders of magnitude faster:</p>\n\n<pre><code> 200011 function calls in 0.066 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.002 0.002 0.066 0.066 <string>:1(<module>)\n 100002 0.021 0.000 0.028 0.000 lus.py:10(<genexpr>)\n 1 0.025 0.025 0.025 0.025 lus.py:16(build_writes)\n 1 0.003 0.003 0.064 0.064 lus.py:24(blockStorageRewrites)\n 2 0.000 0.000 0.036 0.018 lus.py:6(group_blocks)\n 100000 0.008 0.000 0.008 0.000 lus.py:8(<lambda>)\n 1 0.000 0.000 0.066 0.066 {built-in method builtins.exec}\n 2 0.008 0.004 0.036 0.018 {built-in method builtins.sum}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:13:00.300",
"Id": "416590",
"Score": "1",
"body": "The `return list(accumulate(num_writes))` line should be `return list(accumulate(num_writes.values()))` else I'd be accumulating the keys. Other then that, this is a great teaching moment for me. I should know what the bottlenecks are before optimization :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:17:50.260",
"Id": "416592",
"Score": "1",
"body": "And I did had to do `(block_count + 1)` and `num_writes[upper + 1] -= 1` to make the upper bound work correctly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:06:51.817",
"Id": "416637",
"Score": "0",
"body": "@Ludisposed Ah oops :( My main aim was to show how to go about improving performance, so I didn't test at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:14:52.037",
"Id": "416639",
"Score": "0",
"body": "No problem, as the \"You should have profiled the code before starting to optimize\" was the (for me) important part of the answer. I do wonder did you find any other mistakes, simplifications or just quit after profiling?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:19:34.540",
"Id": "416640",
"Score": "1",
"body": "@Ludisposed I quit after profiling, but the first code looks good otherwise. If there wasn't a TLE then I'd say the original code is good and say to stop there. If there's another TLE then I'd look into it more, but I think 25 seconds -> 0.5 would mean there isn't one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:24:29.343",
"Id": "416643",
"Score": "0",
"body": "Thnx! One final note... just nitpicking here ;), that `dict(enumerate)` is superfluous the same can be achieved by a `list` -> `[0] * (block_count + 1)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:26:29.310",
"Id": "416645",
"Score": "0",
"body": "@Ludisposed Yes! Yeah I probably should have thought of that too >:( Also I don't think you need the `list` after the `accumulate`, as IIRC `groupby` works on iterators and iterables."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:17:54.070",
"Id": "215359",
"ParentId": "215355",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "215359",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T15:33:41.523",
"Id": "215355",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Block storage rewrites"
} | 215355 |
<p>So, this is for a clicker game I'm trying to build with Pokémon data drawn from the <a href="https://pokeapi.co" rel="nofollow noreferrer">PokéAPI</a>. Since I'm using <code>Vue.js</code> for the project, <code>Vuex</code> is used to store and share the data between components and I'm persisting and loading the state with <code>LocalForage</code> to <code>IndexedDb</code>.</p>
<p>When constructing a <code>Pokemon</code>-object from the <code>Pokemon</code>-class I'm having two different ways I get the data to construct the object.<br>
From the API I'll get the data structured one way and from the <code>IndexedDb</code> I get the 1to1 <code>JSON</code>-stringified version of the <code>Pokemon</code>-object. So just the raw <code>JSON</code> without the class-methods or any properties tied to other custom classes or any enums. You probably already knew that, but I didn't.<br>
(At first I was just using an <code>init</code>-method to set the async properties, but that changed when I started using <code>IndexedDb</code>)</p>
<p>That's why I got the basic <code>constructor</code> method to build the object anew from the saved object in the <code>IndexedDb</code> and a <code>constuctFromApiResponse</code> method to map the pokeapi response to my <code>Pokemon</code>-object.<br>
I'm trying to figure out what's the best way to write as little code as possible to stay DRY. (while keeping any type-inferences and other goodies that PHPStorm is able to make without much usage of JSHint (although I'm fine with adding hints, just didn't add them here everywhere because I'm going back and forth between the different constructor-approaches))</p>
<p><strong>Pokemon.js</strong></p>
<pre><code>import Item from './Item'
import { Pokedex } from 'pokeapi-js-wrapper'
import Type from './Type'
const P = new Pokedex()
/**
* @class Pokemon
*/
class Pokemon {
constructor ({
dexNum, name, level, types, baseStats, stats, sprites, hp, exp, item,
growthRate = '', catchRate = 0, evolutions = {}
}) {
Object.assign(this, {
dexNum,
name,
level,
baseStats,
stats,
hp,
exp,
sprites,
growthRate,
catchRate,
evolutions
})
/**
* @type {Type[]}
*/
this.types = types.map((type) => Type[type.name.toUpperCase()])
/**
* @type {Move[]}
*/
this.moves = []
/**
* @type {Item}
*/
this.item = item ? (item instanceof Item ? item : new Item(item)) : null
}
/* eslint-disable-next-line camelcase */
static async constructFromApiResponse ({ id, name, types, stats, base_experience, sprites }, level) {
const self = {
dexNum: id,
name,
level,
sprites,
hp: 0,
exp: 0,
item: null
}
self.types = types.map((type) => Type[type.type.name.toUpperCase()])
self.baseStats = {}
for (const stat of stats) {
self.baseStats[stat.stat.name] = stat.base_stat
}
/* eslint-disable-next-line camelcase */
self.baseStats.exp = base_experience
self.stats = self.baseStats
self.hp = self.stats.hp * level
const p = new Pokemon(self)
p.calculateStats()
await p.setGrowthRate()
await p.setCatchRate()
await p.setEvolutionChain()
return p
}
async setGrowthRate () {
this.growthRate = await this.getSpecies()
.then((response) => response.growth_rate.name)
}
async setCatchRate () {
this.catchRate = await this.getSpecies()
.then((response) => response.capture_rate)
}
async setEvolutionChain () {
const evolvesTo = (next, prevDexNum) => {
for (const ev of next) {
const details = ev.evolution_details[0]
const evolution = {
level: details.min_level,
method: details.trigger.name,
item: details.item || details.held_item,
dexnum: ev.species.url.split('/').slice(-2, -1)[0]
}
if (!this.evolutions.hasOwnProperty(prevDexNum)) {
this.evolutions[prevDexNum] = []
}
this.evolutions[prevDexNum].push(evolution)
// recurse
if (ev.hasOwnProperty('evolves_to') &&
ev.evolves_to.length > 0) {
evolvesTo(ev.evolves_to, evolution.dexnum)
}
}
}
const evoChainUrl = await this.getSpecies()
.then((response) => response.evolution_chain.url)
await P.resource(evoChainUrl)
.then((response) => evolvesTo(
response.chain.evolves_to,
response.chain.species.url.split('/').slice(-2, -1)[0])
)
}
/**
* Get species entry
*
* @returns {Promise}
*/
getSpecies () {
return P.resource('/api/v2/pokemon-species/' + this.dexNum)
}
/**
* @param toDexNum {number}
*
* @returns {Promise<void>}
*/
async evolve (toDexNum = 0) {
const evolutions = this.evolutions[this.dexNum]
let evolution = evolutions[0]
// get target evolution if there's more than one
if (toDexNum > 0) {
for (const ev of evolutions) {
if (this.evolutions.dexNum === toDexNum) {
evolution = ev
break
}
}
}
if (evolution.method === 'item' ||
(evolution.method === 'trade' && evolution.item !== null)) {
// TODO: remove held item
}
const evolved = await Pokemon.constructFromApiResponse(
await P.resource('/api/v2/pokemon/' + evolution.dexnum),
this.level
)
// re-set class properties
this.name = evolved.name
this.dexNum = evolved.dexNum
this.types = evolved.types
this.baseStats = evolved.baseStats
this.stats = evolved.stats
this.sprites = evolved.sprites
this.growthRate = evolved.growthRate
this.catchRate = evolved.catchRate
}
// [...] skipping review-unrelated methods
}
export default Pokemon
</code></pre>
<p>I was doing <code>this.name = name</code> before, but was looking for other ways to set the properties without repeating myself that much. But I don't know if the <code>Object.assign</code> method is really considered "cleaner" or better to read.<br>
Also depending on the constructor-approach, maybe there's a better way to re-set the properties for the evolution in the <code>evolve</code>-method.<br>
In addition I don't know what to do about the many function parameters. <code>eslint</code> with <code>standardjs</code> doesn't seem to have an opinion about this.</p>
<p><strong>Item.js</strong></p>
<pre><code>
/**
* @class Item
*/
class Item {
constructor ({ id, name, cost, attributes, category, sprites, quantity, effect, triggerOnHold, onUse }) {
Object.assign(this, {
id,
name,
cost,
attributes,
category,
sprites,
quantity,
effect,
triggerOnHold,
onUse
})
}
static async constructFromApiResponse ({ id, name, cost, attributes, category, sprites }, quantity, effect, triggerOnHold, onUse) {
const self = {
id,
name,
cost,
attributes,
category: category.name,
sprites,
quantity,
effect,
triggerOnHold,
onUse
}
const item = new Item(self)
return item
}
// [...] skipping review-unrelated methods
}
export default Item
</code></pre>
<p>Same thing with <code>Item</code>, although I don't have properties here that need any special treatment just yet. That's when I thought I'd have another look at <code>TypeScript</code> and saw that you can just omit the <code>constructor</code> function body when you're just doing assignments like <code>this.name = name</code>. Maybe I'll rewrite it in <code>TypeScript</code> then if that leads me to DRY-haven. But I'm not sure about that yet.</p>
<hr>
<p>The following are the two files where I'm using the two different <code>Pokemon</code>-constructor methods, for reference.</p>
<p><strong>store.js</strong></p>
<pre><code>import Item from './classes/Item'
import LocalForage from 'localforage'
import Pokemon from './classes/Pokemon'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const lf = LocalForage.createInstance({
driver: LocalForage.INDEXEDDB,
name: 'PokeClicker',
version: 1.0,
storeName: 'pokeclicker'
})
const persistPlugin = store => {
store.subscribe((mutations, state) => {
for (const key in state) {
if (!state.hasOwnProperty(key)) {
continue
}
const value = state[key]
lf.setItem(key, value)
}
})
}
const store = new Vuex.Store({
plugins: [
persistPlugin
],
state: {
bags: {
misc: [],
medicine: [],
pokeballs: [],
// machines: [],
berries: [],
// mail: [],
battle: [],
key: []
},
team: [],
box: [],
money: 0,
reputation: 0,
route: {},
opponent: {},
enemy: {}
},
mutations: {
async init (state, data) {
// init bag
for (const key in data.bags) {
if (!data.bags.hasOwnProperty(key)) {
continue
}
const bag = data.bags[key]
for (const idx in bag) {
const item = bag[idx]
data.bags[bag][key] = new Item(item)
}
}
// init team
for (const idx in data.team) {
const pkmn = data.team[idx]
if (!(pkmn instanceof Pokemon)) {
data.team[idx] = new Pokemon(pkmn)
}
}
Object.assign(state, data)
},
// [...] skipping review-unrelated methods
},
actions: {
async init ({ commit }) {
let state = {}
await lf.iterate((value, key) => {
state[key] = value
})
await commit('init', state)
}
}
})
export default store
</code></pre>
<p>In the <code>store</code>'s init action/mutation I re-set the raw <code>JSON</code> data from <code>IndexedDb</code> to the corresponding classes so I can use their methods properly after loading them.</p>
<p><strong>Explore.vue</strong></p>
<pre><code><template>
<div class="team">
<!-- Team -->
<team-pkmn
v-for="pokemon in $store.state.team"
:key="pokemon.id"
:pokemon="pokemon"
/>
</div>
<!-- [...] skipping review-unrelated code -->
</div>
</template>
<script>
import { Pokedex } from 'pokeapi-js-wrapper'
import Pokemon from '../../classes/Pokemon'
import TeamPkmn from '../Pokemon/TeamPkmn'
const P = new Pokedex()
export default {
components: {
TeamPkmn
},
data () {
return {}
},
async created () {
await this.$store.dispatch('init')
if (!this.$store.state.team.length) {
const ids = [679, 10, 13, 46, 48, 165, 167, 333, 290, 557, 736, 595, 742, 751, 349, 220, 366]
for (const id of ids.reverse()) {
const p = await Pokemon.constructFromApiResponse(
await P.resource('/api/v2/pokemon/' + id), 5
)
this.$store.state.team.push(p)
}
}
}
}
</script>
</code></pre>
<p>In the component's <code>async created</code> method I load some Pokémon from the Api, and create the <code>Pokemon</code>-object with the <code>constructFromApiResponse</code>-method, if none are in the store, so not loaded from the client's Db.</p>
| [] | [
{
"body": "<p>To answer one part of your question, I think you can assign all the properties at once with <code>Object.assign</code>:</p>\n\n<pre><code>class Pokemon {\n\n constructor(data) {\n Object.assign(this, data);\n }\n\n getStats() {\n return this.species + ' ' + this.age;\n }\n}\n\nconst json = '{\"species\":\"pikachu\", \"age\":12}'\nconst obj = JSON.parse(json);\n\nlet u = new Pokemon(obj)\nconsole.log(u.getStats()). // will log pikachu 12\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T20:53:17.493",
"Id": "215631",
"ParentId": "215357",
"Score": "2"
}
},
{
"body": "<p>I see a couple places where there is a <code>for...in</code> loop and then the first line within the block checks to see if the key is not a property - e.g.</p>\n\n<blockquote>\n<pre><code>for (const key in state) {\n if (!state.hasOwnProperty(key)) {\n continue\n }\n</code></pre>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n<pre><code>for (const key in data.bags) {\n if (!data.bags.hasOwnProperty(key)) {\n continue\n }\n</code></pre>\n</blockquote>\n\n<p>Did you consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\"><code>Object.keys()</code></a> to get the array of keys and iterating over those? Then perhaps the calls to <code>.hasOwnProperty()</code> could be eliminated.</p>\n\n<hr>\n\n<p>In the store actions method <code>init</code>, <code>state</code> is never re-assigned: </p>\n\n<blockquote>\n<pre><code>actions: {\n async init ({ commit }) {\n let state = {}\n await lf.iterate((value, key) => {\n state[key] = value\n })\n await commit('init', state)\n</code></pre>\n</blockquote>\n\n<p>You could use <code>const</code> instead of <code>let</code> to declare <code>state</code>.</p>\n\n<hr>\n\n<p>I see two nearly identical lines:</p>\n\n<blockquote>\n<pre><code>/**\n * @type {Type[]}\n */\nthis.types = types.map((type) => Type[type.name.toUpperCase()])\n</code></pre>\n</blockquote>\n\n<p>and shortly after that:</p>\n\n<blockquote>\n<pre><code>self.types = types.map((type) => Type[type.type.name.toUpperCase()])\n</code></pre>\n</blockquote>\n\n<p>if that mapping happens frequently in your code, perhaps it would be wise to abstract that arrow function into a named function that can be referenced wherever needed.</p>\n\n<hr>\n\n<p>In the callback function subscribed on the store (in <code>persistPlugin</code>) the variable <code>value</code> is only used once after it is assigned:</p>\n\n<blockquote>\n<pre><code>const value = state[key]\n lf.setItem(key, value)\n</code></pre>\n</blockquote>\n\n<p>That could be simplified to a single line:</p>\n\n<pre><code>lf.setItem(key, state[key])\n</code></pre>\n\n<p>This would require less memory and one less line.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T22:47:23.977",
"Id": "217517",
"ParentId": "215357",
"Score": "2"
}
},
{
"body": "<p>One thing that stood out for me is that you’re doing multiple HTTP calls to the same end-point during the <code>constructFromApiResponse</code> when you could just do one, i.e.</p>\n\n<pre><code>this.getSpecies().then(resp => new Pokemon({\n growthRate: resp.growth_rate.name\n , catchRate: resp.capture_rate.name\n , baseStats: resp.stats.reduce((acc, {base_stat, stat: {name}}) => {\n acc[name] = base_stat\n return acc\n }, {exp: resp.base_experience}) // just an example of property conversion\n , // etc.\n})\n</code></pre>\n\n<p>One should always strive for minimizing the number of HTTP calls.</p>\n\n<p>Also I would consider using the same constructor for both, from HTTP and local, and doing the property conversions for HTTP in there.</p>\n\n<p>Speaking of properties, there are other options in case you’re interested. One is a method:</p>\n\n<pre><code>// inside class definition\nhp() { this.baseStats.hp * this.level }\n</code></pre>\n\n<p>and another is a getter:</p>\n\n<pre><code>get hp() { this.baseStats.hp * this.level }\n</code></pre>\n\n<p>where the former needs to be executed (<code>poke.hp()</code>), while the latter acts more like a computed property (<code>poke.hp</code>). Though neither wouldn’t get serialized into JSON.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T01:20:29.670",
"Id": "217524",
"ParentId": "215357",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:09:04.353",
"Id": "215357",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"async-await",
"vue.js",
"pokemon"
],
"Title": "Class constructor with async properties set from poke-api"
} | 215357 |
<p>We have a department in our org that generates a lot of data in flat files, all with different formats. We are now trying to sort this data out and load into a database. As step 1, I am trying to identify the structure(separator, header, fields, datatypes, etc) of the files using a python script. This is my first time doing python programming, also I am programming after a long time. While this code gives me the output I need, how can I make it better?</p>
<p>The code looks at the directory C:\logs and loops through all files in the directory first to identify a separator and header, then if the separator is space it will check if it is a fixed width file. use the information here to identify all fields and their related attributes and prints out a mapping file. It also combines multiple mapping files into one mapping file if possible (this allows the mapping sheet to accommodate format variances across multiple files). I want to be able to use this on Excel files later. </p>
<p>SAMPLE INPUT: </p>
<p><a href="https://i.stack.imgur.com/2daBV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2daBV.png" alt="Input"></a><br>
Example Input in txt format below. However this code is supposed to identify 'any character' delimited or fixed width files. Files can have any number of header lines, etc.</p>
<pre><code>Some Title
Grp IDS Date Time Weight
1 3559 3-10-19 8:45 1159.4
1 3680 3-10-19 8:40 1861.2
1 3844 3-10-19 8:36 2039.4
1 3867 3-10-19 8:38 1861.2
1 3985 3-10-19 8:40 1729.2
1 4009 3-10-19 8:46 1883.2
1 4014 3-10-19 8:36 1920.6
1 4044 3-10-19 8:41 1689.6
1 4058 3-10-19 8:39 1764.4
1 4192 3-10-19 8:43 1775.4
1 4344 3-10-19 8:43 1449.8
1 4354 3-10-19 8:49 1555.4
1 4356 3-10-19 8:31 1091.2
1 4359 3-10-19 8:43 0.0
1 4361 3-10-19 8:44 1689.6
1 4365 3-10-19 8:43 1513.6
2 3347 3-10-19 8:34 1867.8
2 3860 3-10-19 8:37 1788.6
2 3866 3-10-19 8:33 1980.0
2 4004 3-10-19 8:24 1634.6
2 4020 3-10-19 8:29 1612.6
2 4086 3-10-19 8:35 1553.2
2 4139 3-10-19 8:22 1883.2
2 4145 3-10-19 8:27 1177.0
2 4158 3-10-19 8:33 0.0
2 4186 3-10-19 8:29 1586.2
2 4193 3-10-19 8:28 1746.8
2 4202 3-10-19 8:28 1870.0
2 4215 3-10-19 8:31 1104.4
2 4348 3-10-19 8:33 1628.0
2 4369 3-10-19 8:32 1392.6
2 4374 3-10-19 8:33 1394.8
</code></pre>
<p>OUTPUT: </p>
<p><a href="https://i.stack.imgur.com/ha1NR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ha1NR.png" alt="Output"></a> </p>
<pre><code># Import Libraries
import os
import csv
import re
import pandas as pd
from collections import Counter
from dateutil.parser import parse
import calendar
# Set Variables
path = "C:\Logs"
printableChars = list('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;?@[\\]^_`{|}~ \t\n\r\x0b\x0c')
skipSeperator = list('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:.!"#$%&\'()*+@[]\n\r\x0b\x0c')
masterFields=pd.DataFrame(columns=['Target Name','Source Name','Column Position','Column Width','DataType','Size','Format', 'KEY','Default','Comments','Unique', 'ImpactsGrain', 'HasNULLs'])
consolidate= True
debug=False
# Identify if any column is duplicate. It needs to be removed from further analysis
def getDuplicateColumns(df):
'''
Get a list of duplicate columns.
It will iterate over all the columns in dataframe and find the columns whose contents are duplicate.
:param df: Dataframe object
:return: List of columns whose contents are duplicates.
'''
duplicateColumnNames = set()
# Iterate over all the columns in dataframe
for x in range(df.shape[1]):
# Select column at xth index.
col = df.iloc[:, x]
# Iterate over all the columns in DataFrame from (x+1)th index till end
for y in range(x + 1, df.shape[1]):
# Select column at yth index.
otherCol = df.iloc[:, y]
# Check if two columns at x 7 y index are equal
if col.equals(otherCol):
duplicateColumnNames.add(df.columns.values[y])
return list(duplicateColumnNames)
# Identify how column values are separated within a row.
def identifySeparator(name):
if debug: print( "Currently analyzing file : " + name)
currentFile = open(path +"\\" +name, "r")
# Create a list of charecters by Line
characterFrequencies =[]
for line in currentFile:
characters = list(line)
if characters[0] == '\n':
continue
characterFrequencies.append(Counter(characters))
if debug: print(pd.DataFrame(characterFrequencies).head())
df = pd.DataFrame(characterFrequencies)
df = df.drop(columns=skipSeperator, errors='ignore') # Remove characters that are generally not used as sperators.
if debug: print("Potential Seperators")
# METHOD 1: Try to identify seperator with the understanding it should be present in every row.
dfDense = df.dropna(axis='columns')
if debug: print(dfDense.head())
Candidates = dfDense.columns
if debug: print("Number of characters present in every row : " + str(len(dfDense.columns)))
if len(dfDense.columns) == 1:
Separator = str(dfDense.columns[0])
if debug: print("Separator identified as : " + Separator + ' using METHOD 1')
else:
Separator = '-1'
if debug: print('Unable to identify seperator using METHOD 1 as 0 or multiple exist!!')
# METHOD 2: Least Variance: The count of the seperator should be more or less same across rows.
if debug: print('% of rows missing the charecter')
if debug: print(df.isna().sum()/ df.isna().count())
cleanupCandidates=df.dropna(axis='columns', thresh = (df.shape[0] + 1)*.8).fillna(-1)
if debug: print('Dropping characters not present in 80% of the columns')
if debug: print(cleanupCandidates.head())
lowestVariance = 0
spaceDetectedFlag = False
Separator2 = ''
for character in cleanupCandidates.columns:
if debug: print('**********' + character +' **********')
x = cleanupCandidates.loc[:,character].var()
if debug: print('Calculated variance : ' + str(x) )
if character == ' ':
spaceDetectedFlag = True
if debug: print('Potential position based file...')
continue
if lowestVariance >= x:
lowestVariance =x
Separator2 = character
if debug: print("Separator identified as : " + Separator2 + ' using METHOD 2')
if Separator == Separator2:
commonSep= Separator
else:
commonSep = list(set(Candidates).intersection(cleanupCandidates.columns))
if debug: print('Both methods identify '+ str(commonSep) + 'as one of the separator candidates.')
maxMode = 0
modeTable = cleanupCandidates.mode()
if len(commonSep) != 1:
print ('Multiple Common Seperator!! Use Max MODE', cleanupCandidates.columns)
if debug: print(cleanupCandidates.mode())
for column in modeTable.columns:
x = modeTable.loc[0,column]
print (column,'\'s Mode: ', x)
if x > maxMode:
commonSep = column
maxMode = x
if debug: print('Resolved ambiguity by Max Mode Method to: ', commonSep)
# Identify if header rows need to be skipped
firstRow = cleanupCandidates[commonSep].idxmax()
if debug: print('The Header is expected to be in row: ',firstRow)
return commonSep[0], firstRow
#candidates = []
#candidates.append(Counter(characters))
def identifyFixedWidth(name):
numberLines = 0
totalCharecters = 0
maxLength = 0
for line in open(path +"\\" +name, "r"):
numberLines +=1
totalCharecters += len(line)
if len(line) <= 2: numberLines -=1
if maxLength < len(line): maxLength = len(line)
avgChars =totalCharecters/numberLines
if debug: print('Sample file has '+ str(numberLines) + ' lines. There are an average '+ str(avgChars) +' charecters pe line.')
counter = 0
for line in open(path +"\\" +name, "r"):
if debug: print(str(counter) + ' has ' + str(len(line)) + ' chars')
if len(line)<= avgChars*.9 or len(line)>=avgChars*1.1:
if debug: print('Line '+ str(counter) +': Maybe part of header and needs to be skipped')
counter+=1
else:
if debug: print('Header found at column :', counter)
break
# Figure out Column Start and stop positions
rowCounter = -1
colPos = []
for line in open(path +"\\" +name, "r"):
rowCounter+=1
if rowCounter < counter: continue
blanks=[m.start() for m in re.finditer(' ', line)]
if len(blanks)>2:
colPos.append([m.start() for m in re.finditer(' ', line)])
if rowCounter<=5:
if debug: print(colPos[-1])
# Intersection
Common = list(set.intersection(*map(set, colPos)))
if debug: print('Potential field separator positions: ',Common)
# Remove sequential values
newCommon = []
for x in Common:
if ((x-1) not in Common):newCommon.append(x)
newCommon.append(maxLength)
if debug: print('Field separator positions identified as :',newCommon)
#Calculate Width
width=[]
range = len(newCommon)
i=0
for x in newCommon[0:range-1]:
width.append(newCommon[i+1]-newCommon[i])
i+=1
if debug: print('Column Lengths:', width)
return counter,width
# Parse File and collect Field Information
def identifyFields(name,separator, HeaderPos, width):
if debug: print( "Currently analyzing column structure for file : " + name)
currentFile = path +"\\" +name
if separator !='FWF':
df = pd.read_csv(currentFile, sep=separator, parse_dates=False, skiprows=HeaderPos)
else:
df = pd.read_fwf(currentFile, parse_dates=False, header=HeaderPos, widths=width)
if debug: print('Opening File as Fixed Width')
dupCols = getDuplicateColumns(df)
df = df.drop(columns=dupCols)
fieldStructure = pd.DataFrame(index=[df.columns], columns=['Target Name','Source Name','Column Position','Column Width','DataType','Size','Format', 'KEY','Default','Comments','Unique', 'ImpactsGrain', 'HasNULLs'])
totalRowCount = df.shape[0]
totalDupRows = df[df.duplicated()].shape[0]
if totalDupRows > 0:
print('!!!!!!!!!WARNING!!!!!!!! This file contains ' + str(totalDupRows) + ' duplicate rows!')
if len(dupCols)> 0:
fieldStructure.loc['Duplicate','Target Name'] = 'DUPLICATE Fields:' + '-'.join(dupCols)
print('!!!!!!!!!WARNING!!!!!!!! The following columns were identified as a duplicate column and will be removed from the final mapping')
if debug: print(dupCols)
if debug: print('Columns in the Dataset',df.columns)
if debug: print(fieldStructure)
counter = 1
for fieldName in df.columns:
print('Processing Field: ' + fieldName)
fieldStructure.loc[fieldName,'Source Name'] = fieldName
fieldStructure.loc[fieldName,'Target Name'] = fieldName
fieldStructure.loc[fieldName,'Column Position'] = counter
if separator =='FWF':fieldStructure.loc[fieldName,'Column Width'] = width[counter-1]
counter +=1
fieldStructure.loc[fieldName,'DataType'] = str(df[fieldName].dtypes).replace('64', '',1)
if str(df[fieldName].dtypes).replace('64', '',1) == 'float':
if df[fieldName].fillna(1).apply(float.is_integer).all():
fieldStructure.loc[fieldName,'DataType'] = 'int'
else:
fieldStructure.loc[fieldName,'DataType'] = 'float'
format = ''
dateFlg = True
if df[fieldName].isnull().all(): fieldStructure.loc[fieldName,'DataType'] = 'Unknown'
if df[fieldName].dtypes == 'object':
fieldValue = str(df.loc[df.loc[:,fieldName].first_valid_index(),fieldName])
if debug: print('First non NaN Index & Value: ',str(df.loc[:,fieldName].first_valid_index()), str(fieldValue))
try:
dateTime = parse(fieldValue,fuzzy=False)
except ValueError:
dateFlg = False
if dateFlg == True:
shortMonth = False
shortDate = False
if debug: print('Input Date:', fieldValue)
if debug: print('Interpreted Date',dateTime)
yrSt = fieldValue.find(str(dateTime.year))
if debug: print('Year Start Position: ',yrSt)
format = fieldValue.replace(str(dateTime.year), 'yyyy',1)
if yrSt == -1:
format = fieldValue.replace(str(dateTime.year)[2:], 'yy',1)
if debug: print('Year format: ',format)
noMonth=False
monSt = format.find(str(dateTime.month).zfill(2))
if debug: print('2 Digit Month Position:',monSt)
format = format.replace(str(dateTime.month).zfill(2), 'mm',1)
if monSt == -1:
monSt1 = format.find(str(dateTime.month))
if monSt1 != -1:
shortMonth = True
format = format.replace(str(dateTime.month).zfill(1), 'mm',1)
else:
noMonth = True
#Check if Month Name or Abbreviations are used
if noMonth:
abbr=map(str.upper,calendar.month_abbr[1:])
fmnth=map(str.upper,calendar.month_name[1:])
if debug: print(abbr)
for mon in abbr:
if(mon in format.upper()):
if debug: print('Month Abbr used in this date format', mon)
noMonth = False
format = format.replace(mon, 'MMM',1)
for mon in fmnth:
if(mon in format.upper()):
if debug: print('Month Name used in this date format', mon)
noMonth = False
format = format.replace(mon, 'MMMM',1)
if debug: print('Month Format: ',format)
daySt = format.find(str(dateTime.day).zfill(2))
if debug: print('2 Digit Day Position: ',daySt)
format = format.replace(str(dateTime.day).zfill(2), 'dd',1)
if daySt == -1:
daySt1 = format.find(str(dateTime.day))
if daySt1 != -1 and not noMonth:
shortDate = True
format = format.replace(str(dateTime.day), 'dd',1)
if debug: print('Day format: ',format)
hhSt = format.find(str(dateTime.hour).zfill(2))
if debug: print('2 digit Hour Position: ',hhSt)
format = format.replace(str(dateTime.hour).zfill(2), 'HH',1)
if debug: print('2 digit Hour Format: ',format)
if hhSt == -1:
hhSt = format.find(str(dateTime.hour).zfill(2))
if debug: print('24 Hour Format Position: ',hhSt)
format = format.replace(str(dateTime.hour).zfill(2), 'HH',1)
if debug: print('24 Hour Format: ',format)
if hhSt == -1:
hhSt = format.find(str(dateTime.hour))
if debug: print('1 digit Hour Position: ',hhSt)
format = format.replace(str(dateTime.hour), 'H',1)
mnSt = format.find(str(dateTime.minute).zfill(2))
if debug: print('Mins Position:',mnSt)
format = format.replace(str(dateTime.minute).zfill(2), 'MM',1)
if debug: print('Mins Format: ',format)
secSt = format.find(str(dateTime.second).zfill(2))
if debug: print('Seconds Position',secSt)
format = format.replace(str(dateTime.second).zfill(2), 'SS',1)
if debug: print('Seconds Format',format)
if shortMonth or shortDate:
format = format + ';' + format.replace(str('mm'), 'm',1).replace(str('dd'), 'd',1)
if debug: print('Date Format Identified as :', format)
fieldStructure.loc[fieldName,'DataType'] = 'Timestamp'
else:
fieldStructure.loc[fieldName,'DataType'] = 'String'
if df[fieldName].isnull().all():
fieldStructure.loc[fieldName,'Size'] = 0
else:
fieldStructure.loc[fieldName,'Size'] = df[fieldName].map(str).apply(len).max()
fieldStructure.loc[fieldName,'Format'] = format
fieldStructure.loc[fieldName,'Unique'] = df[fieldName].is_unique
dftmp = df.drop(columns=fieldName)
# if debug: print(dftmp.head())
dupRows = dftmp[dftmp.duplicated()].shape[0]
if dupRows > totalDupRows:
grainFlg = True
else:
grainFlg = False
fieldStructure.loc[fieldName,'ImpactsGrain'] = grainFlg # NEEDS MORE ANALYSIS
if df[fieldName].isna().sum() > 0:
fieldStructure.loc[fieldName,'HasNULLs'] = True
else:
fieldStructure.loc[fieldName,'HasNULLs'] = False
if debug: print(df.columns)
if debug: print(fieldStructure)
return fieldStructure
# Merge all File Mappings to master mapping file.
def addToMaster(fieldStructure):
if debug: print('Consolidating Multiple Mappings.....')
#if debug: print(fieldStructure.loc[:,'Target Name'])
#masterFields
#masterFields.loc[:,'Format']='XXX'
masterFields['Format'] = masterFields.Format.apply(lambda x: x if not (pd.isnull(x) or x=='') else 'XXX')
if debug: print(masterFields['Format'])
for index, row in fieldStructure.iterrows():
#if debug: print(row)
masterFields.loc[row['Target Name'],'Target Name']=row['Target Name']
masterFields.loc[row['Target Name'],'Source Name']=row['Source Name']
if pd.isnull(masterFields.loc[row['Target Name'],'Column Position']):
masterFields.loc[row['Target Name'],'Column Position']=row['Column Position']
else:
if masterFields.loc[row['Target Name'],'Column Position']!=row['Column Position']:
if debug: print(bcolors.WARNING + "WARNING: Column positions vary by file."+ bcolors.ENDC)
if pd.isnull(masterFields.loc[row['Target Name'],'Column Width']):
masterFields.loc[row['Target Name'],'Column Width']=row['Column Width']
else:
if masterFields.loc[row['Target Name'],'Column Width']<row['Column Width']:
if debug: print('!!!!!!!!!WARNING!!!!!!!! Column Widths vary by file.Merge may not be accurate')
masterFields.loc[row['Target Name'],'Column Width']=row['Column Width']
if pd.isnull(masterFields.loc[row['Target Name'],'DataType']):
masterFields.loc[row['Target Name'],'DataType']=row['DataType']
else:
if masterFields.loc[row['Target Name'],'DataType']!=row['DataType']:
if row['DataType']== 'float': masterFields.loc[row['Target Name'],'DataType'] = float
if row['DataType']=='Timestamp': masterFields.loc[row['Target Name'],'DataType'] = Timestamp
if pd.isnull(masterFields.loc[row['Target Name'],'Size']):
masterFields.loc[row['Target Name'],'Size']=row['Size']
else:
if masterFields.loc[row['Target Name'],'Size']<row['Size']:
masterFields.loc[row['Target Name'],'Size']=row['Size']
if pd.isnull(masterFields.loc[row['Target Name'],'Format']):masterFields.loc[row['Target Name'],'Format']='XXX'
if not(pd.isnull(row['Format']) or row['Format']==''):
if debug: print('Checking if ',row['Format'], ' not in ', masterFields.loc[row['Target Name'],'Format'])
if debug: print('Size of Format value is:', str(len(row['Format'])))
if debug: print('Check to see if the value is NULL: ', pd.isnull(row['Format']))
if row['Format'] not in masterFields.loc[row['Target Name'],'Format']:
masterFields.loc[row['Target Name'],'Format'] += row['Format']
masterFields.loc[row['Target Name'],'Format'] += ';'
if pd.isnull(masterFields.loc[row['Target Name'],'Unique']):
masterFields.loc[row['Target Name'],'Unique'] = row['Unique']
else:
if not(row['Unique']): masterFields.loc[row['Target Name'],'Unique'] = False
if pd.isnull(masterFields.loc[row['Target Name'],'ImpactsGrain']):
masterFields.loc[row['Target Name'],'ImpactsGrain'] = row['ImpactsGrain']
else:
if row['ImpactsGrain']: masterFields.loc[row['Target Name'],'ImpactsGrain'] = True
if pd.isnull(masterFields.loc[row['Target Name'],'HasNULLs']):
masterFields.loc[row['Target Name'],'HasNULLs'] = row['HasNULLs']
else:
if row['HasNULLs']: masterFields.loc[row['Target Name'],'HasNULLs'] = True
if debug: print(masterFields)
def printMapping(fileNameParts,separator,HeaderPos,fieldStructure):
fileNameParts[len(fileNameParts) -1] = 'map'
name='.'.join(fileNameParts)
name+='.csv'
if debug: print(name)
currentFile = open(path +"\\" +name, "w+")
currentFile.write('Source file directory,' + path + '\n')
currentFile.write('Source file pattern,' + 'TBD' + '\n')
currentFile.write('Target table name,' + '[ENTER TABLENAME]' + '\n')
if separator != ' ':
currentFile.write('Field Seperator,"' + separator + '"\n')
else:
currentFile.write('Field Seperator,"' + 'FWF' + '"\n')
currentFile.write('Skip Rows,' + str(HeaderPos) + '\n' + '\n')
currentFile.close()
fieldStructure.to_csv(path +"\\" +name, mode='a', index= False, header= True )
# Read all files in directory
files = os.listdir(path)
masterSep='INIT'
textFormats = ["txt","csv","log"]
#Print all files in directory
for name in files:
print('>>>>>> CURRENTLY PROCESSING FILE : ',name)
fileNameParts = str.split(name, ".")
if debug: print(fileNameParts)
width=[0]
if '.map.' in name:
print('Skip current file (Output File): ',name)
continue
if fileNameParts[len(fileNameParts) -1] in textFormats:
if debug: print("This is a text file.")
separator, HeaderPos = identifySeparator(name)
if separator != '-1':
print('Seperator successfully identified as: ' + separator)
else:
print('Unable to identify Separator. This file will be skipped!')
continue
if separator == ' ':
print('This file may be a fixed width file')
HeaderPos, width=identifyFixedWidth(name)
if debug: print('Width Array ',width, len(width))
if len(width)<=1:
print('This file may be space seperated however it is not a fixed width file.')
continue
else:
separator = 'FWF'
fieldStructure = identifyFields(name, separator, HeaderPos, width)
if masterSep !='INIT':
if (masterSep != separator) and consolidate:
print('These files have different seperators so results will not be consolidated')
consolidate=False
else:
masterSep = separator
print('Field Structure identified successfully')
# Print Mapping Sheet
# if debug: print(fieldStructure)
if consolidate: addToMaster(fieldStructure)
printMapping(fileNameParts,separator,HeaderPos,fieldStructure)
else:
print('Skip current file (Unknown Format) : ',name)
#Prepare to print consolidated results
if consolidate:
fileNameParts[0] = 'FinalMappingSheet'
masterFields['Format'] = [x[3:] for x in masterFields['Format']]
printMapping(fileNameParts,separator,HeaderPos,masterFields)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T17:53:38.470",
"Id": "416532",
"Score": "2",
"body": "I'd be very interested to see a pythonic refactoring of the debug statements"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T19:17:16.673",
"Id": "416545",
"Score": "1",
"body": "Can you include the example input as text instead of an image? This way reviewers don't need to type out your whole file..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T20:03:29.170",
"Id": "416553",
"Score": "0",
"body": "Add the example input as text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T19:09:14.543",
"Id": "417044",
"Score": "0",
"body": "Can someone let me know if there is a better way to get the date format string"
}
] | [
{
"body": "<p>This is going to be relatively long, but I don't have a TL;DR section</p>\n\n<h1><code>if debug: print</code></h1>\n\n<p>Whenever you see code repeated like this, it's quite often you can refactor it into either a function, or there's a builtin to support it. Fortunately, the <a href=\"https://docs.python.org/3/howto/logging.html\" rel=\"nofollow noreferrer\"><code>logging</code></a> module makes this quite simple. You do lose a bit of speed over the <code>if</code> statement, but it's a much easier call to read and visually separate from the rest of your code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import logging\nimport sys\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n# I'm specifying sys.stdout because default is sys.stderr which\n# may or may not be viewable in your console, whereas sys.stdout\n# is always viewable\nlogger.addHandler(logging.StreamHandler(stream=sys.stdout))\n\nfor i in range(10):\n if i > 8:\n logger.debug(f'{i}')\n # do other things\n\n9\n\n# rather than\nfor i in range(10):\n if i > 8:\n if debug:\n print(i)\n # do other things\n\n9\n\n</code></pre>\n\n<p>You can set this up with a <code>level</code> mapping to point to other logging levels:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>levels = {True: logging.DEBUG,\n False: logging.INFO}\n\ndebug = True\n\nlogger.setLevel(levels[debug])\n</code></pre>\n\n<p>This way you don't lose your original way of keeping track of your debug status. The major benefit is that it doesn't visually collide with the rest of your flow control. When you have a ton of <code>if</code> statements, visually sifting through to ignore <code>if debug</code> becomes a major pain.</p>\n\n<p>The way to fix this is to find <code>if debug print</code> and replace it with <code>logger.debug</code>, and everywhere else <code>print</code> is needs to be <code>logger.info</code>, <code>logger.warn</code>, or <code>logger.exception</code> (which will include a stack trace for you :) ). You'll need to fix the print arguments as well, how to do that is below.</p>\n\n<h2>Using <code>logger</code> with objects</h2>\n\n<p>I'd probably start switching to using <a href=\"https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python\" rel=\"nofollow noreferrer\">f-strings</a>, this way you avoid string concatenation and your code is a bit more readable:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\nimport logging\nimport sys\n\ndf = pd.DataFrame([[1,2,3],[4,5,6]], columns = list('abc'))\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.StreamHandler(stream=sys.stdout))\n\n\nlogger.debug(f'My dataframe is \\n{df.head()}')\nMy dataframe is\n a b c\n0 1 2 3\n1 4 5 6\n\n# you can still use it for objects by themselves\nlogger.debug(df.head())\n a b c\n0 1 2 3\n1 4 5 6\n\n# To show logging.exception behavior\ndef f():\n raise TypeError(\"Some random error\")\n\ntry:\n f()\nexcept TypeError as e:\n logger.exception(\"An error occurred\")\n\nAn error occurred\nTraceback (most recent call last):\n File \"<stdin>\", line 2, in <module>\n File \"<stdin>\", line 3, in f\nTypeError: Some random error\n</code></pre>\n\n<h1>Opening and closing files</h1>\n\n<p>I see lots of different ways you open files:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for line in open(file):\n ...\n\nfh = open(file)\nfor line in fh:\n ...\n\n</code></pre>\n\n<p>It's best to be consistent, and the most pythonic way to <a href=\"https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\" rel=\"nofollow noreferrer\">open a file</a> is to use <a href=\"https://docs.python.org/3/reference/compound_stmts.html#with\" rel=\"nofollow noreferrer\"><code>with</code></a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>with open(file) as fh:\n for line in fh:\n ...\n\n</code></pre>\n\n<p>This removes the need to manually close the file, since even on an exception, the handle is closed and you don't have to wait for <code>fh</code> to exit function scope.</p>\n\n<h1>os.listdir vs os.scandir</h1>\n\n<p>If your directories are particularly large, it can be quite advantageous to use <code>os.scandir</code> since it produces a generator rather than a list:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>os.listdir('.')\n['newfile.py', '.Rhistory', 'VMBash.txt', '.config', 'Music', '.sparkmagic', 'transcripts.tar.gz', '.amlinstaller', 'spotify.docx', 'tree.py', '.condarc', '.docker', 'company.20190102.idx.1', 'itertools_loop.py', 'sql2019.ipynb', 'somexml.xml', 'temp'...]\n\nos.scandir('.')\n<posix.ScandirIterator object at 0x10bbb51b0>\n</code></pre>\n\n<p>For large directories, you'd have to wait for <code>listdir</code> to aggregate all of the files into memory, which could be either a) long-running or b) crash your machine (probably not but who knows). You would iterate over <code>scandir</code> with the <code>file.name</code> attribute to get back to what you had before:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for file in os.scandir('.'):\n print(file.name)\n\nnewfile.py\n.Rhistory\nVMBash.txt\n...\n</code></pre>\n\n<h1>Tracking an Index</h1>\n\n<p>If you ever find yourself doing the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>counter = 0\n\nfor x in iterable:\n something[x] = 1\n counter += 1\n</code></pre>\n\n<p>It's probably better to use <code>enumerate</code> to track the index:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>l = list('abcd')\n\nfor idx, item in enumerate(l):\n print(idx)\n\n0\n1\n2\n3\n</code></pre>\n\n<p>You can also provide a <code>start</code> kwarg to tell <code>enumerate</code> where to begin:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>l = list('abcd')\n\nfor idx, item in enumerate(l, start=1):\n print(idx)\n\n1\n2\n3\n4\n</code></pre>\n\n<p>So in your <code>identifyFields</code> function, I would definitely leverage that:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for counter, field_name in enumerate(df.columns, start=1):\n # rest of loop\n</code></pre>\n\n<h1>Counter</h1>\n\n<p>When you are iterating over your file to get character counts, you are losing speed with extra steps by converting to <code>list</code>, then checking for <code>\\n</code>, then building your Counter. <code>Counter</code> will consume a string, and <code>\\n</code> is a single string object. Move that into a separate function for separation of concerns:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def read_file(filepath):\n # It is much better practice to open files using the with context manager\n # it's safer and less error-prone\n with open(filepath) as fh:\n char_counts = []\n\n for line in fh:\n # don't construct a list, there's no need,\n # just check if startswith, which is the same\n # as line[0] == '\\n'\n if not line.startswith('\\n'):\n # Counter will consume a string\n char_counts.append(Counter(line))\n return char_counts\n\nchar_counts = read_file(name)\n</code></pre>\n\n<p>Or, a bit more succinctly as a list comprehension:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def read_file(name):\n with open(filename) as fh:\n return [Counter(line) for line in fh if not line.startswith('\\n')]\n</code></pre>\n\n<p>Where the <code>str.startwith</code> is a bit more robust for variable-length strings, as it avoids the <code>if mystring[:len(to_check)] == to_check</code> mess.</p>\n\n<h1>Checking duplicate columns</h1>\n\n<p>It might be easier to leverage <code>itertools.combinations</code> to get pairs of columns in your dataframe, then use the <code>pd.Series.all()</code> function to check the values:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># change your naming to fit with common naming standards for\n# variables and functions, pep linked below\ndef get_duplicate_columns(df):\n '''\n You are looking for non-repeated combinations of columns, so use\n itertools.combinations to accomplish this, it's more efficient and\n easier to see what you are trying to do, rather than tracking an index\n '''\n duplicate_column_names = set()\n # Iterate over all pairs of columns in df\n for a, b in itertools.combinations(df.columns, 2):\n # will check if every entry in the series is True\n if (df[a] == df[b]).all():\n duplicate_column_names.add(b)\n\n return list(duplicate_column_names)\n</code></pre>\n\n<p>This way you avoid the nested loops, and you are just checking across the boolean mask.</p>\n\n<h1>Check pandas datatype for column</h1>\n\n<p>It is both unclear and bad practice to do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if str(df[fieldName].dtypes).replace('64', '',1) == 'float':\n</code></pre>\n\n<p>To explicitly check a pandas datatype, use the <code>dtype</code> on a <code>pd.Series</code> by accessing the column directly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\n\nif df[field_name].dtype == np.float64:\n # do things\n\n</code></pre>\n\n<p>You'll need <code>numpy</code> because the dtypes for pandas inherit from <code>numpy</code> dtypes. An even clearer way to check (in case you get <code>np.float32</code> instead of <code>np.float64</code>, for example) is to leverage the <code>pandas.api.types</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\nimport pandas.api.types as pdtypes\n\nif pdtypes.is_float_dtype(df[field_name]):\n # do things\n</code></pre>\n\n<p>This might be the preferred way to go, since you are assuming that you will always get <code>float64</code>, where you might not. This also works for other types:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if pdtypes.is_integer_dtype(df[field_name]):\n pass\n\nelif pdtypes.is_object_dtype(df[field_name]):\n pass\n\nelif pdtypes.is_datetimetz(df[field_name]):\n pass\n\n# etc\n</code></pre>\n\n<h1>Checking last element in an indexed data structure</h1>\n\n<p>Instead of using <code>object[len(object) - 1]</code>, just use <code>object[-1]</code>. Negative indexing also works for counting backwards:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>x = list('abcdefg')\n\n# get the last element\nx[-1]\n'g'\n\n# get the third-to-last element\nx[-3]\n'e'\n</code></pre>\n\n<h1>Finding a substring using str.find</h1>\n\n<p>In your datetime processing logic there's a ton of the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>year_st = field_value.find(str(date_time.year))\n\nif year_st == -1:\n # do something\n</code></pre>\n\n<p>This will never evaluate to true, because <code>find</code> will never return a negative index:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>mystr = 'abcd'\n\nmystr.find('d')\n# 3\n</code></pre>\n\n<p>Likewise, later you use:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>mon_st = format.find(str(dateTime.month))\nif mon_st != -1:\n # do things\n</code></pre>\n\n<p>This will always evaluate to <code>True</code>.</p>\n\n<p>This falls under checking <code>str.endswith</code>, since you want to know if that block of text is the last element in the string:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if field_value.endswith(str(date_time.year)):\n # do things\n</code></pre>\n\n<h1>tuples vs lists</h1>\n\n<p>There are numerous places in your code where you use lists that you do not modify:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if ending not in formats:\n\n...\ndf = df.drop(columns=skipSeperator, errors='ignore')\n\n...\n</code></pre>\n\n<p>You incur extra overhead by allocating a mutable data structure:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import sys\n\nlst, tup = list(range(100)), tuple(range(100))\n\nsys.getsizeof(lst)\n1008\n\nsys.getsizeof(tup)\n848\n</code></pre>\n\n<p>With this in mind, it's better to stick with the smaller data structure.</p>\n\n<h1>Pandas Recommendations</h1>\n\n<h2>data-type checking</h2>\n\n<p>This kind of code-snippet is not something you'll want:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if str(df[fieldName].dtypes).replace('64', '',1) == 'float':\n</code></pre>\n\n<p>You're calling <code>dtypes</code>, then coercing it to a string, then replacing it, <em>then</em> comparing to a fixed string. No need, those are numpy datatypes, so just do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if df[fieldName].dtype == np.float64:\n</code></pre>\n\n<h2>str functions</h2>\n\n<p>You can refactor code snippets like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>fieldStructure.loc[fieldName,'Size'] = df[fieldName].map(str).apply(len).max()\n</code></pre>\n\n<p>To be</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>fieldStructure.loc[fieldName, 'Size'] = df[fieldName].str.len().max()\n</code></pre>\n\n<p>Since the field is already a string type, you shouldn't need to map everything with <code>str</code>, and then the <code>len</code> operation should already be supported. The latter is faster largely because of the fewer operations that need to occur:</p>\n\n<h3>timing</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>python -m timeit -s \"import pandas as pd; df = pd.DataFrame([['kladflna', 'l;adfkadf', ';aljdnvohauehfkadflan'] for i in range(1000)], columns=list(range(3)))\" 'df[2].map(str).apply(len).max()'\n1000 loops, best of 3: 506 usec per loop\n\npython -m timeit -s \"import pandas as pd; df = pd.DataFrame([['kladflna', 'l;adfkadf', ';aljdnvohauehfkadflan'] for i in range(1000)], columns=list(range(3)))\" 'df[2].str.len().max()'\n1000 loops, best of 3: 351 usec per loop\n</code></pre>\n\n<h3>function calls</h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>from dis import dis\n\nimport pandas as pd; df = pd.DataFrame([['kladflna', 'l;adfkadf', ';aljdnvohauehfkadflan'] for i in range(1000)], columns=list(range(3)))\n\ndef f(df):\n df[2].map(str).apply(len).max()\n\ndef g(df):\n df[2].str.len().max()\n\ndis(f)\n 2 0 LOAD_FAST 0 (df)\n 2 LOAD_CONST 1 (2)\n 4 BINARY_SUBSCR\n 6 LOAD_ATTR 0 (map)\n 8 LOAD_GLOBAL 1 (str)\n 10 CALL_FUNCTION 1\n 12 LOAD_ATTR 2 (apply)\n 14 LOAD_GLOBAL 3 (len)\n 16 CALL_FUNCTION 1\n 18 LOAD_ATTR 4 (max)\n 20 CALL_FUNCTION 0\n 22 POP_TOP\n 24 LOAD_CONST 0 (None)\n 26 RETURN_VALUE\n\ndis(g)\n 2 0 LOAD_FAST 0 (df)\n 2 LOAD_CONST 1 (2)\n 4 BINARY_SUBSCR\n 6 LOAD_ATTR 0 (str)\n 8 LOAD_ATTR 1 (len)\n 10 CALL_FUNCTION 0\n 12 LOAD_ATTR 2 (max)\n 14 CALL_FUNCTION 0\n 16 POP_TOP\n 18 LOAD_CONST 0 (None)\n 20 RETURN_VALUE\n\n</code></pre>\n\n<h1>Opening a file multiple times</h1>\n\n<p>In your <code>identifyFixedWidth</code> function, you open and read a file multiple times. I would say this makes it a candidate for a refactor, since these tasks should probably be broken into smaller functions:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def identify_fixed_width(name):\n filepath = os.path.join(path, name)\n\n # open the file here, and re-use the file-handle with fh.seek(0)\n with open(filepath) as fh:\n number_lines, avg_chars, max_length = get_avg_chars(fh)\n\n # re-use this file handle, go back to the beginning\n fh.seek(0)\n counter = find_header(fh, avg_chars)\n\n fh.seek(0)\n col_pos = get_row_counter(fh, counter)\n\n common = list(set.intersection(*map(set, col_pos))\n logger.debug(f\"Potential field separator posistions: {common}\")\n\n # replace this with a list comprehension, it's faster and more compact\n new_common = [x for x in common if (x-1) not in common]\n new_common.append(max_len)\n\n logger.debug(f\"Field separator positions identified as {new_common}\"\n\n # do not shadow builtin names like range. If you must, use a leading underscore\n _range = len(new_common)\n width = []\n\n # underscore will show an unused or throwaway variable\n for i, _ in enumerate(new_common[0:_range-1]):\n width.append(new_common[i+1] - new_common[i])\n\n logger.debug(f'Column Lengths: {width}') \n return counter, width \n\n\ndef get_avg_chars(fh):\n \"\"\"\n Use enumerate to track the index here and\n just count how much you want to decrement from the index\n at the end\n \"\"\"\n decrement, max_len, total_chars = 0, 0, 0\n\n for idx, line in enumerate(fh, start=1)\n total_chars += len(line)\n if len(line) <= 2:\n decrement += 1\n\n # this can be evaluated with a ternary expression\n max_len = len(line) if len(line) > max_len else max_len\n\n # at the end of the for loop, idx is the length of the file\n num_lines = idx - decrement\n avg_chars = total_chars / num_lines\n\n return num_lines, avg_chars, max_len\n\n\ndef find_header(fh, avg_chars):\n counter = 0\n for line in fh:\n logger.debug(f\"{counter} has {len(line)} chars\")\n lower = len(line) <= avg_chars * 0.9\n upper = len(line) >= avg_chars * 1.1\n if upper or lower:\n logger.debug(f\"Line {counter}: Maybe part of header and needs to be skipped\")\n counter += 1\n else:\n logger.debug(f\"Header found at {counter}\") \n break\n return counter\n\n\ndef get_row_counter(fh, counter):\n \"\"\"\n Again, use enumerate here for row_counter\n \"\"\" \n col_pos = []\n for row_counter, line in enumerate(fh):\n if row_counter <= counter:\n continue\n blanks = [m.start() for m in re.finditer(' ', line)]\n if len(blanks) > 2:\n # you've already declared this variable, so use it \n col_pos.append(blanks)\n if row_counter <= 5:\n logger.debug(col_pos[-1])\n return col_pos\n</code></pre>\n\n<p>Now, it's easier to break apart, debug, and separate out pieces of work within a function.</p>\n\n<h1>Style</h1>\n\n<p>A few things</p>\n\n<ol>\n<li><p>Variable and function names <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">should be lowercase</a> with words separated by underscores (<code>_</code>). Upper case is usually reserved for types, classes, etc. So something like <code>rowCounter</code> should really be <code>row_counter</code>.</p></li>\n<li><p>When checking for <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">equivalence with singletons such as <code>None</code>, <code>True</code>, and <code>False</code></a>, it is usually better to use <code>if value:</code> or <code>if not value</code>:</p></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code># change this to\nif date_flag == True:\n\n# this\nif date_flag:\n</code></pre>\n\n<ol start=\"3\">\n<li>I'm not sure if there's a PEP for it, but visually separating blocks of code with newlines can be very helpful. As an example:</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code> logger.debug('% of rows missing the charecter')\n logger.debug(df.isna().sum()/ df.isna().count())\n cleanupCandidates=df.dropna(axis='columns', thresh = (df.shape[0] + 1)*.8).fillna(-1)\n logger.debug('Dropping characters not present in 80% of the columns')\n logger.debug(cleanupCandidates.head())\n lowestVariance = 0\n spaceDetectedFlag = False\n Separator2 = ''\n for character in cleanupCandidates.columns:\n logger.debug('**********' + character +' **********')\n x = cleanupCandidates.loc[:,character].var()\n logger.debug('Calculated variance : ' + str(x) )\n if character == ' ':\n spaceDetectedFlag = True\n logger.debug('Potential position based file...')\n continue\n if lowestVariance >= x:\n lowestVariance =x\n Separator2 = character\n logger.debug(\"Separator identified as : \" + Separator2 + ' using METHOD 2')\n if Separator == Separator2:\n commonSep= Separator\n else:\n commonSep = list(set(Candidates).intersection(cleanupCandidates.columns))\n logger.debug('Both methods identify '+ str(commonSep) + 'as one of the separator candidates.')\n maxMode = 0\n modeTable = cleanupCandidates.mode()\n\n</code></pre>\n\n<p>This just looks like a gigantic wall of code, and is difficult to quickly scan for keywords, patterns, etc. Try breaking up the code by breaking things into logical steps:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Break all of this apart\n logger.debug('% of rows missing the charecter')\n logger.debug(df.isna().sum()/ df.isna().count())\n\n cleanupCandidates=df.dropna(axis='columns', thresh = (df.shape[0] + 1)*.8).fillna(-1)\n logger.debug('Dropping characters not present in 80% of the columns')\n logger.debug(cleanupCandidates.head())\n\n lowestVariance = 0\n spaceDetectedFlag = False\n Separator2 = ''\n\n for character in cleanupCandidates.columns:\n logger.debug('**********' + character +' **********')\n x = cleanupCandidates.loc[:,character].var()\n logger.debug('Calculated variance : ' + str(x) )\n\n # separate these if statements, they do different things\n if character == ' ':\n spaceDetectedFlag = True\n logger.debug('Potential position based file...')\n continue\n\n if lowestVariance >= x:\n lowestVariance =x\n Separator2 = character\n\n logger.debug(\"Separator identified as : \" + Separator2 + ' using METHOD 2')\n\n # if, elif, else should be connected because they are one logical\n # block of code\n if Separator == Separator2:\n commonSep= Separator\n else:\n commonSep = list(set(Candidates).intersection(cleanupCandidates.columns))\n logger.debug('Both methods identify '+ str(commonSep) + 'as one of the separator candidates.')\n maxMode = 0\n modeTable = cleanupCandidates.mode()\n</code></pre>\n\n<ol start=\"4\">\n<li>Make sure there's <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"nofollow noreferrer\">consistent whitespace around variables and operators.</a></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code># go from this\nlowest_variance =x\ncommon_sep= separator\n# to this\nlowest_variance = x\ncommon_sep = separator\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T14:48:03.987",
"Id": "224036",
"ParentId": "215360",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224036",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:26:22.923",
"Id": "215360",
"Score": "7",
"Tags": [
"python",
"beginner",
"csv",
"file-system",
"pandas"
],
"Title": "Python code to identify structure of a text file"
} | 215360 |
<p><strong>Background</strong></p>
<p>I got this interview test and got declined due to not meeting their expectations, but never got a reason on what was bad and how they solved it. I want to improve and learn something out of it.</p>
<p><strong>Question</strong></p>
<p>How can this be better written and what is badly written?</p>
<p><strong>Assignment description</strong></p>
<p>To optimize the amount of data sent between the web browser to the web server
a "clever" Javascript developer came up with the idea to translate JSON objects
into binary format in the application and send them to the server. Faced with
the fact that the Javascript is released in its final version to the customer
it is now your task to develop the parser on the back end system.</p>
<p>A JSON object is a hierarchy of key-value pairs where a value in its turn can
contain new key-value pairs. It consists of four basic types: numbers, strings,
arrays and dictionaries. An array is a list of values and a dictionay is a list
of key-value pairs. The key can only be of the type number or string while a
value can be of any type.</p>
<p>A JSON object always starts with a value.</p>
<p>An example JSON object can look like:</p>
<pre><code>{
'firstName': 'John',
'lastName': 'Smith',
'age': 25,
'address': {
'streetAddress': '21 2nd Street',
'city': 'New York',
'state': 'NY',
'postalCode': '10021'
},
'phoneNumber': [
{ 'type': 'home', 'number': '212 555-1234' },
{ 'type': 'fax', 'number': '646 555-4567' }
]
}
</code></pre>
<p>A number is printed in decimal without any decoration.
Example: 25</p>
<p>A string is printed in ASCII with single quotes in the start and end of the
string.
Example: 'test'</p>
<p>A key-value pair is printed as key followed by colon (:), a space ( ) and the
value.
Example: <code>'a': 67</code></p>
<p>A dictionary starts and ends with curly brackets ({ and }) and then has a
comma (,) separated list of key-value pairs.
Example: <code>{ 'name': 'Joe', 'age': 31 }</code></p>
<p>An array starts and ends with square brackets ([ and ]) and then has a
comma (,) separated list of values.
Example: <code>[ 'hello', 56, 'world' ]</code></p>
<p>The binary representation of the JSON object contains a one byte identifier
that describes the type of the data to follow and is then immediately followed
by the data.</p>
<p>The identifiers and their types are as follows:</p>
<pre><code>Identifier Type Description
0x01 Number 4 bytes signed integer in big endian byte order.
0x02 String N ASCII characters terminated by 0x00.
0x05 List Amount of items as a number followed by N values
0x06 Dictionary Amount of items as a number followed by N
key-value pairs
</code></pre>
<p>The program's task is to parse a binary file and prints it as human readable
text. It should read the data from standard input and writes it the result to
standard output.</p>
<p>Look at the files 'input_x' and their respective 'result_x' for examples of
input and output. More background can be found on e.g. www.json.org</p>
<p><strong>Input_4 binary</strong></p>
<p><a href="https://gist.github.com/devharis/c7819ffbeae6f0ef3169c655bdc077e7" rel="nofollow noreferrer">link to input_4 on gist</a></p>
<p><strong>My solution</strong></p>
<pre><code>public class Main {
private static String INPUT_FILENAME = "input_4";
private static String OUTPUT_FILENAME = "result_4";
private static String RESOURCE_INPUT_PATH = "src/main/resources/input/";
private static String RESOURCE_OUTPUT_PATH = "src/main/resources/output/";
public static void main(String[] args) {
File resourcesDirectory = new File(String.format("%s%s", RESOURCE_INPUT_PATH, INPUT_FILENAME));
File file = new File(resourcesDirectory.getAbsolutePath());
try {
byte[] byteArray = Files.readAllBytes(file.toPath());
RecursiveParser recursiveParser = new RecursiveParser();
try {
String result = recursiveParser.parse(byteArray, 0, false).toString();
String prettyPrinted = prettyPrint(result);
BufferedWriter writer = new BufferedWriter(
new FileWriter(
new File(
String.format("%s%s%s", RESOURCE_OUTPUT_PATH, OUTPUT_FILENAME, ".json")
)
)
);
writer.write(prettyPrinted);
writer.close();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String prettyPrint(String data) throws JSONException {
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject){
return (new JSONObject(data)).toString(4);
}
else if (json instanceof JSONArray){
return (new JSONArray(data)).toString(4);
} else {
return data; // nothing to pretty print
}
}
}
</code></pre>
<pre><code>class RecursiveParser {
private static int TERMINATE = 0x00;
private static int NUMBER = 0x01; // Number 4 bytes signed integer in big endian byte order.
private static int STRING = 0x02; // String N ASCII characters terminated by 0x00.
private static int LIST = 0x05; // List Amount of items as a number followed by N values
private static int DICTIONARY = 0x06; // Dictionary Amount of items as a number followed by N key-value pairs
Object parse(byte[] byteArray, int index, boolean hasSub) throws JSONException {
for(; index < byteArray.length; index++){
if(byteArray[index] == NUMBER){
return getNumber(byteArray, index);
}
if(byteArray[index] == STRING){
return getString(byteArray, index);
}
if(byteArray[index] == LIST){
return getList(byteArray, index, hasSub);
}
if(byteArray[index] == DICTIONARY){
return getDictionary(byteArray, index, hasSub);
}
}
return null; // should never get here
}
private Object getDictionary(byte[] byteArray, int index, boolean hasSub) throws JSONException {
index++; // move to size after type because dictionary size
int dictionarySize = (int)parse(byteArray, index, hasSub);
index += ByteBuffer.allocate(4).putInt(dictionarySize).array().length;
JSONWriter jsonWriter = new JSONStringer()
.object();
for(int i = 0; i < dictionarySize; i++){
index++;
Object key = parse(byteArray, index, hasSub);
int keyLength = 0;
if(key instanceof Integer){
jsonWriter.key(String.valueOf(key));
keyLength += ByteBuffer.allocate(4).putInt((Integer) key).array().length;
} else if(key instanceof String) {
jsonWriter.key(String.valueOf(key));
keyLength += ((String) key).getBytes().length + 1;
}
index += keyLength + 1;
// check if sub-array or sub-dictionary
hasSub = hasSub || (byteArray[index] == DICTIONARY || byteArray[index] == LIST);
Object value = parse(byteArray, index, hasSub);
int valueLength = 0;
if (value instanceof Integer) {
jsonWriter.value(value);
valueLength += ByteBuffer.allocate(4).putInt((Integer) value).array().length;
} else if (value instanceof String) {
jsonWriter.value(value);
valueLength += String.valueOf(value).getBytes().length + 1;
} else if (value instanceof AbstractMap.SimpleEntry) {
valueLength = (int) ((AbstractMap.SimpleEntry) value).getKey() - index;
jsonWriter.value(((AbstractMap.SimpleEntry) value).getValue());
}
index += valueLength;
}
jsonWriter
.endObject();
return hasSub && index != (byteArray.length - 1) ? new AbstractMap.SimpleEntry<>(index, new JSONObject(jsonWriter.toString())) : new JSONObject(jsonWriter.toString());
}
private Object getList(byte[] byteArray, int index, boolean hasSub) throws JSONException {
index++; // move to size after type because list size
int listSize = (int)parse(byteArray, index, hasSub);
index += ByteBuffer.allocate(4).putInt(listSize).array().length;
JSONWriter jsonWriter = new JSONStringer().array();
for(int i = 0; i < listSize; i++){
index++;
// check if sub-array or sub-dictionary
hasSub = hasSub || byteArray[index] == DICTIONARY || byteArray[index] == LIST;
Object value = parse(byteArray, index, hasSub);
int valueLength = 0;
if (value instanceof Integer) {
jsonWriter.value(value);
valueLength += ByteBuffer.allocate(4).putInt((Integer) value).array().length;
} else if (value instanceof String) {
jsonWriter.value(value);
valueLength += String.valueOf(value).getBytes().length + 1;
} else if (value instanceof AbstractMap.SimpleEntry) {
valueLength = (int) ((AbstractMap.SimpleEntry) value).getKey() - index;
jsonWriter.value(((AbstractMap.SimpleEntry) value).getValue());
}
index += valueLength;
}
jsonWriter.endArray();
return hasSub && index != (byteArray.length - 1) ? new AbstractMap.SimpleEntry<>(index, new JSONArray(jsonWriter.toString())) : new JSONArray(jsonWriter.toString());
}
private String getString(byte[] byteArray, int index) {
int start = index + 1; // move to next value after type
StringBuilder value = new StringBuilder();
for(int i = start; i < byteArray.length; i++){
if(byteArray[i] == TERMINATE){
break;
}
value.append((char)byteArray[i]);
}
return value.toString();
}
private int getNumber(byte[] byteArray, int index) {
int start = index + 1; // move to next value after type
int offset = start + 4;
byte[] numberByteArray = Arrays.copyOfRange(byteArray, start, offset);
return new BigInteger(numberByteArray).intValue();
}
}
</code></pre>
<p><strong>Result_4 output</strong></p>
<pre><code>{
"5": 25,
"deep": {
"1": "integer as key",
"2": {"4": 19088743},
"mix": "it is possible to mix integers and strings"
},
"first": 16777216,
"second": "value for second"
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T23:14:11.343",
"Id": "416559",
"Score": "0",
"body": "Would you mind adding additional examples? I don't quite follow the transformation from `Input_4` to `Result_4`. Where is, for example, `\"5\": 25` coming from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T07:41:01.380",
"Id": "416585",
"Score": "0",
"body": "It seems codereview strips the values I pasted from the binary and only keept the text ones. I'll try update the Input_4 binary or provide a link instead."
}
] | [
{
"body": "<p>There are two points that showed up immediately when looking at your implementation:</p>\n\n<ul>\n<li>You missed one of the goals of the task: It should read the data from standard input and writes it the result to standard output.</li>\n<li>You are reading in the complete binary data into memory and process it from there.</li>\n</ul>\n\n<p>The latter is a no go, if we're talking about large structures of JSON-data, e.g. containing Base64-encoded binary data of a DVD-image (don't ask ;-) It might be unlikely in a real world example but it might let them come to the conclusion that you're not familiar with stream based processing and had another one how showed that ability which might have led to their decision.</p>\n\n<p>Some remarks about the actual code:</p>\n\n<p>Your reading-number-implementation:</p>\n\n<pre><code>private int getNumber(byte[] byteArray, int index) {\n int start = index + 1; // move to next value after type\n int offset = start + 4;\n\n byte[] numberByteArray = Arrays.copyOfRange(byteArray, start, offset);\n\n return new BigInteger(numberByteArray).intValue();\n}\n</code></pre>\n\n<p>The specification said that a number is a signed integer in big endian order which is exactly how a Java <code>int</code> is defined, so instead of creating temporary arrays and a <code>BigInteger</code> you could simply have used an <code>int</code> and used bit-shifting:</p>\n\n<pre><code>private int getNumber(byte[] byteArray, int index) {\n int ret = byteArray[index + 4] & 0xff;\n ret |= (byteArray[index + 3] & 0xff) < 8;\n ret |= (byteArray[index + 2] & 0xff) < 16;\n ret |= (byteArray[index + 1] & 0xff) < 24;\n return ret;\n}\n</code></pre>\n\n<p>If you had implemented a stream based processing and used a <code>DataInputStream</code> the implementation would have been</p>\n\n<pre><code>private int getNumber(DataInputStream source) {\n return source.readInt();\n}\n</code></pre>\n\n<p>Your reading-text-implementation:</p>\n\n<pre><code>private String getString(byte[] byteArray, int index) {\n int start = index + 1; // move to next value after type\n StringBuilder value = new StringBuilder();\n for(int i = start; i < byteArray.length; i++){\n if(byteArray[i] == TERMINATE){\n break;\n }\n value.append((char)byteArray[i]);\n }\n return value.toString();\n}\n</code></pre>\n\n<p>Not much that can be changed here but for good measure, I'd change <code>(char)byteArray[i]</code> to <code>(char) (byteArray[i] & 0xff)</code>. For ASCII-characters that's irrelevant but still ;-)</p>\n\n<p>In <code>getDictionary</code>:</p>\n\n<pre><code>private Object getDictionary(byte[] byteArray, int index, boolean hasSub) throws JSONException {\n[...]\nindex += ByteBuffer.allocate(4).putInt(dictionarySize).array().length;\n</code></pre>\n\n<p>That's a very elaborate form of</p>\n\n<pre><code>index += 4;\n</code></pre>\n\n<p>because that's the number of bytes a signed integer is defined in the given specification.</p>\n\n<pre><code>keyLength += ((String) key).getBytes().length + 1;\n</code></pre>\n\n<p><code>getBytes()</code> uses the system's file-encoding. Because this particular example uses ASCII you won't see any effect on 99% of all systems but it would break on a system that runs e.g. with UTF-16 as file-encoding. You can see that youself by starting your Java test app with the system property <code>-Dfile.encoding=UTF16</code>.</p>\n\n<p>This is a common Beginner's Error which might have raised a flag with them as well.</p>\n\n<p>Always, <strong>ALWAYS</strong> use <code>getBytes(encoding)</code> unless you really want to use the system's file encoding for some reason.</p>\n\n<pre><code>hasSub = hasSub || (byteArray[index] == DICTIONARY || byteArray[index] == LIST);\n[...]\n} else if (value instanceof AbstractMap.SimpleEntry) {\n valueLength = (int) ((AbstractMap.SimpleEntry) value).getKey() - index;\n jsonWriter.value(((AbstractMap.SimpleEntry) value).getValue());\n}\n</code></pre>\n\n<p>This code block is duplicated in <code>getList</code>, you should put that into its own method and call it from the two methods. Same is true for the logic with the <code>return</code>-statement. This should be put into its own method so you only need to fix it once in case you find a bug in it.</p>\n\n<p>General stuff:</p>\n\n<p>You had to cope with the fact that your <code>get</code>-methods had to return a value and should change the value of the index. That's not possible, so you decided to change the index value in the calling method in dependence of the type of the returned parsed value. This is \"not optimal\" to say the least.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T17:28:34.793",
"Id": "416528",
"Score": "0",
"body": "Thank you very much for your review, I see now that this wasn't one of my greatest moments such as missing a obvious requirement. I learned a lot from your review and will bring it into my future assignments. Really appreciate it, cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:14:38.843",
"Id": "416591",
"Score": "0",
"body": "Also, your solution is just a standalone program. Implementing it as a class that can be directly imported into a project and having a separate unit tests probably would have helped. As to code style, it never hurts to mark your fields final and always throw an exception from code that should never be reached."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:23:27.487",
"Id": "416594",
"Score": "0",
"body": "Probably should have started a separate answer, but eh, here we go. Using FilterOutputStream and InputStream.transferto(...) would have shown the interviewer your knowledge about the standard APIs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T09:01:14.290",
"Id": "416600",
"Score": "0",
"body": "@TorbenPutkonen Can you make it a proposed answer, please? :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T17:16:23.897",
"Id": "215365",
"ParentId": "215361",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "215365",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:27:35.663",
"Id": "215361",
"Score": "7",
"Tags": [
"java",
"recursion",
"interview-questions",
"json"
],
"Title": "Recursive parser from Binary to JSON output"
} | 215361 |
<p>My below code is the slowest <code>sub</code> in my workbook. I can't set it to put the Array in immediatley, because the mode is calculated incorrectly (calculates for just one site no)</p>
<p>Is there a way to cut this down without breaking the fully functioning code?</p>
<pre><code>Sub ModeColumn()
Dim wb As Workbook, ws As Worksheet, LastRow As Long, rng As Range
Set wb = ThisWorkbook
Set ws = Worksheets("Data")
Set rng = ws.Cells(2, 15)
ws.Cells(1, 15) = "MODE"
LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row 'Finds the bottom populated row
With ws.Range(ws.Cells(2, 15), ws.Cells(LastRow, 15))
.Formula = "=IFERROR(MODE(IF(RC[-2]=AllSites,R2C12:R" & LastRow & "C12)),""N/A"")"
.FormulaArray = .FormulaR1C1
End With
End Sub
</code></pre>
<p>Here's what it looks like working</p>
<p><a href="https://i.stack.imgur.com/B9Oc8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B9Oc8.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/1UF4L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1UF4L.png" alt="enter image description here"></a></p>
<p>So above we can see that the selection works perfectly, but if I use the array formula right away, I get a lot of errors - so my time saving, breaks the expected result
And here's what it looks like if I just use "array" straight away</p>
<p><a href="https://i.stack.imgur.com/7gBYF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7gBYF.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/MRYBx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MRYBx.png" alt="enter image description here"></a></p>
<p>This is based on the following code</p>
<pre><code>With ws.Range(ws.Cells(2, 15), ws.Cells(LastRow, 15))
.FormulaArray = "=IFERROR(MODE(IF(RC[-2]=AllSites,R2C12:R" & LastRow & "C12)),""N/A"")"
End With
</code></pre>
<p>P.S I <em>cannot</em> (by request) use Excel Tables to make this easier</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T18:06:00.500",
"Id": "416533",
"Score": "1",
"body": "Just from the images in the top you have `$L$2:$L$3774` and below it you have `$L$2:$L7`. Seems like something was done that's not reflected in your code. Was there a manual edit?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T09:15:10.037",
"Id": "416602",
"Score": "0",
"body": "Sorry, should have mentioned - the last 2 images are from the \"record macro\" feature, where I added in the Array Forumla after"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T09:26:36.057",
"Id": "416606",
"Score": "0",
"body": "I have edited my question to reflect the bad code correctly"
}
] | [
{
"body": "<p>Usually with mass-Formula, I would recommend judicious use of the <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.application.calculation\" rel=\"nofollow noreferrer\"><code>Application.Calculation</code> property</a> to ensure that you don't recalculate for every cell (3773 times in your example!) - but, in this case I am <strong>also</strong> going to recommend using the <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.range.filldown\" rel=\"nofollow noreferrer\"><code>Range.FillDown</code> method</a> instead of assigning the Array Formula to every cell in the range.</p>\n\n<p>(Also the <a href=\"https://support.office.com/en-us/article/mode-function-e45192ce-9122-4980-82ed-4bdc34973120\" rel=\"nofollow noreferrer\"><code>MODE</code> function</a> is only included for Legacy Support, and has been replaced by the <a href=\"https://support.office.com/en-gb/article/mode-sngl-function-f1267c16-66c6-4386-959f-8fba5f8bb7f8\" rel=\"nofollow noreferrer\"><code>MODE.SNGL</code></a> and <a href=\"https://support.office.com/en-us/article/mode-mult-function-50fd9464-b2ba-4191-b57a-39446689ae8c\" rel=\"nofollow noreferrer\"><code>MODE.MULT</code></a> functions)</p>\n\n<pre><code>Application.Calculation = xlCalculationManual 'Do not recalculate formula until we say so!\nWith ws.Range(ws.Cells(2, 15), ws.Cells(LastRow, 15))\n .Cells(1,1).FormulaArray = \"=IFERROR(MODE.SNGL(IF($M2=AllSites,$L$2:$L$\" & LastRow & \")),\"\"N/A\"\")\" 'Set the Array Formula for the first cell\n '.Cells(1,1).FormulaArray = \"=IFERROR(MODE.SNGL(IF(RC[-2]=AllSites,R2C12:R\" & LastRow & \"C12)),\"\"N/A\"\")\"'In R1C1 Notation\n .FillDown 'Copy the Array Formula down to the end\nEnd With\nApplication.Calculation = xlCalculationAutomatic 'Reset Calculation Mode\n</code></pre>\n\n<p>(For comparison - running your method on 99999 rows of junk data took me 105 seconds. Using the <code>.Filldown</code> method on the same data took 29 seconds, and 99% of that was just waiting for Excel to finish calculating the Worksheet after the functions where in!)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T09:59:05.513",
"Id": "417244",
"Score": "0",
"body": "Hi - thanks for the great insight. Clearly looks like a much better way to run this. I'm not sure what I need to do with `Application.Calculate` as it just gives me a compile error. Apologies for this, I've never used this feature"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T10:05:15.530",
"Id": "417246",
"Score": "0",
"body": "Got it, I used `Application.Calculation = xlCalculationManual` instead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T10:06:22.300",
"Id": "417247",
"Score": "1",
"body": "@Badja Yes, I was just about to say that - I typed the wrong one when writing it out for your code. Sorry!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T10:10:39.157",
"Id": "417250",
"Score": "0",
"body": "Brilliant - this has worked perfectly and saved a LOT of time.. One last thing (if people in future want to see this) could you pelase edit your answer to have the array formula from my question? As yours was likely a placeholder? `.Cells(1, 1).FormulaArray = \"=IFERROR(MODE.SNGL(IF(RC[-2]=AllSites,R2C12:R\" & LastRow & \"C12)),\"\"N/A\"\")\" ` Thanks ever so much for your help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T10:16:58.213",
"Id": "417251",
"Score": "1",
"body": "@Badja The [`Range.FormulaArray` property](https://docs.microsoft.com/en-us/office/vba/api/excel.range.formulaarray) is known to sometimes have... *issues*... with `R1C1` notation, which is why I rewrote `\"=IFERROR(MODE.SNGL(IF(RC[-2]=AllSites,R2C12:R\" & LastRow & \"C12)),\"\"N/A\"\")\"` as `\"=IFERROR(MODE.SNGL(IF($M2=AllSites,$L$2$L$\" & LastRow & \")),\"\"N/A\"\")\"` (the same, but in `A1` notation)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T10:26:48.133",
"Id": "417253",
"Score": "0",
"body": "I believe there's a notation issue with your formula, I'm unable to run it, could you have a look as I can't pick it up. It will have something to do with my `C12` at the end, but I'm stumped as yours should work, looking at it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T10:40:28.283",
"Id": "417260",
"Score": "1",
"body": "I was missing the colon from `\"$L$2:$L$\" & LastRow`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T10:46:07.160",
"Id": "417264",
"Score": "0",
"body": "Can't believe I missed that... Thanks for your help!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T09:48:43.107",
"Id": "215658",
"ParentId": "215363",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215658",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:58:53.877",
"Id": "215363",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Vba to create a new column and insert array formula"
} | 215363 |
<p>I decided to write a little snake game in c++ to practice and as an opportunity to learn ncurses. It turned out to be much bigger than I anticipated but since I've never really written anything big, I'd be really thankful if you could point out more efficient ways or better practices.</p>
<p>main.cpp</p>
<pre><code>#include "ui.hpp"
#include "settings.hpp"
Point Settings::field_size = {18, 35};
bool Settings::enable_walls = false;
int main()
{
MainMenu main_menu;
main_menu.show();
return 0;
}
</code></pre>
<p>ui.hpp</p>
<pre><code>#pragma once
#include <ncurses.h>
#include <string>
#include <vector>
#include "point.hpp"
class Field;
enum class Facing;
using menu_item_t = int;
struct MenuItem
{
std::string label;
Point pos;
};
class MainMenu
{
private:
template<typename Functor>
void display_menu(std::vector<MenuItem> &p_menu_items, Functor p_selected_item_handler, bool p_quit_with_q, std::string p_title = "Snake");
void new_game();
void show_settings();
public:
MainMenu();
~MainMenu();
void show();
};
class GameUI
{
private:
WINDOW *m_border_win, *m_field_win;
const Field *m_field;
void update_field();
public:
GameUI(WINDOW *p_border_win, WINDOW *p_field_win);
void set_field(Field *p_field) { m_field = p_field; };
void draw_border();
void draw_static_elements();
void update(int score);
Facing get_input();
};
class UIUtils
{
private:
UIUtils() {};
public:
static menu_item_t dialogbox(std::string p_text, std::vector<std::string> p_buttons);
};
</code></pre>
<p>ui.cpp</p>
<pre><code>#include <stdexcept>
#include "ui.hpp"
#include "field.hpp"
#include "game.hpp"
#include "player.hpp"
#include "settings.hpp"
struct GameExit : std::exception {};
const char* const bool_to_str(bool b) { return b ? "enabled" : "disabled"; }
template<typename Functor>
void MainMenu::display_menu(std::vector<MenuItem> &p_menu_items, Functor p_selected_item_handler, bool p_quit_with_q, std::string p_title)
{
for(std::size_t i = 0; i < p_menu_items.size(); ++i)
{
p_menu_items[i].pos = {LINES / 2 + (int) i,
(COLS - (int) p_menu_items[i].label.length()) / 2};
}
try
{
erase();
menu_item_t selected_item = 0;
bool is_selected = false;
while(true)
{
mvprintw(LINES / 4, (COLS - p_title.length()) / 2, p_title.c_str());
for(std::size_t i = 0; i < p_menu_items.size(); ++i)
{
mvprintw(p_menu_items[i].pos.y, p_menu_items[i].pos.x, p_menu_items[i].label.c_str());
}
// make the currently selected item standout
mvchgat(p_menu_items[selected_item].pos.y, p_menu_items[selected_item].pos.x, p_menu_items[selected_item].label.length(), A_STANDOUT, 0, NULL);
refresh();
switch(getch())
{
case KEY_UP:
selected_item = selected_item != 0 ? selected_item - 1 : p_menu_items.size() - 1;
break;
case KEY_DOWN:
selected_item = selected_item != (int) p_menu_items.size() - 1 ? selected_item + 1 : 0;
break;
case '\n':
is_selected = true;
break;
case 'q':
case 27:
if(p_quit_with_q) throw GameExit();
break;
}
if(is_selected)
{
p_selected_item_handler(selected_item);
is_selected = false;
erase();
}
}
}
// exit the game, if it's called for an exit
catch(const GameExit &) {}
}
void MainMenu::new_game()
{
erase();
refresh();
WINDOW *game_win = newwin(Settings::field_size.y + 2, Settings::field_size.x + 2, (LINES - Settings::field_size.y) / 2 - 1, (COLS - Settings::field_size.x) / 2 - 1);
WINDOW *game_field_win = newwin(Settings::field_size.y, Settings::field_size.x, (LINES - Settings::field_size.y) / 2, (COLS - Settings::field_size.x) / 2);
GameUI *game_ui = new GameUI(game_win, game_field_win);
Game game(game_ui);
game.start();
delwin(game_field_win);
delwin(game_win);
delete game_ui;
}
void MainMenu::show_settings()
{
std::vector<MenuItem> settings_menu_items = {{
{std::string("Field size: ") + std::to_string(Settings::field_size.y) + " rows, " + std::to_string(Settings::field_size.x) + " cols"},
{std::string("Walls: ") + bool_to_str(Settings::enable_walls), {} },
}};
display_menu(settings_menu_items,
[&settings_menu_items](menu_item_t p_selected_item)
{
switch (p_selected_item)
{
case 0:
switch(Settings::field_size.y)
{
case 18:
Settings::field_size = {25, 50};
break;
case 25:
Settings::field_size = {10, 20};
break;
default:
Settings::field_size = {18, 35};
break;
}
settings_menu_items[0].label = std::string("Field size: ") + std::to_string(Settings::field_size.y) + " rows, " + std::to_string(Settings::field_size.x) + " cols";
break;
case 1:
Settings::enable_walls = !Settings::enable_walls;
settings_menu_items[1].label = std::string("Walls: ") + bool_to_str(Settings::enable_walls);
break;
default:
break;
}
},
true, "Settings");
}
MainMenu::MainMenu()
{
initscr();
cbreak();
noecho();
curs_set(0);
keypad(stdscr, true);
}
MainMenu::~MainMenu()
{
endwin();
}
void MainMenu::show()
{
std::vector<MenuItem> main_menu_items = {{
{"New Game", {} },
{"Settings", {} },
{"Exit", {} }
}};
display_menu(main_menu_items,
[this](menu_item_t p_selected_item)
{
switch(p_selected_item)
{
// New Game
case 0:
new_game();
break;
// Settings
case 1:
show_settings();
break;
case 2:
throw GameExit();
}
}, false);
}
GameUI::GameUI(WINDOW *p_border_win, WINDOW *p_field_win) : m_border_win(p_border_win), m_field_win(p_field_win)
{
draw_border();
nodelay(m_field_win, true);
keypad(m_field_win, true);
}
void GameUI::draw_border()
{
box(m_border_win, 0, 0);
wrefresh(m_border_win);
}
void GameUI::draw_static_elements()
{
for(int row = 0; row < m_field->m_field_size.y; ++row)
{
for(int col = 0; col < m_field->m_field_size.x; ++col)
{
if(m_field->get({row, col}) == Object::wall) mvwaddch(m_field_win, row , col, '#');
}
}
wrefresh(m_field_win);
}
void GameUI::update(int score)
{
mvwprintw(m_border_win, 0, 2, "Score: %d", score);
wrefresh(m_border_win);
update_field();
wrefresh(m_field_win);
}
void GameUI::update_field()
{
for(int row = 0; row < m_field->m_field_size.y; ++row)
{
for(int col = 0; col < m_field->m_field_size.x; ++col)
{
switch(m_field->get({row, col}))
{
case Object::empty:
mvwaddch(m_field_win, row , col, ' ');
break;
case Object::player:
mvwaddch(m_field_win, row , col, '*');
break;
case Object::food:
mvwaddch(m_field_win, row , col, '$');
break;
default:
break;
}
}
}
}
Facing GameUI::get_input()
{
int input = wgetch(m_field_win);
switch (input)
{
case KEY_UP:
return Facing::up;
case KEY_RIGHT:
return Facing::right;
case KEY_DOWN:
return Facing::down;
case KEY_LEFT:
return Facing::left;
case 'q':
case 27:
throw GameEndQuit();
break;
}
return Facing::null;
}
menu_item_t UIUtils::dialogbox(std::string p_text, std::vector<std::string> p_buttons)
{
// if COLS / 4 < min_width(the width so that all elements would fit) -> width = COLS - 4, else width = COLS / 4
int width = COLS / 4 < [&p_text, &p_buttons]() -> int
{
int min_width = 0;
for(std::string button : p_buttons)
{
min_width += button.length() + 2;
}
min_width = min_width > (int) p_text.length() ? min_width : p_text.length();
return min_width + 10;
} () ? COLS - 10 : COLS / 4;
WINDOW *win = newwin(7, width, (LINES - 7) / 2, (COLS - (width)) / 2);
keypad(win, true);
box(win, 0, 0);
mvwprintw(win, 2, (win->_maxx - p_text.length()) / 2, p_text.c_str());
wrefresh(win);
menu_item_t selected_item = 0;
while(true)
{
for(std::size_t i = 0; i < p_buttons.size(); ++i)
{
// x = (total width of the window / (amount of buttons + 1)) * (current button + 1) - (length of the text of the button / 2)
mvwprintw(win,
5,
(win->_maxx / (p_buttons.size() + 1)) * (i + 1) - (p_buttons[i].length() / 2),
p_buttons[i].c_str());
}
mvwchgat(win, 5, (win->_maxx / (p_buttons.size() + 1)) * (selected_item + 1) - (p_buttons[selected_item].length() / 2), p_buttons[selected_item].length(), A_STANDOUT, 0, NULL);
switch(wgetch(win))
{
case KEY_LEFT:
selected_item = selected_item != 0 ? selected_item - 1 : p_buttons.size() - 1;
break;
case KEY_RIGHT:
selected_item = selected_item != (int) p_buttons.size() - 1 ? selected_item + 1 : 0;
break;
// Enter
case '\n':
werase(win);
wrefresh(win);
delwin(win);
return selected_item;
}
}
throw std::logic_error("Out of the infinite while loop");
}
</code></pre>
<p>point.hpp</p>
<pre><code>#pragma once
struct Point
{
int y;
int x;
};
inline bool operator==(const Point& left, const Point& right)
{
return left.y == right.y &&
left.x == right.x;
}
</code></pre>
<p>field.hpp</p>
<pre><code>#pragma once
#include "point.hpp"
class Player;
enum class Object { empty, player, food, wall };
class Field
{
private:
Object **m_field;
public:
Field();
~Field();
const Point m_field_size;
Object get(Point p_point) const { return m_field[p_point.y][p_point.x]; }
void set(Point p_point, Object p_object) { m_field[p_point.y][p_point.x] = p_object; }
void place_food();
void add_walls();
void update_player(Player *p_player);
};
</code></pre>
<p>field.cpp</p>
<pre><code>#include <random>
#include "field.hpp"
#include "player.hpp"
#include "settings.hpp"
Field::Field() : m_field_size(Settings::field_size)
{
m_field = new Object*[m_field_size.y];
for(int row = 0; row < m_field_size.y; ++row)
{
m_field[row] = new Object[m_field_size.x];
}
for(int y = 0; y < m_field_size.y; ++y)
{
for(int x = 0; x < m_field_size.x; ++x)
{
m_field[y][x] = Object::empty;
}
}
}
Field::~Field()
{
for(int row = 0; row < m_field_size.y; ++row) delete [] m_field[row];
delete [] m_field;
}
void Field::place_food()
{
while(true)
{
static std::mt19937 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> disty(0, m_field_size.y - 1);
std::uniform_int_distribution<std::mt19937::result_type> distx(0, m_field_size.x - 1);
Point new_food = {(int) disty(rng), (int) distx(rng)};
if(m_field[new_food.y][new_food.x] == Object::empty)
{
m_field[new_food.y][new_food.x] = Object::food;
break;
}
}
}
void Field::add_walls()
{
for(int y = 0; y < m_field_size.y; ++y)
{
m_field[y][0] = Object::wall;
m_field[y][m_field_size.x - 1] = Object::wall;
}
for(int x = 0; x < m_field_size.x; ++x)
{
m_field[0][x] = Object::wall;
m_field[m_field_size.y - 1][x] = Object::wall;
}
}
void Field::update_player(Player *p_player)
{
for(int row = 0; row < m_field_size.y; ++row)
{
for(int col = 0; col < m_field_size.x; ++col)
{
if (m_field[row][col] == Object::player)
{
m_field[row][col] = Object::empty;
}
}
}
for(int i = 0; i < p_player->size(); ++i)
{
Point player_point = p_player->get(i);
m_field[player_point.y][player_point.x] = Object::player;
}
}
</code></pre>
<p>player.hpp</p>
<pre><code>#pragma once
#include <vector>
#include "point.hpp"
enum class Facing { right, down, left, up, null };
class Player
{
private:
std::vector<Point> m_position {{5, 5}};
unsigned int m_length = 1;
Facing m_facing = Facing::right;
public:
void move(Point p_field_size);
void lengthen() { ++m_length; };
Point get(unsigned int p_at = 0) { return m_position.at(p_at); }
Facing get_facing() { return m_facing; }
void set_facing(Facing p_facing);
// returns the amount of Points the player occupies (costly!)
int size() { return m_position.size(); }
// returns the player's length. size() may have not been updated to it yet
unsigned int length() { return m_length; }
};
</code></pre>
<p>player.cpp</p>
<pre><code>#include <stdexcept>
#include "player.hpp"
void Player::move(Point p_field_size)
{
switch (m_facing)
{
case Facing::right:
{
if(m_position[0].x + 1 == p_field_size.x)
m_position.insert(m_position.begin(), { m_position.front().y, 0 });
else
m_position.insert(m_position.begin(), { m_position.front().y, m_position.front().x + 1 });
break;
}
case Facing::down:
{
if(m_position[0].y + 1 == p_field_size.y)
m_position.insert(m_position.begin(), { 0, m_position.front().x });
else
m_position.insert(m_position.begin(), { m_position.front().y + 1, m_position.front().x });
break;
}
case Facing::left:
{
if(m_position[0].x - 1 == -1)
m_position.insert(m_position.begin(), { m_position.front().y, p_field_size.x - 1 });
else
m_position.insert(m_position.begin(), { m_position.front().y, m_position.front().x - 1 });
break;
}
case Facing::up:
{
if(m_position[0].y - 1 == -1)
m_position.insert(m_position.begin(), { p_field_size.y - 1, m_position.front().x });
else
m_position.insert(m_position.begin(), { m_position.front().y - 1, m_position.front().x });
break;
}
default:
{
throw std::invalid_argument("Player has wrong Facing");
}
}
if(m_position.size() > m_length) m_position.pop_back();
}
void Player::set_facing(Facing p_facing)
{
switch (p_facing)
{
case Facing::right:
if(m_facing != Facing::left) m_facing = p_facing;
break;
case Facing::left:
if(m_facing != Facing::right) m_facing = p_facing;
break;
case Facing::down:
if(m_facing != Facing::up) m_facing = p_facing;
break;
case Facing::up:
if(m_facing != Facing::down) m_facing = p_facing;
break;
default:
break;
}
}
</code></pre>
<p>game.hpp</p>
<pre><code>#pragma once
#include <exception>
class Field;
class GameUI;
class Player;
struct GameEndDeath : std::exception {};
struct GameEndQuit : std::exception {};
class Game
{
private:
GameUI *m_ui;
Field *m_field;
Player *m_player;
void tick();
void update();
public:
Game(GameUI *p_ui);
~Game();
void start();
};
</code></pre>
<p>game.cpp</p>
<pre><code>#include <chrono>
#include <unistd.h>
#include "game.hpp"
#include "field.hpp"
#include "player.hpp"
#include "settings.hpp"
#include "ui.hpp"
void Game::tick()
{
const static std::chrono::milliseconds TICK_DURATION(145);
auto last_tick = std::chrono::high_resolution_clock::now();
while(true)
{
m_player->set_facing(m_ui->get_input());
// true if the time of the next tick(last tick + tick duration) is in the past
while((last_tick + TICK_DURATION) < std::chrono::high_resolution_clock::now())
{
update();
last_tick += TICK_DURATION;
}
// sleep for 25 ms
usleep(25 * 1000);
}
}
void Game::update()
{
Point player_head = m_player->get();
switch(m_field->get(player_head))
{
case Object::food:
{
m_field->set(player_head, Object::player);
m_field->place_food();
m_player->lengthen();
break;
}
case Object::wall:
case Object::player:
{
throw GameEndDeath();
break;
}
default:
break;
}
m_field->update_player(m_player);
m_player->move(m_field->m_field_size);
m_ui->update(m_player->length() - 1);
}
Game::Game(GameUI *p_ui) : m_ui(p_ui)
{
m_field = new Field();
m_ui->set_field(m_field);
m_player = new Player();
}
Game::~Game()
{
delete m_field;
delete m_player;
}
void Game::start()
{
if(Settings::enable_walls) m_field->add_walls();
m_field->place_food();
m_ui->draw_static_elements();
while(true)
{
try
{
tick();
}
catch(const GameEndQuit &)
{
// TODO: redraw the field when "No" is clicked
if(UIUtils::dialogbox(std::string("Quit?"), std::vector<std::string> {std::string("No"), std::string("Yes")}) == 1) return;
m_ui->draw_border();
m_ui->draw_static_elements();
}
catch(const GameEndDeath &)
{
UIUtils::dialogbox(std::string("You died"), std::vector<std::string> {std::string("OK")});
return;
}
}
}
</code></pre>
<p>settings.hpp</p>
<pre><code>#pragma once
struct Point;
class Settings
{
private:
Settings() {};
public:
static Point field_size;
static bool enable_walls;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T18:06:01.490",
"Id": "416534",
"Score": "5",
"body": "Don't worry, we can handle big projects at Code Review. Welcome!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T20:34:57.437",
"Id": "416556",
"Score": "0",
"body": "The more I look at the code, the more I notice ways I can improve it (e.g. use a namespace instead of a class with a private constructor). But too late now, I guess. The question is, why didn't I notice it earlier since I've been looking for ways to improve the code for some time now? Well..."
}
] | [
{
"body": "<p>This is a pretty nice effort for a C++ beginner. Well done! I see a number of things that may help you improve your code.</p>\n\n<h2>Don't reseed the random number generator more than once</h2>\n\n<p>In the <code>Field::place_food()</code> routine, the loop is written like this:</p>\n\n<pre><code>while(true)\n{ \n static std::mt19937 rng;\n rng.seed(std::random_device()());\n std::uniform_int_distribution<std::mt19937::result_type> disty(0, m_field_size.y - 1);\n std::uniform_int_distribution<std::mt19937::result_type> distx(0, m_field_size.x - 1);\n\n Point new_food = {(int) disty(rng), (int) distx(rng)};\n if(m_field[new_food.y][new_food.x] == Object::empty)\n {\n m_field[new_food.y][new_food.x] = Object::food;\n break;\n }\n}\n</code></pre>\n\n<p>There are a few problems with this. First, it reseeds the <code>rng</code> each time which is neither necessary nor advisable. Second, it uses <code>std::mt19937::result_type</code> as the distribution type but then casts to an <code>int</code>. Fourth, it hides the loop exit function. Here's how I'd write it instead:</p>\n\n<pre><code>void Field::place_food()\n{\n static std::mt19937 rng(std::random_device{}());\n std::uniform_int_distribution<int> disty(0, m_field_size.y - 1);\n std::uniform_int_distribution<int> distx(0, m_field_size.x - 1);\n Point location{disty(rng), distx(rng)};\n while(get(location) != Object::empty)\n { \n location = Point{disty(rng), distx(rng)};\n }\n set(location, Object::food);\n}\n</code></pre>\n\n<p>Note also that I've named the point <code>location</code> which seemed more appropriate to me, and used the <code>get</code> and <code>set</code> functions already defined. Which leads us to the next suggestion...</p>\n\n<h2>Pass references where appropriate</h2>\n\n<p>The <code>Point</code> parameter to the <code>Field::get</code> and <code>Field::set</code> functions should probably be a <code>const Point&</code> and <code>Point&</code>, respectively.</p>\n\n<h2>Don't specify type qualifiers on return types</h2>\n\n<p>The <code>ui.cpp</code> file contains this function:</p>\n\n<pre><code>const char* const bool_to_str(bool b) { return b ? \"enabled\" : \"disabled\"; }\n</code></pre>\n\n<p>The problem with it is that it's claiming to not allow the caller to modify the returned pointer. What's intended is for the caller not to be able to modify the strings to which they're pointing -- the other <code>const</code> is just ignored. So the way to write this would actually be:</p>\n\n<pre><code>static const char* bool_to_str(bool b) { return b ? \"enabled\" : \"disabled\"; }\n</code></pre>\n\n<p>Note also that I've made it <code>static</code> because it's not used anywhere else.</p>\n\n<h2>Prefer standard functions to platform-specific ones</h2>\n\n<p>The <code>Game::tick()</code> routine is much more complex than needed and uses <code>usleep</code> from <code><unistd.h></code> which is not standard C++. I'd use <code><thread></code> instead and write the function like this:</p>\n\n<pre><code>void Game::tick()\n{\n m_player->set_facing(m_ui->get_input());\n update();\n std::this_thread::sleep_for(std::chrono::milliseconds(145));\n}\n</code></pre>\n\n<h2>Eliminate raw <code>new</code> and <code>delete</code> where practical</h2>\n\n<p>The <code>MainWindow::new_game()</code> has these lines:</p>\n\n<pre><code>GameUI *game_ui = new GameUI(game_win, game_field_win);\n\nGame game(game_ui);\ngame.start();\n\ndelwin(game_field_win);\ndelwin(game_win);\ndelete game_ui;\n</code></pre>\n\n<p>But is there really any reason to use <code>new</code> there? I'd suggest it would be better to write it like this:</p>\n\n<pre><code>GameUI game_ui{game_win, game_field_win};\nGame game(&game_ui);\ngame.start();\ndelwin(game_field_win);\ndelwin(game_win);\n</code></pre>\n\n<p>Now there's no chance of forgetting to call the destructor for <code>game_ui</code>.</p>\n\n<h2>Initialize all members</h2>\n\n<p>In <code>MainMenu::show_settings()</code> the <code>settings_menu_items</code> vector initialization fails to initialize the <code>pos</code> member for the first item. However, rather than simply fixing that, have a look at the next suggestion instead.</p>\n\n<h2>Rethink class interfaces</h2>\n\n<p>There are a number of peculiarities in the class interface. For instance, as you've already noted in the comments, the use of a <code>Settings</code> singleton is probably not ideal. Instead, it would probably make sense to associate the <code>Settings</code> with a <code>Game</code> instance. The <code>MainMenu</code> class is also strange. First, it doesn't just have a main menu, but functions as a generic menu class. Second, the <code>MenuItem</code> class doesn't seem to do much. I'd expect that instead a <code>Menu</code> might be a collection of <code>MenuItem</code> and that its function would be solely to display the menu and get a valid choice back from the user. Instead, this <code>MainMenu</code> class also contains all of the processing for the user choices. I think it would make more sense and be much more reusable to separate responsibilities that way.<br>\nThe other somewhat awkward interface is the relationship among the <code>Game</code>, <code>GameUI</code>, <code>Player</code> and <code>Field</code> objects. This might benefit from the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"noreferrer\">Model-View-Controller</a> design pattern. The <em>model</em> would comprise the <code>Field</code> and <code>Player</code> objects, the <em>view</em> would contain the display portion of the <code>Game::update()</code> function and the <em>controller</em> would comprise all of the portions of <code>GameUI</code> that manage player input. I think you'll find that it would result in a much cleaner interface that's easier to understand and maintain. One way that often helps when reasoning about this design pattern is to ask yourself if the component (model, view or controller) could be replaced with an alternative without affecting the other two components.</p>\n\n<h2>Don't define <code>enum</code> values you don't want</h2>\n\n<p>The <code>player.hpp</code> file has this <code>enum class</code>:</p>\n\n<pre><code>enum class Facing { right, down, left, up, null };\n</code></pre>\n\n<p>It seems that <code>null</code> is not particularly meaningful here. The only place it's used is in the case of non-input by the user. Again, this suggests that a single <code>enum class</code> omitting <code>null</code> would make more sense. Then the UI would sort out by itself whether to tell the <code>Player</code> object to change direction (or not) and the ambiguous <code>null</code> direction would no longer exist. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T15:10:23.390",
"Id": "215426",
"ParentId": "215366",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "215426",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T17:41:29.680",
"Id": "215366",
"Score": "14",
"Tags": [
"c++",
"console",
"snake-game",
"curses"
],
"Title": "Ncurses Snake game"
} | 215366 |
<p>This is a follow-up to "<em><a href="https://codereview.stackexchange.com/questions/215280/rock-paper-scissors-game">"Rock, Paper, Scissors" game</a></em>". I did almost everything the answers recommended and I hope you like it.</p>
<pre><code>import os
from random import choice
def player_choice():
while True:
print("Rock, paper or scissors?")
choice = input(">").capitalize()
if choice in ('Rock', 'Paper', 'Scissors'):
return choice
def win_msg(player_choice, computer_choice):
msg = f"{player_choice} beats {computer_choice}. You won!"
return msg
def lose_msg(player_choice, computer_choice):
msg = f"{computer_choice} beats {player_choice}. You lost!"
return msg
def computer_choice():
return choice(('Rock', 'Paper', 'Scissors'))
def show_statistics(scores):
os.system('cls' if os.name == 'nt' else 'clear')
print(f"Wins: {scores[0]}\nLosses: {scores[1]}\nDraws: {scores[2]}")
def game_outcome(player, computer):
if player == computer:
return 'Draw'
elif player == 'Rock':
if computer == 'Paper':
return 'Lose'
else:
return 'Win'
elif player == 'Paper':
if computer == 'Rock':
return 'Win'
else:
return 'Lose'
else:
if computer == 'Rock':
return 'Lose'
else:
return 'Win'
def show_results(outcome, player, computer):
if outcome == 'Win':
print(win_msg(player, computer))
elif outcome == 'Lose':
print(lose_msg(player, computer))
else:
print("Draw. Nobody wins or losses.")
def update_scores(scores, outcome):
new_scores = list(scores)
if outcome == 'Win':
new_scores[0] += 1
elif outcome == 'Lose':
new_scores[1] += 1
else:
new_scores[2] += 1
new_scores = tuple(new_scores)
return new_scores
def rock_paper_scissors(scores):
player = player_choice()
computer = computer_choice()
outcome = game_outcome(player, computer)
show_results(outcome, player, computer)
new_scores = update_scores(scores, outcome)
return new_scores
def play_again():
while True:
print("\nDo you want to play again?")
print("(Y)es")
print("(N)o")
ans = input("> ").lower()
if ans == 'y':
return True
elif ans == 'n':
return False
def starting_scores():
return 0, 0, 0
def main():
scores = starting_scores()
still_playing = True
while still_playing:
show_statistics(scores)
scores = rock_paper_scissors(scores)
still_playing = play_again()
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>Firstly, this is some nice clean code. Well done.</p>\n\n<p>The changes I'd make:</p>\n\n<ol>\n<li><code>win_msg</code> and <code>lose_msg</code> can instead be global constant strings.</li>\n<li>You should pick a preferred string delimiter and stick to using just that one. I prefer <code>'</code>.</li>\n<li>I would make a function <code>clear_console</code> as the code is rather strange. And will ease use if you need it again.</li>\n<li><p><code>game_outcome</code> can be simplified by using a dictionary to store what beats what.</p>\n\n<p>This also means you can expand to RPSLS with ease.</p></li>\n<li><code>show_results</code> can be changed to use a dictionary too.</li>\n<li><p><code>update_scores</code> can be changed in one of two ways:</p>\n\n<ul>\n<li>Add a dictionary that converts from <code>outcome</code> to the index.</li>\n<li>Change <code>scores</code> to a dictionary.</li>\n</ul></li>\n</ol>\n\n<p>And so you can get the following code:</p>\n\n<pre><code>import os\nfrom random import choice\n\nMESSAGES = {\n 'Win': '{player} beats {computer}. You won!',\n 'Lose': '{computer} beats {player}. You lost!',\n 'Draw': 'Draw. Nobody wins or losses.'\n}\n\nBEATS = {\n 'Rock': 'Scissors',\n 'Paper': 'Rock',\n 'Scissors': 'Paper'\n}\n\n\ndef player_choice():\n while True:\n print('Rock, paper or scissors?')\n choice = input('>').capitalize()\n if choice in ('Rock', 'Paper', 'Scissors'):\n return choice\n\n\ndef play_again():\n while True:\n print('\\nDo you want to play again?')\n print('(Y)es')\n print('(N)o')\n ans = input('> ').lower()\n if ans == 'y':\n return True\n elif ans == 'n':\n return False\n\n\ndef computer_choice():\n return choice(('Rock', 'Paper', 'Scissors'))\n\n\ndef clear_console():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n\ndef game_outcome(player, computer):\n if player == computer:\n return 'Draw'\n\n if BEATS[player] == computer:\n return 'Win'\n else:\n return 'Lose'\n\n\ndef rock_paper_scissors(scores):\n clear_console()\n print(f'Wins: {scores[\"Win\"]}\\nLosses: {scores[\"Lose\"]}\\nDraws: {scores[\"Draw\"]}')\n player = player_choice()\n computer = computer_choice()\n outcome = game_outcome(player, computer)\n print(MESSAGES[outcome].format(player=player, computer=computer))\n scores[outcome] += 1\n return new_scores\n\n\ndef main():\n scores = {\n 'Win': 0,\n 'Lose': 0,\n 'Draw': 0\n }\n still_playing = True\n while still_playing:\n scores = rock_paper_scissors(scores)\n still_playing = play_again()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<hr>\n\n<p>From here you can look into using <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\"><code>enum</code></a> to remove the strings from your code. This is good because it's easy to make a typo in a string, say I use <code>'rock'</code> rather than <code>'Rock'</code>. It also means that if you do make a typo then you'll be able to see where it was made when you reach that code. However with a string it'll move the error to a later part of the code and make debugging horrible.</p>\n\n<p>Here is an example of how you can use them:</p>\n\n<pre><code>from enum import Enum\n\n\nclass Score(Enum):\n WIN = 'Win'\n LOSE = 'Lose'\n DRAW = 'Draw'\n\n\nMESSAGES = {\n Score.WIN: '{player} beats {computer}. You won!',\n Score.LOSE: '{computer} beats {player}. You lost!',\n Score.DRAW: 'Draw. Nobody wins or losses.'\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T18:51:21.010",
"Id": "215371",
"ParentId": "215367",
"Score": "2"
}
},
{
"body": "<p>I agree with <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">Peilonrayz</a> that you can use a <code>dict</code>, but I would not use it this way. Not because it won't work but because it only works in this specific case.</p>\n\n<pre><code>WIN = {('paper', 'rock'), ('rock', 'scissors'), ('scissors', 'paper')}\n\ndef game_outcome(player, computer):\n if player==computer:\n print('Draw. Nobody wins or losses.')\n return 0\n elif (player, computer) in WIN:\n print(f'{player} beats {computer}. You won!')\n return 1\n elif (computer, player) in WIN:\n print(f'{computer} beats {player}. You lost!')\n return -1 \n else:\n raise NotImplementedError(f\"no defined rule for '{player}' and '{computer}'\")\n</code></pre>\n\n<pre><code>>>> game_outcome('paper', 'paper')\nDraw. Nobody wins or looses.\n0\n>>> game_outcome('rock', 'paper')\npaper beats rock. You lost!\n-1\n>>> game_outcome('paper', 'rock')\npaper beats rock. You won!\n1\n</code></pre>\n\n<p>Why is it more generic, because if you want to play <a href=\"https://www.youtube.com/watch?v=x5Q6-wMx-K8\" rel=\"nofollow noreferrer\"><strong>rock-paper-scissor-lizard-spock</strong></a>, you just change the dict to this:</p>\n\n<pre><code>RULES = {\n ('paper', 'rock'): 'covers',\n ('rock', 'scissors'): 'crushes',\n ('rock', 'lizard'): 'crushes',\n ('spock', 'rock'): 'vaporises',\n ('scissors', 'paper'): 'cuts',\n ('lizard', 'paper'): 'eats',\n ('paper', 'spock'): 'disproves',\n ('scissors', 'lizard'): 'decapitates',\n ('spock', 'scissors'): 'smashes',\n ('lizard', 'spock'): 'poisons'\n}\ndef game_outcome(player, computer):\n if player==computer:\n print('Draw. Nobody wins or losses.')\n return 0\n elif (player, computer) in RULES:\n print(f'{player} {RULES[player, computer]} {computer}. You won!')\n return 1\n elif (computer, player) in RULES:\n print(f'{computer} {RULES[computer, player]} {player}. You lost!')\n return -1 \n else:\n raise NotImplementedError(f\"no defined rule for '{player}' and '{computer}'\")\n</code></pre>\n\n<pre><code>>>> game_outcome('paper', 'spock')\npaper disproves spock. You won!\n1\n>>> game_outcome('lizard', 'spock')\nlizard poisons spock. You won!\n1\n>>> game_outcome('lizard', 'scissor')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 12, in game_outcome\nNotImplementedError: no defined rule for 'lizard' and 'scissor'\n>>> game_outcome('lizard', 'scissors')\nscissors decapitates lizard. You lost!\n-1\n</code></pre>\n\n<p>All this code just to say that <code>{(inputs, ...): output}</code> is generally a good pattern when the mapping between the inputs and the output isn't obvious.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T17:18:01.347",
"Id": "416665",
"Score": "0",
"body": "I find it funny how you say \"don't use a dict\" and use a dict in your second code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T10:21:59.950",
"Id": "416797",
"Score": "1",
"body": "**\"I agree with Peilonrayz that you can use a dict, but I would not use it this way\"** You probably misread. (and I didn't edit anything)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:34:54.853",
"Id": "215424",
"ParentId": "215367",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T18:14:08.100",
"Id": "215367",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"rock-paper-scissors"
],
"Title": "\"Rock, Paper, Scissors\" game - follow-up"
} | 215367 |
<p>This is a simple calculator made in 2/3 hours. I am still new and I was trying out some tags. If you can add some comment and say what to do and what to improve I will be really grateful.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var buttonOne = document.forms.formularzCalc.keyOne;
var buttonTwo = document.forms.formularzCalc.keyTwo;
var buttonThree = document.forms.formularzCalc.keyThree;
var buttonFour = document.forms.formularzCalc.keyFour;
var buttonFive = document.forms.formularzCalc.keyFive;
var buttonSix = document.forms.formularzCalc.keySix;
var buttonSeven = document.forms.formularzCalc.keySeven;
var buttonEight = document.forms.formularzCalc.keyEight;
var buttonNine = document.forms.formularzCalc.keyNine;
var buttonZero = document.forms.formularzCalc.keyZero;
var buttonPlus = document.forms.formularzCalc.keyPlus;
var buttonMinus = document.forms.formularzCalc.keyMinus;
var buttonMulti = document.forms.formularzCalc.keyMulti;
var buttonDivide = document.forms.formularzCalc.keyDivide;
var buttonCancel = document.forms.formularzCalc.keyCancel;
var buttonResult = document.forms.formularzCalc.keyResult;
var resultArea = document.forms.formularzCalc.Wynik;
var znacznik = 0;
var x;
var y = "";
// klawisze
function LiczbaX() {
resultArea.value += this.value
}
function LiczbaY() {
if (resultArea.value != "")
resultArea.value += this.value
}
// operatory arytmetyczne i przypisywanie wartości resultArea do x
function znak() {
x = resultArea.value;
resultArea.value = "";
znacznik = this.value;
}
// przypisywanie wartości resultArea do y i obliczanie
function wyniczek() {
y = resultArea.value;
if (y == "")
alert("Co do **** karmazyna ?!?");
else {
switch (znacznik) {
case "+":
if (isNaN(x) == false && isNaN(y) == false)
resultArea.value = parseInt(x) + parseInt(y);
else
alert("Thats wrong! use C and try again");
break;
case "-":
if (isNaN(x) == false && isNaN(y) == false)
resultArea.value = parseInt(x) - parseInt(y);
else
alert("Thats wrong! use C and try again");
break;
case "*":
if (isNaN(x) == false && isNaN(y) == false)
resultArea.value = parseInt(x) * parseInt(y);
else
alert("Thats wrong! use C and try again");
break;
case "/":
if (y == 0 || isNaN(x) == true || isNaN(y) == true)
alert("Thats wrong! use C and try again");
else
resultArea.value = parseInt(x) / parseInt(y);
break;
}
}
}
// zdarzenia kliknięć cyfr
buttonOne.addEventListener("click", LiczbaX)
buttonTwo.addEventListener("click", LiczbaX)
buttonThree.addEventListener("click", LiczbaX)
buttonFour.addEventListener("click", LiczbaX)
buttonFive.addEventListener("click", LiczbaX)
buttonSix.addEventListener("click", LiczbaX)
buttonSeven.addEventListener("click", LiczbaX)
buttonEight.addEventListener("click", LiczbaX)
buttonNine.addEventListener("click", LiczbaX)
buttonZero.addEventListener("click", LiczbaY)
// zdarzenia kliknięć cyfr
buttonPlus.addEventListener("click", znak)
buttonMinus.addEventListener("click", znak)
buttonMulti.addEventListener("click", znak)
buttonDivide.addEventListener("click", znak)
// zdarzenie podawania wyniku
buttonResult.addEventListener("click", wyniczek);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: #fff0b7;
}
/* Edytowanie formularza */
form {
width: 40%;
margin: auto;
text-align: center;
}
td input {
width: 40px;
height: 30px;
}
fieldset {
border-color: #00998C;
background-color: rgba(0, 0, 0, 0.05);
}
legend:first-letter {
color: #DDcc67;
font-size: 120%;
}
legend {
background-color: #00998C;
padding: 5px 15px;
border-radius: 15px;
font-size: 23px;
font-weight: bolder;
color: #eeeeee;
font-family: "Arial Black";
margin: 0 auto;
text-shadow: 3px 3px 1px #333333;
}
/* Edytowanie tabeli */
table {
margin: auto;
}
th input {
text-align: right;
}
/* reszta */
footer {
width: 40%;
background-color: #00998C;
margin: 5px auto;
text-align: center;
border: 1px rgba(0, 0, 0, 0.30) solid;
color: #EEEEEE;
font-family: verdana;
font-weight: bold;
font-size: 80%;
min-width: 250px;
border-radius: 10px;
padding: 3px 0px;
}
input[disabled] {
box-shadow: 1px 1px 1px black;
}
img {
position: absolute;
left: 20px;
top: 20px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Kalkulator </title>
<link rel="stylesheet" href="kalkulatorCss.css" type="text/css">
</head>
<body>
<form name="formularzCalc">
<fieldset>
<legend> Calc Upgraded version </legend>
<table>
<!-- Tabela do wyrównania zawartości kalkulatora -->
<tr>
<th colspan="4"><input type="text" name="Wynik" disabled></th>
<!-- Użycie th w celu łatwiejszej edycji -->
</tr>
<tr>
<td><input type="button" name="keySeven" value="7"></td>
<td><input type="button" name="keyEight" value="8"></td>
<td><input type="button" name="keyNine" value="9"></td>
<td><input type="button" name="keyPlus" value="+"></td>
</tr>
<tr>
<td><input type="button" name="keyFour" value="4"></td>
<td><input type="button" name="keyFive" value="5"></td>
<td><input type="button" name="keySix" value="6"></td>
<td><input type="button" name="keyMinus" value="-"></td>
</tr>
<tr>
<td><input type="button" name="keyOne" value="1"></td>
<td><input type="button" name="keyTwo" value="2"></td>
<td><input type="button" name="keyThree" value="3"></td>
<td><input type="button" name="keyMulti" value="*"></td>
</tr>
<tr>
<td><input type="reset" name="keyCancel" value="C"></td>
<td><input type="button" name="keyZero" value="0"></td>
<td><input type="button" name="keyResult" value="="></td>
<td><input type="button" name="keyDivide" value="/"></td>
</tr>
</table>
</fieldset>
</form>
<footer>
The new Calc made by Hyakkimaru <sup>&copy;</sup> Wszelkie prawa zastrzeżone
</footer>
<script src="kalkulatorJavaScript.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T19:26:41.300",
"Id": "416548",
"Score": "3",
"body": "Welcome to Code Review! I hope you get some good answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T18:27:30.127",
"Id": "417693",
"Score": "0",
"body": "You could add another feature. For example, if I press 2 + 3 + 1 and then equals, I get 4. It only adds the last two numbers you entered. Apart from this it seems to work pretty good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T02:04:57.463",
"Id": "419018",
"Score": "0",
"body": "@hyakkimaru Still wanting a review? I see this is pretty old"
}
] | [
{
"body": "<h2>General feedback</h2>\n\n<p>For a beginner the code is okay - for the most part it appears to function like a calculator, except for the fact that if I click the sequence<kbd>4</kbd>, <kbd>+</kbd>, <kbd>C</kbd>, <kbd>5</kbd>, <kbd>=</kbd> then the result shows <code>5</code>, whereas with your calculator I see <code>9</code> because clearing the form via the reset/cancel button (i.e. <kbd>C</kbd>) doesn't clear the value in the variable <code>x</code>. </p>\n\n<p>This code is quite redundant - which is covered in more detail below. Also, some of the prompts, variables and method names appear to be in Polish while others are in English. It is best to choose one and be consistent.</p>\n\n<h2>Targeted feedback</h2>\n\n<h3>Repeated code</h3>\n\n<p>This code does not adhere to the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><strong>D</strong>on't <strong>R</strong>epeat <strong>Yourself</strong> principle</a> - thus some would say the code is <em>wet</em>. When creating larger applications, there may be many more elements on a page that need to have interactions handled and it would take a long time to copy/paste references and event handlers. </p>\n\n<p>There are various ways to avoid such redundancy. One technique would be to name the integer inputs with the integer number instead of the cardinal number (e.g. <code>key1</code>, <code>key2</code>, etc.) and then loop through the elements and add event handlers - something like:</p>\n\n<pre><code>for (var i = 1; i < 10; i++ ) {\n document.forms.formularzCalc[\"key\" + i].addEventListener(\"click\", LiczbaX)\n}\n</code></pre>\n\n<p>Another approach would be to use <a href=\"https://davidwalsh.name/event-delegate\" rel=\"nofollow noreferrer\">Event delegation</a> to handle clicks on a container element and then delegate actions based on the target element that was clicked. With that approach there is no need to add the event listener to all elements to observe events on.</p>\n\n<h3>Global variables</h3>\n\n<p>The variables setup at the top (i.e. <code>x</code>, <code>y</code>, <code>znacznik</code>, as well as all the DOM references) are global to the window. It is wise to limit the scope to avoid namespace collisions. This can be achieved with various approaches, such as using an <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/IIFE\" rel=\"nofollow noreferrer\">IIFE</a> or wrapping the code in a DOM-loaded callback.</p>\n\n<h3>Checking for numbers</h3>\n\n<p>The calls to <code>isNaN()</code> will return either <code>true</code> or <code>false</code> so the <code>== true</code> can be omitted in conditional expressions. Similarly, many JavaScript developers use <code>!isNaN()</code> instead of <code>isNaN() == false</code>.</p>\n\n<h3>Input validation in <code>wyniczek()</code></h3>\n\n<p>There is a line repeated many times in this function: <code>alert(\"Thats wrong! use C and try again\");</code>. The code already checks to see if <code>y</code> is blank (i.e. <code>if (y == \"\")\n alert(\"Co do **** karmazyna ?!?\");)</code> so a similar check could be made after that to ensure the input is valid. And if a <code>return</code> statement is added whenever the inputs are invalid, then there is no need to use the <code>else</code> block.</p>\n\n<h3>Using <code>alert()</code></h3>\n\n<p>For this single page application it might be okay to use <code>alert()</code> but in a larger application it may be better to have a separate UI element to hold messages to the user. Read more about this topic in <a href=\"https://codereview.stackexchange.com/a/210625/120114\">this answer by @blindman67</a>.</p>\n\n<h3>Parsing integers with <code>parseInt()</code></h3>\n\n<p>If you are going to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\" rel=\"nofollow noreferrer\"><code>parseInt()</code></a>, it is wise to specify the radix using the second parameter - unless you are using a unique number system like hexidecimal, octal, etc. then specify 10 for decimal numbers. </p>\n\n<blockquote>\n <p><strong>Always specify this parameter</strong> to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<h3>Strict Equality</h3>\n\n<p>It is a best practice to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity\" rel=\"nofollow noreferrer\">strict equality</a> when comparing values, especially when you expect the types to be the same. The code above uses loose equality comparisons, like: </p>\n\n<blockquote>\n<pre><code>if (y == \"\")\n</code></pre>\n</blockquote>\n\n<p>With the strict equality operator, the type of the value of <code>y</code> would never need to be converted to a string in case it had a different type.</p>\n\n<pre><code>if (y === \"\")\n</code></pre>\n\n<h2>Updated code</h2>\n\n<p>The code below utilizes suggestions from above to obtain the same functionality as the original code. It does use <code>eval()</code> to simplify the evaluation of the mathematic expressions but as you can see in the answers to <a href=\"https://stackoverflow.com/q/10474306/1575353\">this SO post</a> using it is highly discouraged. </p>\n\n<p>It also uses a few features added with the <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> specification like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/include\" rel=\"nofollow noreferrer\"><code>Array.includes()</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">template literals</a>, and the keywords <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a>, and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a> so note the browser compatibility with those features if necessary.</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>document.addEventListener('DOMContentLoaded', function() {\n const resultArea = document.forms.formularzCalc.Wynik;\n let operation = \"\";\n let x;\n let y = \"\";\n const OPERATIONS = [\"+\", \"-\", \"*\", \"/\"];\n\n // operatory arytmetyczne i przypisywanie wartości resultArea do x\n function setOperation(value) {\n x = resultArea.value;\n resultArea.value = \"\";\n operation = value;\n }\n\n // przypisywanie wartości resultArea do y i obliczanie\n function setResult() {\n y = resultArea.value;\n if (y === \"\") {\n alert(\"Co do **** karmazyna ?!?\");\n return;\n }\n if (y === 0 && operation === \"/\" || isNaN(x) || isNaN(y)) {\n alert(\"Thats wrong! use C and try again\");\n return;\n }\n if (OPERATIONS.includes(operation)) {\n resultArea.value = eval(`${parseInt(x, 10)} ${operation} ${parseInt(y, 10)}`);\n }\n }\n document.addEventListener('click', function(clickEvent) {\n if (clickEvent.target.tagName.toLowerCase() === 'input') {\n const value = clickEvent.target.value;\n const intValue = parseInt(value, 10);\n if (!isNaN(intValue)) {\n if (resultArea.value != \"\" || intValue) { //LiczbaX(), LiczbaY()\n resultArea.value += intValue\n }\n }\n if (OPERATIONS.includes(value)) {\n setOperation(value);\n }\n if (value === \"=\") {\n setResult();\n }\n }\n });\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n background-color: #fff0b7;\n}\n\n\n/* Edytowanie formularza */\n\nform {\n width: 40%;\n margin: auto;\n text-align: center;\n}\n\ntd input {\n width: 40px;\n height: 30px;\n}\n\nfieldset {\n border-color: #00998C;\n background-color: rgba(0, 0, 0, 0.05);\n}\n\nlegend:first-letter {\n color: #DDcc67;\n font-size: 120%;\n}\n\nlegend {\n background-color: #00998C;\n padding: 5px 15px;\n border-radius: 15px;\n font-size: 23px;\n font-weight: bolder;\n color: #eeeeee;\n font-family: \"Arial Black\";\n margin: 0 auto;\n text-shadow: 3px 3px 1px #333333;\n}\n\n\n/* Edytowanie tabeli */\n\ntable {\n margin: auto;\n}\n\nth input {\n text-align: right;\n}\n\n\n/* reszta */\n\nfooter {\n width: 40%;\n background-color: #00998C;\n margin: 5px auto;\n text-align: center;\n border: 1px rgba(0, 0, 0, 0.30) solid;\n color: #EEEEEE;\n font-family: verdana;\n font-weight: bold;\n font-size: 80%;\n min-width: 250px;\n border-radius: 10px;\n padding: 3px 0px;\n}\n\ninput[disabled] {\n box-shadow: 1px 1px 1px black;\n}\n\nimg {\n position: absolute;\n left: 20px;\n top: 20px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form name=\"formularzCalc\">\n <fieldset>\n <legend> Calc Upgraded version </legend>\n <table>\n <!-- Tabela do wyrównania zawartości kalkulatora -->\n <tr>\n <th colspan=\"4\"><input type=\"text\" name=\"Wynik\" disabled></th>\n <!-- Użycie th w celu łatwiejszej edycji -->\n </tr>\n <tr>\n <td><input type=\"button\" name=\"keySeven\" value=\"7\"></td>\n <td><input type=\"button\" name=\"keyEight\" value=\"8\"></td>\n <td><input type=\"button\" name=\"keyNine\" value=\"9\"></td>\n <td><input type=\"button\" name=\"keyPlus\" value=\"+\"></td>\n </tr>\n <tr>\n <td><input type=\"button\" name=\"keyFour\" value=\"4\"></td>\n <td><input type=\"button\" name=\"keyFive\" value=\"5\"></td>\n <td><input type=\"button\" name=\"keySix\" value=\"6\"></td>\n <td><input type=\"button\" name=\"keyMinus\" value=\"-\"></td>\n </tr>\n <tr>\n <td><input type=\"button\" name=\"keyOne\" value=\"1\"></td>\n <td><input type=\"button\" name=\"keyTwo\" value=\"2\"></td>\n <td><input type=\"button\" name=\"keyThree\" value=\"3\"></td>\n <td><input type=\"button\" name=\"keyMulti\" value=\"*\"></td>\n </tr>\n <tr>\n <td><input type=\"reset\" name=\"keyCancel\" value=\"C\"></td>\n <td><input type=\"button\" name=\"keyZero\" value=\"0\"></td>\n <td><input type=\"button\" name=\"keyResult\" value=\"=\"></td>\n <td><input type=\"button\" name=\"keyDivide\" value=\"/\"></td>\n </tr>\n </table>\n </fieldset>\n</form>\n<footer>\n The new Calc made by Hyakkimaru <sup>&copy;</sup> Wszelkie prawa zastrzeżone\n</footer></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T19:48:18.207",
"Id": "220202",
"ParentId": "215369",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T18:32:41.837",
"Id": "215369",
"Score": "7",
"Tags": [
"javascript",
"beginner",
"css",
"calculator",
"html5"
],
"Title": "Just a calculator"
} | 215369 |
<p>Today I faced a difficult problem where I needed to step through several totally unrelated classes, and I suspected (among others) an object aliasing problem somewhere deep in the framework layers.</p>
<p>In Eclipse, I had several breakpoints at which I could look at some of the objects and variables. But as soon as the frame finished, these variables would be gone. In addition, I wanted to relate objects from all over the system. And because I suspected an aliasing problem I wanted to see the Instance IDs. My first idea was to just right-click on a variable and add that object to the Watches, but that's not helpful. The watch expression would be evaluated each time anew in the then-current execution context.</p>
<p>Then I got creative. A global list of variables, that could solve my problem. I implemented this idea and added a nice and simple API that is targeted towards use in conditional breakpoints. I think this simple class will prove quite powerful since once you get creative, there's so many things this class can do:</p>
<ul>
<li>event tracing in real-time</li>
<li>collecting data from different sources</li>
<li>watching variables change (by using watch points)</li>
<li>and probably many more I haven't thought off</li>
<li>having a separate GUI to filter the captured variables during debugging, like in the Process Monitor from Sysinternals (this would require much more code though)</li>
</ul>
<p>Here's the code:</p>
<pre><code>package de.roland_illig.debug;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* DebugVars remembers the given objects for use in a debugging session.
* <p>
* To use it, add a permanent watch for {@code DebugVars.get()}.
* This will give access to all the remembered variables.
* <p>
* Not only can this class be used for remembering variables, it's
* equally possible to create a trace log by just adding a string
* instead of an arbitrary object.
* <p>
* Code that is writeable in the IDE can simply call:
* <pre> DebugVars.add(obj, "description");</pre>
* <p>
* Code that is read-only in the IDE can set a breakpoint with the
* following condition:
* <pre> DebugVars.add(this, "the session state")</pre>
* Since that method always returns {@code false}, the debugger will
* never stop at that breakpoint but still evaluate the side effects.
* <p>
* In a long debugging session, it is possible to set a {@link #mark()},
* and the next call to {@link #reset()} will discard all variables
* that have been added after that mark. There can be several marks,
* which allows for recording interesting objects while diving deep
* into a call hierarchy. These two methods return {@code false} as
* well, to be used in side-effect breakpoints.
* <p>
* Hint: for taking small notes during the debugging session, it is
* possible to interactively modify the variable's description via
* the Change Value menu item in the Variables view.
* <p>
* Note: all objects are remembered by reference, which means the
* values shown here are their current values. These may be different
* from the values they had at the time they were added.
*/
public final class DebugVars {
private DebugVars() {
}
private static final List<DebugVar> variables = new CopyOnWriteArrayList<>();
private static final List<Integer> marks = new CopyOnWriteArrayList<>();
/**
* @param descr either a simple string describing the object, or a
* printf-like format string if any args are given
*/
public static boolean add(Object obj, String descr, Object... args) {
String msg = args.length == 0
? descr
: String.format(Locale.ROOT, descr, args);
variables.add(new DebugVar(obj, msg));
return false;
}
public static List<DebugVar> get() {
return variables;
}
public static void clear() {
variables.clear();
marks.clear();
}
public static boolean mark() {
marks.add(variables.size());
return false;
}
public static boolean reset() {
if (marks.isEmpty()) return false;
int mark = marks.remove(marks.size() - 1);
if (mark >= variables.size()) return false;
variables.subList(mark, variables.size()).clear();
return false;
}
private static class DebugVar {
private final Object obj;
private final String descr;
private DebugVar(Object obj, String descr) {
this.obj = obj;
this.descr = descr;
}
@Override
public String toString() {
return String.format(Locale.ROOT, "%s (%s)", obj, descr);
}
}
}
</code></pre>
| [] | [
{
"body": "<p>I actually only have a minor sidenote that might be interesting here. This code is clean and well-documented. I only have nitpicks (formatting, lack of braces) aside from the one thing that really \"bothers\" me.</p>\n\n<p>As it stands, you're adding an additional entry-point to the heap, which <em>could</em> result in a memory leak. So long as you're only using this class in Debug-mode, that of course does not have very strong implications (especially if you use <code>reset</code> to clean the reference graph).</p>\n\n<p>If you want to avoid this, you should look into using <code>WeakReference<T></code> instead of keeping a direct reference to the object. Of course that implies you will need to deal with the object in <code>DebugVar</code> possibly being <code>null</code>. This doesn't really affect the code you currently have, though, since calling <code>add(null, \"null\");</code> does not result in any erroneous behaviour.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T19:36:50.857",
"Id": "215446",
"ParentId": "215373",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T19:05:59.633",
"Id": "215373",
"Score": "3",
"Tags": [
"java"
],
"Title": "Debugging aid for collecting objects from everywhere into a single scope"
} | 215373 |
<p><a href="https://projecteuler.net/problem=273" rel="nofollow noreferrer">Problem</a>:</p>
<blockquote>
<p>Consider equations of the form: <span class="math-container">\$a^2 + b^2 = N; 0 \leq a \leq b; a, b, N \in \mathbb{N}\$</span>.</p>
<p>For <span class="math-container">\$N=65\$</span> there are two solutions:</p>
<p><span class="math-container">\$a=1, b=8\$</span> and <span class="math-container">\$a=4, b=7\$</span>.</p>
<p>We call <span class="math-container">\$S(N)\$</span> the sum of the values of <span class="math-container">\$a\$</span> of all solutions of <span class="math-container">\$a^2 + b^2 = N\$</span>.</p>
<p>Thus <span class="math-container">\$S(65) = 1 + 4 = 5\$</span>.</p>
<p>Find <span class="math-container">\$\sum S(N)\$</span>, for all squarefree <span class="math-container">\$N\$</span> only divisible by primes of the form <span class="math-container">\$4k+1\$</span> with <span class="math-container">\$4k+1 < 150\$</span>.</p>
</blockquote>
<p>My solution is painfully slow:</p>
<pre><code>import math
import itertools
import time
def candidate_range(n):
cur = 5
incr = 2
while cur < n+1:
yield cur
cur += incr
incr ^= 6 # or incr = 6-incr, or however
def sieve(end):
prime_list = [2, 3]
sieve_list = [True] * (end+1)
for each_number in candidate_range(end):
if sieve_list[each_number]:
prime_list.append(each_number)
for multiple in range(each_number*each_number, end+1, each_number):
sieve_list[multiple] = False
return prime_list
primes = sieve(150)
goodprimes = []
for prime in primes:
if prime%(4)==1:
goodprimes.append(prime)
sum=[]
start_time = time.time()
#get a number that works
print("-------Part 1------")
mi=0
for L in range(1, len(goodprimes)+1):
sumf=0
for subset in itertools.combinations(goodprimes, L):
max=2**L/2
n=1
for x in subset:
n*=x
for b in range(math.floor(math.sqrt(n/2)), math.floor(math.sqrt(n)+1)):
a=math.sqrt(n-b*b)
if a.is_integer() and b>=a:
sum.append(a)
mi+=1
if mi==max:
mi=0
break
for num in sum:
sumf+=num
print(L,sumf, "--- %s seconds ---" % (time.time() - start_time))
#q+=1
print("--- %s seconds ---" % (time.time() - start_time))
sumf=0
for num in sum:
sumf+=num
print(sumf)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T11:17:55.450",
"Id": "416617",
"Score": "0",
"body": "I find beautiful that N has 65535 values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T11:34:56.293",
"Id": "416619",
"Score": "0",
"body": ".... and that you will need a BigInteger library because the topmost one will require 92 bit to be represented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T19:05:25.613",
"Id": "416701",
"Score": "1",
"body": "@Astrinus Python has unlimited size integers built in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T10:10:57.860",
"Id": "416795",
"Score": "0",
"body": "@mkrieger1 https://en.wikipedia.org/wiki/Proofs_of_Fermat's_theorem_on_sums_of_two_squares will solve the problem better ;-)"
}
] | [
{
"body": "<h2>The code</h2>\n\n<p>The formatting has a number of PEP8 violations.</p>\n\n<hr>\n\n<p>It's not obvious from the name what <code>candidate_range</code> does. It seems to be a wheel for the sieve. Normally that would be inlined in the sieve; even if you prefer not to do that, you could place the function inside <code>sieve</code> to make its scope clear.</p>\n\n<p>I don't find <code>sieve_list</code> a very helpful name. In general for sieving I prefer <code>is_composite</code>, inverting the booleans from the way you've done it. Similarly for <code>each_number</code>: it reads well on the first line which uses it, but very oddly on the others.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>goodprimes = []\nfor prime in primes:\n if prime%(4)==1:\n goodprimes.append(prime)\n</code></pre>\n</blockquote>\n\n<p>It's more Pythonic to use comprehensions:</p>\n\n<pre><code>goodprimes = [p for p in primes if p % 4 == 1]\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>#get a number that works\n</code></pre>\n</blockquote>\n\n<p>What does this mean? It looks more like noise than a useful comment to me.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>for L in range(1, len(goodprimes)+1):\n sumf=0\n for subset in itertools.combinations(goodprimes, L):\n</code></pre>\n</blockquote>\n\n<p>I don't know why <code>itertools</code> doesn't have a function to give all subsets, but it seems like the kind of thing which is worth pulling out as a separate function, both for reuse and for readability.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> max=2**L/2\n</code></pre>\n</blockquote>\n\n<p>What does this do?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> n=1\n for x in subset:\n n*=x\n</code></pre>\n</blockquote>\n\n<p>Consider as an alternative</p>\n\n<pre><code>from functools import reduce\nimport operator\n\n n = reduce(operator.mul, subset, 1)\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> for b in range(math.floor(math.sqrt(n/2)), math.floor(math.sqrt(n)+1)):\n a=math.sqrt(n-b*b)\n if a.is_integer() and b>=a:\n</code></pre>\n</blockquote>\n\n<p>Why <code>floor</code>s rather than <code>ceil</code>s?</p>\n\n<p>Are you certain that <code>math.sqrt</code> on an integer is never out by 1ULP?</p>\n\n<p>Why is <code>b>=a</code> necessary? (Obviously <code>b==a</code> is impossible, and isn't the point of the <code>range</code> chosen to force <code>b > a</code>?)</p>\n\n<hr>\n\n<blockquote>\n<pre><code> sum.append(a)\n</code></pre>\n</blockquote>\n\n<p>Is this for debugging? I can't see why you wouldn't just add <code>a</code> to a <code>total</code>.</p>\n\n<p>NB <code>sum</code> is aliasing the builtin function for adding up the values in a list.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> #q+=1\n</code></pre>\n</blockquote>\n\n<p>??? I can't see any other mention of <code>q</code>.</p>\n\n<h2>The algorithm</h2>\n\n<p>There are a few Project Euler problems which fall to brute force, but in general you need to find the right mathematical insight. Given the way this question is structured, you probably need to figure out how to find <span class=\"math-container\">\\$S(n)\\$</span> given the prime factorisation of <span class=\"math-container\">\\$n\\$</span>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T09:29:33.153",
"Id": "215408",
"ParentId": "215374",
"Score": "4"
}
},
{
"body": "<h1><code>sieve_list</code></h1>\n\n<p>Why don't you use a generator here? It can be clearer as generator, and the <code>candidate_range</code> proves you know how those work.</p>\n\n<pre><code>def sieve_OP_gen(end):\n yield 2\n yield 3\n sieve_list = [True] * (end+1)\n for each_number in candidate_range(end):\n if sieve_list[each_number]:\n yield each_number\n for multiple in range(each_number*each_number, end+1, each_number):\n sieve_list[multiple] = False\n</code></pre>\n\n<h1>list slice assignment</h1>\n\n<p>instead of:</p>\n\n<pre><code>for multiple in range(each_number*each_number, end+1, each_number):\n sieve_list[multiple] = False\n</code></pre>\n\n<p>you can do:</p>\n\n<pre><code>sieve_list[each_number::each_number] = [False] * (end // each_number)\n</code></pre>\n\n<p>this doesn't provide any speedup, but is more clear to me</p>\n\n<h1><code>candidate_range</code></h1>\n\n<p>I don't like <code>incr ^= 6</code>. This can be done a lot clearer with <code>itertools.cycle</code></p>\n\n<pre><code>def candidate_range_maarten():\n cur = 5\n increments = itertools.cycle((2, 4))\n while True:\n yield cur\n cur += next(increments)\n</code></pre>\n\n<p>But all in all I think this is a lot of effort to reduce the number of checks in generating the primes sieve by 1/3rd. In fact, it slows down the sieve generation</p>\n\n<pre><code>def sieve2(end):\n yield 2\n sieve_list = [True] * (end + 1)\n for each_number in range(3, end + 1, 2):\n if not sieve_list[each_number]:\n continue\n yield each_number\n sieve_list[each_number::each_number] = [False] * (end // each_number)\n</code></pre>\n\n<blockquote>\n<pre><code>sieve_OP(150) == list(sieve2(150))\n</code></pre>\n</blockquote>\n\n<pre><code>True\n</code></pre>\n\n<p>timings:</p>\n\n<pre><code>%timeit sieve_OP(150)\n</code></pre>\n\n<blockquote>\n<pre><code>24.5 µs ± 1.63 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n</blockquote>\n\n<pre><code>%timeit list(sieve2(150))\n</code></pre>\n\n<blockquote>\n<pre><code>16.3 µs ± 124 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n</code></pre>\n</blockquote>\n\n<h1>filtering primes</h1>\n\n<p>to filter the primes, you can use the builtin <code>filter</code></p>\n\n<pre><code>primes = list(sieve2(150))\ngoodprimes = list(filter(lambda x: x % 4 == 1, primes))\n</code></pre>\n\n<p>or a list comprehension: good_primes = [i for i in primes if i % 4 == 1]</p>\n\n<h1>functions</h1>\n\n<p>The rest of the code would be more clear if you split it in different functions. One to find the different candidates for the products, and another function to generate the <em>pythagorean</em> <code>a</code></p>\n\n<h2>product:</h2>\n\n<p>The product of an iterable can be calculated like this:</p>\n\n<pre><code>from functools import reduce\nfrom operator import mul\n\ndef prod(iterable):\n return reduce(mul, iterable, 1)\n</code></pre>\n\n<h2>powerset</h2>\n\n<p>As @PeterTaylor tnoted, there might be a itertools function to do this. There is,'t but there is an <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\">itertools recipe</a> <code>powerset</code>:</p>\n\n<pre><code>def powerset(iterable):\n \"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n s = list(iterable)\n return itertools.chain.from_iterable(\n itertools.combinations(s, r) for r in range(len(s) + 1)\n )\n</code></pre>\n\n<p>So generating the candidates is as easy as </p>\n\n<pre><code>def candidates(good_primes):\n for subset in powerset(good_primes):\n yield prod(subset)\n</code></pre>\n\n<h1><code>pythagorean_a</code></h1>\n\n<p>Instead of that nested for-loop which is not very clear what happens, I would split this to another function:</p>\n\n<pre><code>def pythagorean_a(n):\n for a in itertools.count(1):\n try:\n b = sqrt(n - (a ** 2))\n except ValueError:\n return\n if b < a:\n return\n if b.is_integer():\n yield a\n</code></pre>\n\n<blockquote>\n<pre><code>list(pythagorean_a(65))\n</code></pre>\n</blockquote>\n\n<pre><code>[1, 4]\n</code></pre>\n\n<h1>bringing it together</h1>\n\n<p><span class=\"math-container\">\\$S(N)\\$</span> then becomes: <code>sum(pythagorean_a(i))</code></p>\n\n<p>and <span class=\"math-container\">\\$\\sum S(N)\\$</span>: <code>sum(sum(pythagorean_a(i)) for i in candidates(good_primes))</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T10:03:12.877",
"Id": "215491",
"ParentId": "215374",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T19:07:38.600",
"Id": "215374",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded",
"mathematics"
],
"Title": "Project Euler, Problem 273: finding perfect-square partitions"
} | 215374 |
<p>I wrote this algorithm which takes input data from something like a CSV file or a large array that contain a series of String elements in the format of "count, FQDN" and then adds or increments the count of each domain component up to the complete FQDN. For example:</p>
<pre><code>// Sample output (in any order/format):
// getTotalsByDomain(counts)
// 1320 com
// 900 google.com
// 410 yahoo.com
// 60 mail.yahoo.com
// 10 mobile.sports.yahoo.com
// 50 sports.yahoo.com
// 10 stackoverflow.com
// 3 org
// 3 wikipedia.org
// 2 en.wikipedia.org
// 1 es.wikipedia.org
// 1 mobile.sports
// 1 sports
let counts = [ "900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"2,en.wikipedia.org",
"1,es.wikipedia.org",
"1,mobile.sports" ];
</code></pre>
<p>I was able to do this pretty well with the below algorithm, but I am concerned with the inner for loop which uses var 'j'. I felt like the only way that I could incrementally parse the domain components from the already split array was to create another array which unshifted the domain components to partially create a new array until I completed all of the components of the given FQDN element.</p>
<pre><code>function getDomainHits(arr){
var splitCount = [];
var domainCountDict = {};
for (var i = 0; i < arr.length; i++){
splitCount = arr[i].split(",");
var curCnt = 0;
if (splitCount[0]){
curCnt = splitCount[0];
}
var domain = [];
var currentDom = [];
if (splitCount[1] != undefined && splitCount[1]){
domain = splitCount[1].split(".");
for (var j = domain.length - 1; j >= 0; j--){
currentDom.unshift(domain.pop());
/*console.log("current iter: " + k + "\n"
+ "currentDom: " + currentDom.join(".") + "\n"
+ "current count: " + curCnt + "\n");*/
if (currentDom.join(".") in domainCountDict){
/*console.log("currentDom2: " + currentDom.join("."));
console.log("increment existing");*/
domainCountDict[currentDom.join(".")] += parseInt(curCnt);
}
if (!(currentDom.join(".") in domainCountDict)){
/*console.log("currentDom3: " + currentDom.join("."));
console.log("increment new");*/
domainCountDict[currentDom.join(".")] = parseInt(curCnt);
//console.log(domainCountDict);
}
}
}
}
return domainCountDict;
}
console.log(getDomainHits(counts));
</code></pre>
<p>If you want to see a complete walkthrough of my logic then you can see my answer to <a href="https://stackoverflow.com/questions/55132836/increment-counts-of-sites-visited-including-tlds-and-subdomains-outputted-to-jso">my question in Stack Overflow</a></p>
| [] | [
{
"body": "<p>You can modify the input until there's nothing left of it. In this example, I've used a regex with <code>.replace()</code> to shorten the FQDN. </p>\n\n<p>If you don't like regex, you could instead split the domain name on <code>.</code>, then in the loop use <code>dom.join(\".\")</code> to compose the object key, followed by <code>dom.shift()</code> to shorten the array. With the array technique, the loop conditional is <code>dom.length</code> (instead of just <code>dom</code>).</p>\n\n<pre><code>function getDomainHits(arr){\n let total={};\n arr.forEach( row => {\n let [hits, dom] = row.split(\",\");\n hits=parseInt(hits);\n while ( hits && dom ) { \n total[dom] = (total[dom] || 0) + hits;\n dom = dom.replace( /^[^.]*\\.?/, '' )\n }\n });\n return total;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T03:33:05.473",
"Id": "416574",
"Score": "0",
"body": "Wow this is a very elegant solution. Thanks for that I really do need to learn my regex patterns. I used to be better with them, but I never kept up with it. Do you recommend a resource that I could use to catch back up?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T04:44:47.557",
"Id": "416579",
"Score": "1",
"body": "Start small and spend time dissecting patterns to see what they are doing. There are [tools like regexbuddy](https://softwarerecs.stackexchange.com/questions/6971/free-program-to-create-regular-expressions-with-a-gui) to help with analysis; some people find those helpful, some don't. It's a handy skill, but in many ways nonessential—the array-split version of this code is only one line longer and uses no regex at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T17:21:26.947",
"Id": "416667",
"Score": "0",
"body": "I am still digesting your algorithm in its simplicity. I comprehend everything up until the while loop. Can you give me some commentary on whats going on here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T17:32:30.107",
"Id": "416672",
"Score": "1",
"body": "First line of while: add hitcount `hits` to counter `total[dom]` where `dom` is the FQDN; Second line: remove first part of FQDN (**aaa.example.com** ⇒ **example.com**), repeat loop for remaining part. Eventually `dom` will be just the TLD and when that is removed, there is nothing left, `dom == \"\"` and the `while` conditional fails, ending the loop. If `hits` is zero, the loop doesn't need to run at all, so we include `hits` in the conditional. The `|| 0` part simply initializes the counters if they are unset."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:08:40.670",
"Id": "416676",
"Score": "0",
"body": "Oh okay. It seems obvious now. Thanks again!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T00:26:51.133",
"Id": "215387",
"ParentId": "215376",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215387",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T19:26:20.337",
"Id": "215376",
"Score": "3",
"Tags": [
"javascript",
"array"
],
"Title": "Counting hits by domain"
} | 215376 |
<p>I am writing a compiler for esoteric language as one of my first Rust projects. I am using rust-pest to generate a parser. Since I'm new in Rust, code review would be great.</p>
<p>Full source code can be found <a href="https://github.com/fexolm/jfec" rel="nofollow noreferrer">here</a>.</p>
<p>Here are some code snippets.</p>
<p>Thanks in advance.</p>
<p>ast.rs</p>
<pre class="lang-rust prettyprint-override"><code>use std::rc::Rc as Rc;
#[derive(Debug)]
pub struct Module {
pub functions: Vec<FnDecl>
}
#[derive(Debug)]
pub struct FnDecl {
pub name: String,
pub inputs: Vec<Arg>,
pub output: String,
pub body: Rc<Stmt>,
}
#[derive(Debug)]
pub struct Arg {
pub typ: String,
pub name: String,
}
#[derive(Debug)]
pub enum Stmt {
Invalid,
Assign(AssignStmt),
Block(BlockStmt),
Expr(Rc<Expr>),
}
#[derive(Debug)]
pub struct AssignStmt {
pub name: String,
pub typ: String,
pub value: Rc<Expr>,
}
#[derive(Debug)]
pub struct BlockStmt {
pub list: Vec<Rc<Stmt>>,
}
#[derive(Debug)]
pub enum Expr {
Id(IdExpr),
Call(CallExpr),
}
#[derive(Debug)]
pub struct IdExpr {
pub name: String
}
#[derive(Debug)]
pub struct CallExpr {
pub name: String,
pub params: Vec<Rc<Expr>>,
}
</code></pre>
<p>parser.rs</p>
<pre class="lang-rust prettyprint-override"><code>use pest::iterators::Pair;
use pest::Parser;
use std::io;
use crate::ast;
use super::utils;
#[derive(Parser)]
#[grammar = "parser/grammar.pest"]
struct JFECParser;
fn parse_arg(arg_p: Pair<Rule>) -> Result<ast::Arg, io::Error> {
let mut iter = arg_p.into_inner();
let name = utils::next_string(&mut iter)?;
let typ = utils::next_string(&mut iter)?;
return Ok(ast::Arg { name, typ });
}
fn parse_args(args_p: Pair<Rule>) -> Result<Vec<ast::Arg>, io::Error> {
let mut res = vec!();
for p in args_p.into_inner() {
match p.as_rule() {
Rule::param => {
let arg = parse_arg(p)?;
res.push(arg);
}
_ => unreachable!(),
}
}
return Ok(res);
}
fn parse_call_params(call_params_p: Pair<Rule>) -> Result<Vec<Box<ast::Expr>>, io::Error> {
let mut res = vec!();
for p in call_params_p.into_inner() {
match p.as_rule() {
Rule::expr => {
let expr = parse_expr(p)?;
res.push(expr);
}
_ => unreachable!(),
}
}
Ok(res)
}
fn parse_call_expr(call_expr_p: Pair<Rule>) -> Result<Box<ast::Expr>, io::Error> {
let mut name = String::default();
let mut params = vec!();
for expr_p in call_expr_p.into_inner() {
match expr_p.as_rule() {
Rule::id => {
name = utils::to_string(expr_p);
}
Rule::call_params => {
params = parse_call_params(expr_p)?;
}
_ => unreachable!()
}
}
Ok(Box::new(ast::Expr::Call(ast::CallExpr { name, params })))
}
fn parse_expr(expr_p: Pair<Rule>) -> Result<Box<ast::Expr>, io::Error> {
let expr = utils::inner_next(expr_p)?;
match expr.as_rule() {
Rule::id => {
return Ok(Box::new(
ast::Expr::Id(ast::IdExpr { name: utils::to_string(expr) })));
}
Rule::call_expr => {
return parse_call_expr(expr);
}
_ => unreachable!(),
}
}
fn parse_stmt(stmt_p: Pair<Rule>) -> Result<Box<ast::Stmt>, io::Error> {
let stmt = utils::inner_next(stmt_p)?;
match stmt.as_rule() {
Rule::assign_stmt => {
let mut iter = stmt.into_inner();
let name = utils::next_string(&mut iter)?;
let typ = utils::next_string(&mut iter)?;
let val = utils::get_next(&mut iter)?;
let value = parse_expr(val)?;
return Ok(Box::new(ast::Stmt::Assign(
ast::AssignStmt { name, typ, value }
)));
}
Rule::expr_stmt => {
let next = utils::inner_next(stmt)?;
let expr = parse_expr(next)?;
return Ok(Box::new(ast::Stmt::Expr(expr)));
}
Rule::block_stmt => {
let block = parse_block(stmt)?;
return Ok(block);
}
_ => unreachable!(),
}
}
fn parse_block(block_p: Pair<Rule>) -> Result<Box<ast::Stmt>, io::Error> {
let mut list = vec!();
let next = utils::inner_next(block_p)?;
for p in next.into_inner() {
match p.as_rule() {
Rule::stmt => {
let stmt = parse_stmt(p)?;
list.push(stmt);
}
_ => unreachable!(),
}
}
Ok(Box::new(ast::Stmt::Block(ast::BlockStmt { list })))
}
fn parse_fn_decl(fndecl_p: Pair<Rule>) -> Result<ast::FnDecl, io::Error> {
let mut name = String::default();
let mut inputs = vec!();
let mut output = String::default();
let mut body = Box::new(ast::Stmt::Invalid);
for p in fndecl_p.into_inner() {
match p.as_rule() {
Rule::id => {
name = p.as_str().to_string();
}
Rule::param_list => {
inputs = parse_args(p)?;
}
Rule::ret_typ => {
output = utils::to_string(p);
}
Rule::block_stmt => {
body = parse_block(p)?;
}
_ => unreachable!(),
}
}
Ok(ast::FnDecl { name, inputs, output, body })
}
pub fn create_ast(text: &String) -> Result<ast::Module, io::Error> {
let mut parsed = JFECParser::parse(Rule::program, &text).expect("parse error");
let module = utils::get_next(&mut parsed)?;
let mut fn_decls = vec!();
for decl in module.into_inner() {
match decl.as_rule() {
Rule::decl => {
let next = utils::inner_next(decl)?;
let decl = parse_fn_decl(next)?;
fn_decls.push(decl);
}
Rule::EOI => (),
_ => unreachable!(),
}
}
Ok(ast::Module { functions: fn_decls })
}
</code></pre>
<p>utils.rs</p>
<pre class="lang-rust prettyprint-override"><code>use pest::iterators::{Pair, Pairs};
use pest::RuleType;
use std::io;
pub fn to_string<R: RuleType>(p: Pair<R>) -> String {
p.as_str().to_string()
}
pub fn next_string<R: RuleType>(p: &mut Pairs<R>) -> Result<String, io::Error> {
let next = get_next(p)?;
Ok(to_string(next))
}
pub fn get_next<'s, 't, R: RuleType>(p: &'s mut Pairs<'t, R>) -> Result<Pair<'t, R>, io::Error> {
if let Some(val) = p.next() {
Ok(val)
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Fail to get next element"))
}
}
pub fn inner_next<R: RuleType>(p: Pair<R>) -> Result<Pair<R>, io::Error> {
get_next(&mut p.into_inner())
}
</code></pre>
<p>grammar.pest</p>
<pre><code>WHITESPACE = _{ " " | "\t" | "\r" | "\n" }
program = { SOI ~ decl* ~ EOI }
decl = { fn_decl }
fn_decl = { "fn" ~ id ~ "(" ~ param_list? ~ ")" ~ ret_typ ~ block_stmt }
ret_typ = { ("->" ~ id)? }
block_stmt = { "{" ~ stmt_list ~ "}" }
param = { id ~ ":" ~ id }
param_list = { param ~ ("," ~ param)* }
stmt_list = { stmt* }
stmt = { assign_stmt | expr_stmt | block_stmt }
assign_stmt = { "let" ~ id ~ ":" ~ id ~ "=" ~ expr ~ ";"}
expr_stmt = { expr ~ ";" }
expr = { call_expr | id }
call_params = { expr ~ ("," ~ expr)* }
call_expr = { id ~ "(" ~ call_params? ~")" }
id = @{ ASCII_ALPHA+ }
</code></pre>
<p>The language looks like rust. Currently only function decls and assign statements are supported. See the code snippet below.</p>
<pre class="lang-rust prettyprint-override"><code>fn foo( a: int, b: int, c: int ) -> int {
let a: int = bar(baz(x, y), z);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T20:03:21.760",
"Id": "416552",
"Score": "4",
"body": "Please tell us a bit about the language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T20:38:33.223",
"Id": "416557",
"Score": "0",
"body": "@200_success, language looks like rust, right now it supports function decls, assign statements and function call exprs. \nThis looks like\n```rust\nfn foo( a: int, b: int, c: int ) -> int {\n let a: int = bar(baz(x, y), z);\n}\n```\nI have added grammar.pest to make it more clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T15:03:47.987",
"Id": "416650",
"Score": "1",
"body": "No worries - welcome to Code Review! I hope you get some good answers (I don't know Rust myself, so not willing to stick my neck out here!)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T19:34:18.263",
"Id": "215377",
"Score": "2",
"Tags": [
"rust",
"compiler"
],
"Title": "Parser for simple esoteric language in Rust"
} | 215377 |
<p>I have implemented a simple do/while loop to handle a http request to a third-party. I don’t know when the data I receive will have elements in its array so I retry up to 10 times until the array given to me has data which then I stop and store the data in my database.</p>
<p>My question is in terms of performance is my API going to be affected by having this retry mechanism using a simple do/while loop? If so what is a better way to implement a retry mechanism like this??</p>
<pre><code>public MAX_RETRY = 10;
public async processMetrics(sessionId: any, side: any): Promise <any> {
try {
let metrics;
let retryAttempts = 0;
do {
await new Promise((done) => setTimeout(done, 2000));
metrics = await this.getMetrics(session._id, sessionRequest._id);
retryAttempts++;
} while (!metrics.body.metrics.length && (retryAttempts < this.MAX_RETRY));
// Store in DB
} catch (err) {
}
}
public async getMetrics(sessionId: any, requestId: any): Promise <any> {
const url = this.config.backendUrl + "/check/metrics";
const options = {
uri: url,
headers: {
"X-IDCHECK-SESSION_ID": sessionId,
},
body: {},
json: true,
resolveWithFullResponse: true,
};
const metrics = await request.get(options);
return metrics;
}
</code></pre>
<p>I am calling processMetrics from a different async function. processMetrics is calling a backend (getMetrics) every 2 seconds, it will retry 10 times to see if the result is ready. If it is I will store something in the database and then return.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T21:33:27.723",
"Id": "417372",
"Score": "0",
"body": "So this seems to be within the context of a class. You should include the entire class for review so full context can be seen. Also this appears to be Typescript, so you should ad that to your tags."
}
] | [
{
"body": "<p>In terms of performance this should not be an issue, because async operations don't block the event loop, meaning your server will happily accept incoming requests in between the retries. Once in 2 seconds it will be busy making the request to the 3rd party API, but other than that your will not be blocking the main thread.</p>\n\n<p>(You can verify that by shooting requests to your API while it is in the while loop).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T17:11:12.010",
"Id": "216434",
"ParentId": "215381",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T22:13:08.963",
"Id": "215381",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"error-handling",
"http",
"express.js"
],
"Title": "Node.js http retry do while mechanism"
} | 215381 |
<p>I have the following working code to calculate the potential of a matrix after normalizing the matrix. But it is too much time consuming. Is there a way to make this code run faster?</p>
<pre><code>import csv
import numpy as np
from normalization import normalized_matrix
n = len(normalized_matrix)
sigma = 1
potential_writer = csv.writer(open('potential.csv', 'w'))
for l in range(n):
elem = []
for j in range(len(normalized_matrix[0])):
GWF = 0
PotSecPart = 0
for i in range(n):
if (i!=l):
PotSecPart = (PotSecPart + (((normalized_matrix[l][j] - normalized_matrix[i][j])**2)*(np.exp((-(normalized_matrix[l][j] - normalized_matrix[i][j])**2)/(2*(sigma**2))))))
GWF = GWF + (np.exp((-(normalized_matrix[l][j] - normalized_matrix[i][j])**2)/(2*(sigma**2))))
PotFirPart = (2*(sigma**2))* GWF
elem.append(np.round(PotSecPart/PotFirPart, 2))
potential_writer.writerows([elem])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T00:27:52.867",
"Id": "416568",
"Score": "4",
"body": "For the uninitiated, what is a potential of a matrix?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T02:04:37.053",
"Id": "416569",
"Score": "0",
"body": "How long does this take you to run?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T02:43:17.870",
"Id": "416572",
"Score": "0",
"body": "it is running continuously for the last 13 hours without any output."
}
] | [
{
"body": "<p>Your code loops N x M x N times, where N is currently 424600 and M is 55. I don't think it's going to finish. </p>\n\n<p>I tried a couple of variations of your code, and the results are below. The version marked \"original\" is pretty true to your original code, except that I returned the results instead of storing them in a file. (So I could compare them against the original version.)</p>\n\n<p>The version marked \"fortran\" is an attempt to change the internal arrangement of data in the array, to try to get better cache performance out of consecutive reads. It didn't work, but I may not have done it right, or I maybe should have done it on the numpyier version. (It's late, I'm tired, sorry.)</p>\n\n<p>The \"cached\" version is the original code, but I tried to cache everything I could to eliminate repeated reads of the same items. I also tried to eliminate repeated sub-expressions, and I eliminated the <code>sigma</code> variable, since it was 1 and never changed.</p>\n\n<p>The \"numpyier\" version uses numpy operations in the inner loop. There may be a way to do the same thing with the columns, doing a 2-d computation and eliminating the middle loop as well. Someone better at numpy than I am may be able to provide that. At any rate, this version does not produce quite the same results, but they're close and it runs a lot faster. </p>\n\n<pre><code>import sys\nimport csv\nfrom timeit import timeit\n\nimport numpy as np\n#from normalization import normalized_matrix\n#MAKE_ROWS = 424600\nMAKE_ROWS = 424\nMAKE_COLS = 55\nnormalized_matrix = np.random.rand(MAKE_ROWS, MAKE_COLS)\n\ndef do_original():\n print(f\"Original method\", file=sys.stderr)\n n = len(normalized_matrix)\n sigma = 1\n #potential_writer = csv.writer(open('pot_orig.csv', 'w'))\n writer = []\n\n for l in range(n):\n elem = []\n for j in range(len(normalized_matrix[0])):\n GWF = 0\n PotSecPart = 0\n for i in range(n):\n if (i!=l):\n PotSecPart = (PotSecPart + (((normalized_matrix[l][j] - normalized_matrix[i][j])**2)*(np.exp((-(normalized_matrix[l][j] - normalized_matrix[i][j])**2)/(2*(sigma**2))))))\n GWF = GWF + (np.exp((-(normalized_matrix[l][j] - normalized_matrix[i][j])**2)/(2*(sigma**2))))\n PotFirPart = (2*(sigma**2))* GWF\n elem.append(np.round(PotSecPart/PotFirPart, 2))\n #potential_writer.writerows([elem])\n writer.append(elem)\n return writer\n\ndef do_cached():\n print(f\"Cached method\", file=sys.stderr)\n num_rows = len(normalized_matrix)\n num_cols = len(normalized_matrix[0])\n\n sigma = 1\n #potential_writer = csv.writer(open('pot_orig.csv', 'w'))\n writer = []\n\n exp = np.exp\n\n for l in range(num_rows):\n elem = []\n for j in range(num_cols):\n GWF = 0\n PotSecPart = 0\n\n nm_lj = normalized_matrix[l][j]\n\n for i in range(num_rows):\n if i != l:\n nm_ij = normalized_matrix[i][j]\n diff_sq = (nm_lj - nm_ij) ** 2\n exp_diff_sq_2 = exp(-diff_sq/2)\n\n PotSecPart += diff_sq * exp_diff_sq_2\n GWF += exp_diff_sq_2\n PotFirPart = 2 * GWF\n elem.append(np.round(PotSecPart/PotFirPart, 2))\n #potential_writer.writerows([elem])\n writer.append(elem)\n return writer\n\ndef do_fortran():\n print(f\"Fortran (cached) method\", file=sys.stderr)\n matrix = normalized_matrix\n shape = matrix.shape\n matrix = np.reshape(matrix, shape, order='F')\n num_rows, num_cols = shape\n\n sigma = 1\n #potential_writer = csv.writer(open('pot_orig.csv', 'w'))\n writer = []\n\n exp = np.exp\n\n for l in range(num_rows):\n elem = []\n for j in range(num_cols):\n GWF = 0\n PotSecPart = 0\n\n nm_lj = matrix[l][j]\n\n for i in range(num_rows):\n if i != l:\n nm_ij = matrix[i][j]\n diff_sq = (nm_lj - nm_ij) ** 2\n exp_diff_sq_2 = exp(-diff_sq/2)\n\n PotSecPart += diff_sq * exp_diff_sq_2\n GWF += exp_diff_sq_2\n PotFirPart = 2 * GWF\n elem.append(np.round(PotSecPart/PotFirPart, 2))\n #potential_writer.writerows([elem])\n writer.append(elem)\n return writer\n\ndef do_numpyier():\n print(f\"Numpy-ier method\", file=sys.stderr)\n matrix = normalized_matrix\n num_rows, num_cols = normalized_matrix.shape\n\n sigma = 1\n #potential_writer = csv.writer(open('pot_orig.csv', 'w'))\n writer = []\n\n exp = np.exp\n\n for l in range(num_rows):\n elem = []\n for j in range(num_cols):\n GWF = 0\n PotSecPart = 0\n\n nm_lj = normalized_matrix[l][j]\n\n diff_sq = (nm_lj - matrix[:, j]) ** 2\n np.delete(diff_sq, l)\n exp_diff_sq_2 = exp(-diff_sq / 2)\n np.delete(exp_diff_sq_2, l)\n\n PotSecPart = np.sum(diff_sq * exp_diff_sq_2)\n GWF = np.sum(exp_diff_sq_2)\n PotFirPart = 2 * GWF\n\n elem.append(np.round(PotSecPart/PotFirPart, 2))\n #potential_writer.writerows([elem])\n writer.append(elem)\n return writer\n\nif __name__ == '__main__':\n #orig = do_original()\n #print(timeit('do_original()', globals=globals(), number=1))\n #cached = do_cached()\n #assert cached == orig\n print(timeit('do_cached()', globals=globals(), number=1))\n #fortran = do_fortran()\n #assert fortran == orig\n #print(timeit('do_fortran()', globals=globals(), number=1))\n #numpyier = do_numpyier()\n #assert numpyier == cached\n print(timeit('do_numpyier()', globals=globals(), number=1))\n</code></pre>\n\n<p>The cached version was a little better than 2x faster than the original version, when I ran it on a 42x55 array. After a few passes, I stopped running the original.</p>\n\n<p>The fortran version surprised me, because I expected to see better performance. Its results were consistently a smidge faster (.01-.02 sec) than the cached version, but that's it.</p>\n\n<p>The numpyier version uses numpy operations to do the individual element calculations. This effectively replaces the inner loop with C. </p>\n\n<p><strong>Please Note:</strong> The numpyier version gets <strong>different results</strong> than your python-only version. The differences are typically +/- 0.01 in your rounded output. But they're different, and I haven't looked into why.</p>\n\n<p>I did most of my work at a shape of 42 x 55. That was in the 3-second range for me, about what I was willing to run repeatedly. After I got the numpyier version sort-of working, and satisfied myself that the differences were small, I ran it again with a shape of 424 x 55. That's 10 times bigger, which means 100x slower since this is an <span class=\"math-container\">\\$n^2\\$</span> operation. The results were:</p>\n\n<pre><code>Cached method\n114.699519728\nNumpy-ier method\n4.552203466999998\n</code></pre>\n\n<p>This seems intuitively correct: the numpy-ier version eliminates the python inner loop in favor of C looping operations, reducing the runtime by a factor of 424. The results are 23x faster, which is on the order of 100x. </p>\n\n<p>Note that this suggests that increasing the shape by a factor of 1000 (424600 instead of 424) would increase the runtime by somewhere between 1,000x and 1,000,000x. The numpyier version would require somewhere between 4000 seconds (1 hr, 20 mins) and 4,000,000 seconds (50 days).</p>\n\n<p>I am working on a 10+ year old, 32-bit laptop. Your mileage is very likely going to be better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T03:21:58.923",
"Id": "215391",
"ParentId": "215385",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T23:54:18.487",
"Id": "215385",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"matrix",
"numpy"
],
"Title": "Calculating the potential of a matrix of size (424600, 55)"
} | 215385 |
<p>Feature requirements.</p>
<ul>
<li>I can move a square box.</li>
<li>I can resize a square box by stretching four edges.</li>
<li>Many square boxes can exist.</li>
</ul>
<p>I've implemented moving and resizing square boxes by module pattern. Of course, I thought making a square box as a <code>Class</code>. But I think that using module pattern is better in this case. </p>
<p>Module Pattern</p>
<ul>
<li>Pros
<ul>
<li>Can manage only focused element. Don't need to care about unfocused elements. </li>
<li>Can control event handling in it.</li>
<li>Can hide private variables and methods.</li>
</ul></li>
<li>Cons
<ul>
<li>Maybe need many changes by changing features.</li>
<li>Test issue.</li>
</ul></li>
</ul>
<p>Class</p>
<ul>
<li>Pros
<ul>
<li>Can manage and maintain properties of each square box.</li>
<li>Can be more clean code.</li>
</ul></li>
<li>Cons
<ul>
<li>Should manage many instances.</li>
<li>Should add additional information to the DOM for finding each instance.</li>
</ul></li>
</ul>
<p>So, I implemented as module pattern. It looks like not good for test and can be more clear code. What should I do more for clean code or more testable? </p>
<p><a href="https://jsfiddle.net/docf1t40/2/" rel="nofollow noreferrer">https://jsfiddle.net/docf1t40/2/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>
<html>
<head>
<title>Practice</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.plate {
position: absolute;
width: 100%;
height: 100%;
background: rgb(240, 240, 240);
}
.edge {
position: absolute;
width: 12px;
height: 12px;
border-radius: 6px;
background: rgb(211, 211, 211);
}
.edge.lt {
top: -6px;
left: -6px;
cursor: nwse-resize;
}
.edge.rt {
top: -6px;
right: -6px;
cursor: nesw-resize;
}
.edge.lb {
bottom: -6px;
left: -6px;
cursor: nesw-resize;
}
.edge.rb {
bottom: -6px;
right: -6px;
cursor: nwse-resize;
}
</style>
</head>
<body>
<script type="text/javascript">
const Square = (function() {
let userAction;
let focusedElement = {
DOM: null,
width: 0,
height: 0,
screenX: 0,
screenY: 0,
translateX: 0,
translateY: 0,
};
function focusElement(dom, width, height, sx, sy, tx, ty) {
focusedElement.DOM = dom;
focusedElement.width = width;
focusedElement.height = height;
focusedElement.screenX = sx;
focusedElement.screenY = sy;
focusedElement.translateX = tx;
focusedElement.translateY = ty;
}
function blurElement() {
focusedElement = {
DOM: null,
width: 0,
height: 0,
screenX: 0,
screenY: 0,
translateX: 0,
translateY: 0,
};
}
function getMovement(sx, sy) {
return {
x: sx - focusedElement.screenX,
y: sy - focusedElement.screenY
};
}
function move(sx, sy) {
const movement = getMovement(sx, sy);
const tx = focusedElement.translateX + movement.x;
const ty = focusedElement.translateY + movement.y;
focusedElement.DOM.style.transform = `translate(${tx}px, ${ty}px)`;
}
function resize(sx, sy) {
const movement = getMovement(sx, sy);
let tx = focusedElement.translateX;
let ty = focusedElement.translateY;
let width = focusedElement.width;
let height = focusedElement.height;
switch (userAction) {
case 'RESIZE-LT':
width = focusedElement.width - movement.x;
height = focusedElement.height - movement.y;
tx = focusedElement.translateX + movement.x;
ty = focusedElement.translateY + movement.y;
break;
case 'RESIZE-RT':
width = focusedElement.width + movement.x;
height = focusedElement.height - movement.y;
ty = focusedElement.translateY + movement.y;
break;
case 'RESIZE-LB':
width = focusedElement.width - movement.x;
height = focusedElement.height + movement.y;
tx = focusedElement.translateX + movement.x;
break;
case 'RESIZE-RB':
width = focusedElement.width + movement.x;
height = focusedElement.height + movement.y;
break;
}
width = Math.max(50, width);
height = Math.max(50, height);
focusedElement.DOM.style.transform = `translate(${tx}px, ${ty}px)`;
focusedElement.DOM.style.width = `${width}px`;
focusedElement.DOM.style.height = `${height}px`;
}
function onMouseDown(e) {
if (e.target && e.target.dataset && e.target.dataset.userAction) {
let tx = 0;
let ty = 0;
const transform = e.target.parentNode.style.transform;
const matchTranslate = transform.match(/translate\((-?\d+.?\d*)px ?, ?(-?\d+.?\d*)px\)/);
if (matchTranslate) {
tx = parseInt(matchTranslate[1]);
ty = parseInt(matchTranslate[2]);
}
focusElement(
e.target.parentNode,
parseInt(e.target.parentNode.style.width),
parseInt(e.target.parentNode.style.height),
e.screenX,
e.screenY,
tx,
ty
);
userAction = e.target.dataset.userAction;
}
}
function onMouseUp(e) {
blurElement();
userAction = null;
}
function onMouseMove(e) {
switch (userAction) {
case 'MOVE':
move(e.screenX, e.screenY);
break;
case 'RESIZE-LT':
case 'RESIZE-RT':
case 'RESIZE-LB':
case 'RESIZE-RB':
resize(e.screenX, e.screenY);
break;
}
}
return {
create: function(x, y, width, height) {
const div = document.createElement('div');
div.setAttribute('style', `position:absolute; width:${width}px; height:${height}px; transform: translate(${x}px, ${y}px)`);
div.innerHTML = `<div data-user-action="MOVE" class="plate"></div>
<span data-user-action="RESIZE-LT" class="edge lt"></span>
<span data-user-action="RESIZE-RT" class="edge rt"></span>
<span data-user-action="RESIZE-LB" class="edge lb"></span>
<span data-user-action="RESIZE-RB" class="edge rb"></span>`;
document.body.appendChild(div);
},
onMouseDownListener: onMouseDown,
onMouseUpListener: onMouseUp,
onMouseMoveListener: onMouseMove,
}
})();
document.addEventListener('DOMContentLoaded', function() {
Square.create(300, 300, 100, 200);
Square.create(200, 100, 80, 80);
document.addEventListener('mousedown', Square.onMouseDownListener);
document.addEventListener('mouseup', Square.onMouseUpListener);
document.addEventListener('mousemove', Square.onMouseMoveListener);
});
</script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2><code>class</code> syntax</h2>\n<p>In JS <code>class</code> is a syntax for creating objects. It is not an independent distinct entity. Class creates an object adding a <code>constructor</code> function and assigning functions and (optionally) properties to the associated prototype. It does not provide any features not available using standard syntax.</p>\n<p>The 'class` syntax does suffer from one serious flaw (that in my book makes it unusable). It lacks a mechanism to create private functions and properties. Objects created via the class syntax can not adequately encapsulate an objects state, an essential requirement of OO design.</p>\n<h2>Modules</h2>\n<p>In modern JS module, modules, modular, etc... refers to code that is import/export able.</p>\n<p>Modules provide a local and isolated scope (state) that does provide some encapsulation for single instance objects created with the <code>class</code> syntax. The same can be achieved with the IIS style and <code>class</code> syntax.</p>\n<h2>Objects</h2>\n<p>Your code is a IIF, or IIFE meaning Immediately Invoked Function Expression <code>const obj=(() => ({foo: "bar", log() {console.log(this.foo)}}))()</code> It provides the best encapsulation mechanism for single instance objects (such as your example)</p>\n<p>A variation is an object factory <code>function obj() { return {foo: "bar", log() {console.log(this.foo)}} }</code> best suited to long lived multi instance objects.</p>\n<p>For performance and many (100 to 1000+) instances of short lived objects, the prototype model is best suited. <code>function Obj() { this.foo = "bar" }; Obj.prototype = { log() {console.log(this.foo)}};</code> However the encapsulation model is not as strong.</p>\n<p>Modern JS engines cache compiled code, thus you can define the prototype inside the function with only a minor memory penalty (prototyped properties and functions each need a reference per object) This lets you use closure to encapsulate state and still provide prototypal inheritance. However I would argue that in JS polymorphisum is the preferred method of extension for JS objects (though not everyone would agree).</p>\n<p>There are many more ways to define and instanciate objects. Which you use is defined by how the object is to be used, and what your preferred style is.</p>\n<h2>Reviewing your code</h2>\n<ul>\n<li><p>The mouse event provides delta mouse position in <code>MouseEvent.movementX</code> and <code>MouseEvent.movementY</code> so you don't need to function <code>getMovement</code></p>\n</li>\n<li><p>You should not expose the mouse events for <code>Square</code>. Have <code>Square.create</code> add the events if needed.</p>\n</li>\n<li><p>You can simplify the resize and move logic by treating the corners as part of a side (top, bottom, left, and right) then you move only a side, left or right, top or bottom. Using a bitfield to define corners you can then specify which sides to move for each corner. (see example)</p>\n</li>\n<li><p>It is best not to add markup to the page. Use the DOM API to manipulate the DOM. I find the API somewhat awkward so use some helper functions to improve readability and reduce code noise. (see example <code>/* DOM helpers */</code>)</p>\n</li>\n<li><p>Rather than inspecting the DOM element to get its position and size, assign your <code>focusElement</code> to each size-able element as you create it. Use a <code>Map</code> to make the association. You can then just get that object using the element as key on mouse down (see example) Note that I assume your example is self contained and that there is no manipulation of relevant elements outside the <code>Square</code> object</p>\n</li>\n<li><p>You update the DOM elements position in two places. Use a single function to update the position (and size) of the element.</p>\n</li>\n<li><p>To reduce code complexity use the <code>MouseEvent.type</code> property to determine the event type and handle all similar mouse events in one function.</p>\n</li>\n<li><p>Mouse events are out of sync with the display refresh. For the cleanest updates you should be using <code>requestAnimationFrame</code> to update elements. <code>requestAnimationFrame</code> ensures that backbuffers associated with elements that are rendered from within the callback are only presented during the displays vertical sync.</p>\n</li>\n</ul>\n<h2>Example</h2>\n<p>Uses same IIF style to encapsulate the object (renamed <code>Squares</code> as it can represent many)</p>\n<p>Removed the 3 exposed <code>onMouse...</code> functions.</p>\n<p>The aim was to reduce source size and improve efficiency.</p>\n<p>Creates a <code>boxDesc</code> for each box mapped to the element, rather than updating the one <code>focusElement</code> object.</p>\n<p>I did not include the use of <code>requestAnimationFrame</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> const Squares = (() => {\n /* Privates */\n var addMouseEvents = true, focus; \n const boxMap = new Map();\n const corners = { // bit fields \n none: 0, // 0b0000\n top: 1, // 0b0001\n bottom: 2, // 0b0010\n left: 4, // 0b0100\n right: 8, // 0b1000\n };\n const MIN_SIZE = 50;\n const HANDLE_SIZE = 8; // adds 2 px\n\n /* DOM helpers */\n const tag = (name, props ={}) => Object.assign(document.createElement(name), props);\n const elStyle = (el, style) => (Object.assign(el.style, style), el);\n const elData = (el, data) => (Object.assign(el.dataset, data), el);\n const append = (par, ...sibs) => {\n for(const sib of sibs) { par.appendChild(sib) }\n return par;\n };\n\n const boxDesc = (DOM, width, height, x, y) => ({ DOM, width, height, x, y });\n function update(box) {\n box.width = box.width < MIN_SIZE ? MIN_SIZE : box.width;\n box.height = box.height < MIN_SIZE ? MIN_SIZE : box.height;\n const right = innerWidth - (box.width + HANDLE_SIZE);\n const bot = innerHeight - (box.height + HANDLE_SIZE);\n box.x = box.x < HANDLE_SIZE ? HANDLE_SIZE : box.x > right ? right : box.x;\n box.y = box.y < HANDLE_SIZE ? HANDLE_SIZE : box.y > bot ? bot : box.y;\n elStyle(box.DOM, {\n transform: `translate(${box.x}px, ${box.y}px)`,\n width: box.width + \"px\",\n height: box.height + \"px\",\n });\n return box;\n }\n function move(box, dx, dy) {\n const bot = innerHeight - HANDLE_SIZE;\n const right = innerWidth - HANDLE_SIZE;\n if (box.action === corners.none) {\n box.x += dx;\n box.y += dy;\n } else {\n if ((box.action & corners.bottom) === corners.bottom) { \n box.height = box.y + box.height + dy > bot ? bot - box.y : box.height + dy;\n } else {\n if (box.height - dy < MIN_SIZE) { dy = box.height - MIN_SIZE }\n if (box.y + dy < HANDLE_SIZE) { dy = HANDLE_SIZE - box.y }\n box.y += dy;\n box.height -= dy;\n }\n if ((box.action & corners.right) === corners.right) { \n box.width = box.x + box.width + dx > right ? right - box.x : box.width + dx;\n } else {\n if (box.width - dx < MIN_SIZE) { dx = box.width - MIN_SIZE }\n if (box.x + dx < HANDLE_SIZE) { dx = HANDLE_SIZE - box.x }\n box.x += dx;\n box.width -= dx;\n }\n }\n update(box);\n }\n function mouseEvent(e) {\n if(e.type === \"mousedown\") {\n if (e.target.dataset && e.target.dataset.userAction) {\n focus = boxMap.get(e.target.parentNode);\n focus.action = Number(e.target.dataset.userAction);\n }\n }else if(e.type === \"mouseup\") { focus = undefined }\n else {\n if (e.buttons === 0) { focus = undefined } // to stop sticky button in snippet\n if (focus) { move(focus, e.movementX, e.movementY) }\n }\n }\n function mouseEvents() {\n document.addEventListener('mousedown', mouseEvent);\n document.addEventListener('mouseup', mouseEvent);\n document.addEventListener('mousemove', mouseEvent); \n addMouseEvents = false; \n }\n return {\n create(x, y, width, height) {\n const box = append( \n elStyle(tag(\"div\"), { position: \"absolute\" }),\n elData(tag(\"div\", {className : \"plate\"}), {userAction : corners.none}),\n elData(tag(\"span\", {className : \"edge lt\"}), {userAction : corners.top + corners.left}),\n elData(tag(\"span\", {className : \"edge rt\"}), {userAction : corners.top + corners.right}),\n elData(tag(\"span\", {className : \"edge lb\"}), {userAction : corners.bottom + corners.left}),\n elData(tag(\"span\", {className : \"edge rb\"}), {userAction : corners.bottom + corners.right})\n );\n boxMap.set(box, update(boxDesc(box, width, height, x, y))); // update() sizes and positions elements\n append(document.body, box);\n if (addMouseEvents) { mouseEvents() }\n }\n };\n\n})();\n\ndocument.addEventListener('DOMContentLoaded', function() {\n Squares.create(10, 100, 80, 80);\n Squares.create(110, 100, 80, 80);\n Squares.create(210, 100, 80, 80);\n Squares.create(310, 100, 80, 80);\n Squares.create(410, 100, 80, 80);\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n user-select: none; \n -moz-user-select: none; \n}\n.plate {\n position: absolute;\n width: 100%;\n height: 100%;\n background: rgb(240, 240, 240);\n cursor: move;\n}\n.plate:hover {\n background: #DEE;\n}\n.edge {\n position: absolute;\n width: 12px;\n height: 12px;\n border-radius: 6px;\n background: rgb(211, 211, 211);\n}\n.edge:hover {\n background: #CDD;\n}\n.edge.lt {\n top: -6px;\n left: -6px;\n cursor: nwse-resize;\n}\n.edge.rt {\n top: -6px;\n right: -6px;\n cursor: nesw-resize;\n}\n.edge.lb {\n bottom: -6px;\n left: -6px;\n cursor: nesw-resize;\n}\n.edge.rb {\n bottom: -6px;\n right: -6px;\n cursor: nwse-resize;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T16:27:45.043",
"Id": "215430",
"ParentId": "215388",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215430",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T01:47:17.007",
"Id": "215388",
"Score": "3",
"Tags": [
"javascript",
"html",
"dom",
"revealing-module-pattern"
],
"Title": "Move and resize square boxes with Vanilla JS"
} | 215388 |
<p>I have piece metaled this code together from multiple google searches and thanks to the function from the site mentioned in the code. I am sure there are ways to optimize this for speed. What do you guys suggest?</p>
<pre><code>using System;
using System.Globalization;
public class Program
{
public static void Main()
{
string shortmonth = "Mar";
string num = GetMonthNumberFromAbbreviation(shortmonth);
string monthname = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Convert.ToInt32(num));
Console.WriteLine(monthname);
}
//https://blogs.msmvps.com/deborahk/converting-month-abbreviations-to-month-numbers/
private static string GetMonthNumberFromAbbreviation(string mmm)
{
string[] monthAbbrev =
CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames;
int index = Array.IndexOf(monthAbbrev, mmm) + 1;
return index.ToString("0#");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T07:30:15.147",
"Id": "416584",
"Score": "4",
"body": "So you pass in the 3-letter English month abbreviation and expect the full name in the current locale. This mix of languages should be documented in the function's comment."
}
] | [
{
"body": "<p>You can speed up the program by changing the return type from string to int. If it's a number (of the kind you can do calculations with, not something like a phone number), it should be represented as an int, not as a string.</p>\n\n<p>As long as you can ensure that the locale doesn't change, you can cache the full month names in an array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T07:33:11.033",
"Id": "215400",
"ParentId": "215389",
"Score": "0"
}
},
{
"body": "<p>The following avoids assumptions about and/or the need to convert according to culture, by letting the tried-and-tested DateTime plumbing do the work. Creating a translation map once at first instantiation of the class (the static constructor) is the best I can think of to optimise performance.</p>\n\n<p>If you use it, don't forget to do error-checking - specifically the result of TryParse.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\npublic class Program\n{\n private static readonly Dictionary<string, string> MonthNameMap;\n // Static constructor to build the translation dictionary once\n static Program()\n {\n MonthNameMap = new Dictionary<string, string>();\n //var months = new List<string>() { \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\" };\n //foreach (var shortMonthString in months)\n //{\n // DateTime.TryParse($\"1 {shortMonthString} 2000\", out var dt);\n // MonthNameMap.Add(shortMonthString, dt.ToString(\"MMMM\"));\n //}\n for (int i = 1; i <= 12; i++)\n {\n DateTime.TryParse($\"2000-{i}-25\", out var dt);\n MonthNameMap.Add(dt.ToString(\"MMM\"), dt.ToString(\"MMMM\"));\n }\n }\n\n public static void Main()\n {\n foreach (var entry in MonthNameMap)\n {\n Console.WriteLine($\"{entry.Key}: {entry.Value}\");\n }\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>Jan: January\nFeb: February\nMar: March\nApr: April\nMay: May\nJun: June\nJul: July\nAug: August\nSep: September\nOct: October\nNov: November\nDec: December\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T09:16:30.430",
"Id": "215407",
"ParentId": "215389",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215407",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T02:25:14.533",
"Id": "215389",
"Score": "1",
"Tags": [
"c#",
"performance"
],
"Title": "Return Full Month Name From 3 Letter Month"
} | 215389 |
<p>The use case that this code tries to meet is</p>
<p>There will be an interview session where the video calling is done between two participants, <code>interviewer(ER)</code> and <code>interviewee(EE)</code>. For this I need to have a video element and reference that video element using ref. For ER its a <code>localStreamRef</code> and for EE its <code>remoteStreamRef</code>. To use ref, i need to have that video element already because attaching the stream in the video element is done inside <code>componentDidMount</code> by listening to the sockets from there.</p>
<p>The conditions that I have to fulfill is, if the event is</p>
<ol>
<li>event1 - Show ER and EE screen</li>
<li>event2 - Only EE screen</li>
<li>event3 - Only ER screen</li>
<li>event4 - ER, EE and Screen Recording screen(this is also a video
element)</li>
<li>event5 - ER and SS</li>
<li>event6 - EE and SS</li>
<li>event7 - SS only</li>
</ol>
<p>To achieve this I did the code following way but its too repetitive. </p>
<pre><code>import React from "react";
import isElectron from "is-electron";
import styled from "styled-components";
const Wrapper = styled.div``;
const PowerPoint = styled.div`
color: #fff;
text-align: center;
background: #2d3561;
position: relative;
& > video {
position: absolute;
top: 0;
left: 0;
width: 100%;
object-fit: cover;
}
`;
const VideoPanel = styled.video`
max-width: 100%;
width: 400px;
height: auto;
transition: all 0.3s ease;
transform: rotateY(180deg);
-webkit-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
${props =>
props.left &&
`
position: absolute;
bottom: 50px;
left: 50px;
z-index: 1;
transition: all 1s ease;
width: 400px;
`};
${props =>
props.right &&
`
position: absolute;
bottom: 50px;
right: 50px;
z-index: 1;
transition: all 1s ease;
`}
&.fullscreen {
position: absolute;
top: 0;
left: 0;
transform: translateY(0);
width: 100%;
height: 100%;
}
`;
const VideoPanels = styled.div`
width: 100%;
height: auto;
position: absolute;
top: 80%;
left: 0;
width: 100%;
transform: translateY(-50%);
transition: all 0.3s ease;
&.fullscreen {
position: absolute;
top: 0;
left: 0;
transform: translateY(0);
${VideoPanel} {
width: 100%;
height: 100%;
}
}
`;
const user = JSON.parse(localStorage.getItem("user"));
const Studio = ({ interviewer, interviewee, ...props }) => {
const [hotkeys, setHotkeys] = React.useState("event4");
React.useEffect(() => {
return () => {
window.ipcRenderer.removeAllListeners("eventListened");
};
}, []);
React.useEffect(
() => {
console.log("user", user);
console.log(
"remoteJoined",
props.isRemoteJoined,
user !== null && user.data.isInterviewer
);
if (
isElectron() &&
props.isRemoteJoined &&
(user !== null && user.data.isInterviewer)
) {
window.ipcRenderer.on("eventListened", (event, hotkeys) => {
setHotkeys(hotkeys);
});
}
},
[props.isRemoteJoined]
);
const renderVideo = () => {
switch (hotkeys) {
case "event1":
return (
<React.Fragment>
<PowerPoint style={{ display: "none" }}>
<video autoPlay id="screenshare" style={{ display: "none" }} />
</PowerPoint>
<VideoPanel
ref={interviewer}
autoPlay
muted="muted"
id="local-media"
left
/>
<VideoPanel
ref={interviewee}
autoPlay
muted="muted"
id="remote-media"
className="fullscreen"
/>
</React.Fragment>
);
case "event2": {
return (
<React.Fragment>
<PowerPoint style={{ display: "none" }}>
<video autoPlay id="screenshare" style={{ display: "none" }} />
</PowerPoint>
<VideoPanel
ref={interviewer}
autoPlay
muted="muted"
id="local-media"
style={{ display: "none" }}
/>
<VideoPanel
ref={interviewee}
autoPlay
className="fullscreen"
id="remote-media interviewee-for-now"
/>
</React.Fragment>
);
}
case "event3": {
return (
<React.Fragment>
<PowerPoint style={{ display: "none" }}>
<video autoPlay id="screenshare" style={{ display: "none" }} />
</PowerPoint>
<VideoPanel
ref={interviewer}
autoPlay
muted="muted"
className="fullscreen"
/>
<VideoPanel
ref={interviewee}
autoPlay
id="remote-media"
style={{ display: "none" }}
/>
</React.Fragment>
);
}
case "event4": {
return (
<React.Fragment>
<PowerPoint>
<video autoPlay id="screenshare" />
</PowerPoint>
<VideoPanel ref={interviewer} autoPlay muted="muted" left />
<VideoPanel ref={interviewee} autoPlay id="remote-media" right />
</React.Fragment>
);
}
case "event5": {
return (
<React.Fragment>
<PowerPoint>
<video autoPlay id="screenshare" />
</PowerPoint>
<VideoPanel ref={interviewer} autoPlay muted="muted" />
<VideoPanel
ref={interviewee}
autoPlay
id="remote-media"
style={{ display: "none" }}
/>
</React.Fragment>
);
}
case "event6": {
return (
<React.Fragment>
<PowerPoint>
<video autoPlay id="screenshare" />
</PowerPoint>
<VideoPanel
ref={interviewer}
autoPlay
muted="muted"
style={{ display: "none" }}
/>
<VideoPanel ref={interviewee} autoPlay id="remote-media" />
</React.Fragment>
);
}
default:
return (
<React.Fragment>
<PowerPoint>
<video autoPlay id="screenshare" />
</PowerPoint>
<VideoPanels
className={
hotkeys === "event2" || hotkeys === "event3" ? "fullscreen" : ""
}
>
<VideoPanel ref={interviewer} autoPlay muted="muted" />
<VideoPanel ref={interviewee} autoPlay id="remote-media" />
</VideoPanels>
</React.Fragment>
);
}
};
console.log("hotkeys", hotkeys !== "event1");
return (
<React.Fragment>
<Wrapper>{renderVideo()}</Wrapper>
</React.Fragment>
);
};
export default Studio;
</code></pre>
<p>My question is, in the <code>renderVideo</code>, the code are too much duplicated due to many conditions. The styling to show the screen is done in that way. How can this code be refactored to make it clean and remove code duplication?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T04:14:02.487",
"Id": "416577",
"Score": "0",
"body": "I think for local stream display you have to have switch statements but what about remote stream? maybe just rendering all the video components (and powerpoint components), and passing all the stream data as props,then in the each child component check if the prop is empty or not in the componentLifeCycle methods? \n\nif the props is empty them don't render that video tag if no then attach the stream to the video element?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T04:18:52.670",
"Id": "416578",
"Score": "0",
"body": "I did not quite understand you. Can you put the sample code in the answer section, please?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T02:31:06.880",
"Id": "215390",
"Score": "1",
"Tags": [
"react.js",
"jsx"
],
"Title": "Conditionally show various video panels"
} | 215390 |
<p>I have this sorting algorithm which takes an array of dictionary values:</p>
<pre><code>guard var imageUrlString = anyImage.value as? [String:AnyObject] else { return }
</code></pre>
<p>I then loop through it, adding the values with the smallest <code>Int</code> key to a new array to be used afterward. Thus the values in this array of <code>AnyObjects</code> would go from 1 to n.</p>
<p>I was wondering if I could make it more concise.</p>
<pre><code>var values = [AnyObject]()
var keys = [String]()
var Done = false
var j = 1
while !Done {
for i in imageUrlString {
let key = Int(String(i.key.last!))
if j == key {
values.append(i.value)
keys.append(i.key)
print(i, " This is the i for in if ")
if imageUrlString.count == j {
print("Done yet: yes", values[0], " ", values[3])
Done = true
break;
}
j+=1
} else {
print("No,,.")
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:00:02.350",
"Id": "416587",
"Score": "0",
"body": "If `imageUrlString` is empty, you'll never be `Done`; Force-unwrapping `i.key.last` calls for trouble; The logic that makes sure that `values` has at least 4 elements isn't clear enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T15:29:13.280",
"Id": "416654",
"Score": "0",
"body": "@ielyamani imageUrlString will always have values its a prerequesit to enter the class with this sort"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T15:51:43.807",
"Id": "416655",
"Score": "2",
"body": "@Outsider Could you edit your question by adding all the necessary information so that it is easily reproducible in a playground?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T22:00:47.493",
"Id": "416745",
"Score": "0",
"body": "@ielyamani check the edit"
}
] | [
{
"body": "<p>Consider:</p>\n\n<pre><code>let dictionary = [\"3\": \"c\", \"1\": \"a\", \"2\": \"b”]\n</code></pre>\n\n<p>If you want to get separate arrays of <code>keys</code> and <code>values</code>, sorted by the order of the <code>Int</code> values of the keys, you can do:</p>\n\n<pre><code>let (keys, values) = dictionary.map { (Int($0.key) ?? 0, $0.value) } // get `Int` keys\n .sorted { $0.0 < $1.0 } // now sort by those `Int` values\n .reduce(into: ([Int](), [String]())) { arrays, entry in // divide that up into two arrays\n arrays.0.append(entry.0)\n arrays.1.append(entry.1)\n}\n</code></pre>\n\n<p>That results in a <code>keys</code> of <code>[1, 2, 3]</code> and <code>values</code> of <code>[\"a\", \"b\", \"c\"]</code>.</p>\n\n<p>But a key observation is that you actually have to explicitly sort your results. Dictionaries, unlike arrays, are unordered. E.g. regardless of what order the keys appeared in a dictionary literal or JSON, when you iterate through the key-value pairs in a dictionary, the order may be different. You have to convert to an array and sort it yourself if order is important.</p>\n\n<hr>\n\n<p>The above arbitrarily uses <code>0</code> for any keys (if any) that couldn’t be converted to an <code>Int</code>. If you just wanted to drop those entries, you could alternatively do:</p>\n\n<pre><code>let (keys, values) = dictionary.compactMap { entry in Int(entry.key).map { ($0, entry.value) } }\n .sorted { $0.0 < $1.0 } // now sort by those `Int` values\n .reduce(into: ([Int](), [String]())) { arrays, entry in // divide that up into two arrays\n arrays.0.append(entry.0)\n arrays.1.append(entry.1)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T13:42:51.357",
"Id": "215422",
"ParentId": "215392",
"Score": "0"
}
},
{
"body": "<h2>Making it to the promised land of <em>O(n)</em></h2>\n\n<p>To reproduce your code in a playground, a <code>Media</code> struct could be defined this way:</p>\n\n<pre><code>struct Media {\n let mediaUrl: String\n let postTimeStamp: String?\n let timeStamp: String //A double would be more appropriate\n\n init(mediaUrl: String, timeStamp: String, postTimeStamp: String? = nil) {\n self.mediaUrl = mediaUrl\n self.timeStamp = timeStamp\n self.postTimeStamp = postTimeStamp\n }\n}\n</code></pre>\n\n<p>Let's suppose the value of <code>imageUrlString</code> is this:</p>\n\n<pre><code>let imageUrlString: [String: Media] =\n [\"media1\": Media(mediaUrl: \"URL\", timeStamp: \"573889179.6991431\", postTimeStamp: \"573889189.73954\"),\n \"media4\": Media(mediaUrl: \"URL\", timeStamp: \"573889185.750419\"),\n \"media2\": Media(mediaUrl: \"URL\", timeStamp: \"573889181.49576\"),\n \"media3\": Media(mediaUrl: \"URL\", timeStamp: \"573889183.89598\")]\n\nvar values = [Media]()\n</code></pre>\n\n<p>Your code works by relying on the <strong>chance</strong> of having the last character read from the <code>imageUrlString</code> dictionary, equal the order of the element you want to append to the <code>values</code> array. </p>\n\n<p>Bear in mind that a dictionary is an unordered collection. And unless mutated, the order of elements stays the same. The worst case would be when, reading elements from the dictionary, yields elements in a reversed \"<em>order</em>\". In this case, you'll have to read from the dictionary <code>n*(n+1)/2</code> times, in order to build your <code>values</code> array. <a href=\"https://en.wikipedia.org/wiki/Big_O_notation\" rel=\"nofollow noreferrer\">In other terms</a>, this <em>algorithm</em> is has <em><code>O(n²)</code></em> time complexity (worst case), <em><code>O(n)</code></em> best case, and is not the proper <a href=\"https://stackoverflow.com/a/55061682/2907715\">Counting Sort</a> Algorithm which is <em><code>O(n)</code></em>. </p>\n\n<p>Here is an attempt to make this <em><code>O(n)</code></em>:</p>\n\n<pre><code>let tempo = Media(mediaUrl: \"\", timeStamp: \"\")\nvar values = Array(repeating: tempo, count: imageUrlString.count)\nvar keys = Array(repeating: \"\", count: imageUrlString.count)\n\nfor entry in imageUrlString {\n let index = Int(String(entry.key.last!))! - 1 //Force-unwrapping for brevity\n (keys[index], values[index]) = entry\n}\n</code></pre>\n\n<hr>\n\n<h2>Robustness</h2>\n\n<p>The code in question relies on external facts that are not checked in code. For example:</p>\n\n<ul>\n<li>If <code>imageUrlString</code> is empty, <code>Done</code> will never be mutated and thus the outer loop will be infinite;</li>\n<li>The order of the elements in the result array relies on the last character in a string;</li>\n<li>The last character in all the keys has to exist and be numerical for <code>j</code> to be incremented. Otherwise, you're in for another infinite loop;</li>\n<li>Breaking the outer loop relies on the digits at the end of the keys go from 1 to <em>at least</em> <code>imageUrlString.count</code>. </li>\n</ul>\n\n<hr>\n\n<h2>Breaking an outer loop</h2>\n\n<p>Instead of mutating the variable <code>Done</code> (which shouldn't be uppercased since it's an instance, not a class/type/struct/enum/etc), you can break from a nested loop this way:</p>\n\n<pre><code>OuterLoop: while true {\n for i in imageUrlString {\n ...\n if imageUrlString.count == j {\n break OuterLoop\n }\n ...\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Straight forward sorting</h2>\n\n<p>In Swift 5, Timsort is the algorithm that is going to be used by the standard library while sorting. It has better time complexity than Introsort and is more versatile and less memory greedy than O(n) sorting algorithms. </p>\n\n<p>So, why not just use it to sort the entries in <code>imageUrlString</code> by <code>timeStamp</code> or a some other more reliable criteria?</p>\n\n<pre><code>let values = imageUrlString.values\n .sorted(by: { $0.timeStamp < $1.timeStamp }) \n</code></pre>\n\n<p>(If you're sure that <code>timeStamp</code>s represent real numbers, you could cast them to Double before comparing them)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T00:19:59.477",
"Id": "416752",
"Score": "1",
"body": "Appreciate the in-depth answer! :]"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T23:49:25.020",
"Id": "215462",
"ParentId": "215392",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "215462",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T03:27:04.180",
"Id": "215392",
"Score": "0",
"Tags": [
"sorting",
"swift",
"ios",
"hash-map"
],
"Title": "Counting sort in Swift"
} | 215392 |
<p>I have an assignment to solve this problem. There are a total of 12 test case files, 1 of which that I have failed due to exceeding limit on the script.</p>
<blockquote>
<p><strong>Question Description</strong> </p>
<p>Bob has somehow managed to obtain a class list of <span class="math-container">\$N\$</span> students that
contains the name of the students, as well as their scores for an
exam. The task is to generate the rank of each student in the class
list. </p>
<p>Let <span class="math-container">\$S\$</span> be the number of students in the class list that have
obtained a higher score than student <span class="math-container">\$X\$</span>. The <strong>rank</strong> of student
<span class="math-container">\$X\$</span> in the class list is formally defined as <span class="math-container">\$(S+1)\$</span>. This means that if there are many students that obtain the same score, they will
all have the same rank. </p>
<p><strong>Input</strong></p>
<p>The first line of input contains a single integer <span class="math-container">\$N\$</span>, the number of
students in the class list.
<span class="math-container">\$N\$</span> lines will follow. Each line will describe one student in the following form: [name] [score]. </p>
<p><strong>Output</strong> </p>
<p>For each student, print the rank of the student in the following form:
[name] [rank]. These students should be printed in the <strong>same order as
the input.</strong> </p>
<p><strong>Limits</strong></p>
<ul>
<li><p>\$1 \leq N \leq 50000 </p></li>
<li><p>All the names of students will only contain uppercase and lowercase
English letters with no spaces. The names will not be more than 20
characters long. It is possible that there can be 2 students with the
same name. </p></li>
<li><p>All scores of students will range from 0 to 109 inclusive.</p></li>
</ul>
</blockquote>
<p>Does anyone have a solution to my problem? Do inform me if any more information is needed. Any other comments on coding styles and space complexities that may arise are also appreciated, though the focus should be the time.</p>
<p>Here's my code and test cases.</p>
<pre><code>import java.util.*;
//Comparator to rank people by score in ascending order
//No tiebreaking for equal scores is considered in this question
class PairComparator implements Comparator<List<Object>> {
public int compare(List<Object> o1, List<Object> o2) {
return (Integer)o1.get(0) - (Integer)o2.get(0);
}
}
public class Ranking {
private void run() {
Scanner sc = new Scanner(System.in);
ArrayList<List<Object>> inputPairs = new ArrayList<>();
ArrayList<String> nameIterList = new ArrayList<>();//To store names in scanned order
HashMap<String, Integer> dupeCount = new HashMap<>();//To consider cases where there are people with same names
int count = sc.nextInt();
for (int i=0;i<count;i++) {
String name = sc.next();
int score = sc.nextInt();
name = checkDuplicates(nameIterList,name,dupeCount);//returns a unique name after considering duplicates
List<Object> pair = List.of(score,name);//simulates a struct data structure in C with non-homogeneous elements
inputPairs.add(pair);
nameIterList.add(name);
}
Collections.sort(inputPairs, (new PairComparator()).reversed());//descending order sorting
HashMap<String,Integer> nameRank = new HashMap<>();//name and respective rank in O(1) time
makeTable(nameRank,inputPairs);
for (String name: nameIterList) {
System.out.println(String.format("%s %d",name.trim(),nameRank.get(name)));
} //for displaying purposes, repeated name is printed
}
public static void main(String[] args) {
Ranking newRanking = new Ranking();
newRanking.run();
}
public static void makeTable(HashMap<String,Integer> nameRank, ArrayList<List<Object>> inputPairs) {
int lowestRank = 1;
int previousScore = (Integer)inputPairs.get(0).get(0);
for (int i=0;i<inputPairs.size();i++) {
List<Object> pairs = inputPairs.get(i);
String name = (String) pairs.get(1);
int score = (Integer) pairs.get(0);
int currentRank = i+1;//default rank if there are no tiebreakers
if (score==previousScore) {
currentRank = lowestRank;//takes the smallest possible rank for a tie-breaker
} else {
lowestRank = currentRank;//updates the smallest possible rank as tie-breaker is broken
previousScore = score;
}
nameRank.put(name,currentRank);//updates HashMap
}
}
public static String checkDuplicates(ArrayList<String> nameList, String name, HashMap<String,Integer> dupeCount) {
if (dupeCount.containsKey(name)) {
int count = dupeCount.get(name);
dupeCount.replace(name,count+1); //updates the duplicateTable
return name+ new String(new char[count]).replace('\0', ' ');//new name is appending with spaces, trimmed later on
} else {//entry not found, add in as the first one
dupeCount.put(name,1);
return name;//no change
}
}
}
</code></pre>
<p><strong>Sample Inputs</strong></p>
<pre><code>25
Sloane 15
RartheCat 94
Taylor 34
Shark 52
Jayce 58
Westin 91
Blakely 6
Dexter 1
Davion 78
Saanvi 65
Tyson 15
Kiana 31
Roberto 88
Shark 55
MrPanda 25
Rar 26
Blair 12
RartheCat 81
Zip 74
Saul 58
ProfTan 77
SJShark 0
Georgia 79
Darian 44
Aleah 7
</code></pre>
<p><strong>Sample Output</strong></p>
<pre><code>Sloane 19
RartheCat 1
Taylor 15
Shark 13
Jayce 10
Westin 2
Blakely 23
Dexter 24
Davion 6
Saanvi 9
Tyson 19
Kiana 16
Roberto 3
Shark 12
MrPanda 18
Rar 17
Blair 21
RartheCat 4
Zip 8
Saul 10
ProfTan 7
SJShark 25
Georgia 5
Darian 14
Aleah 22
</code></pre>
| [] | [
{
"body": "<p>Your data model is slowing down your code.</p>\n\n<pre><code> ArrayList<List<Object>> inputPairs = new ArrayList<>();\n ArrayList<String> nameIterList = new ArrayList<>();//To store names in scanned order\n HashMap<String, Integer> dupeCount = new HashMap<>();//To consider cases where there are people with same names\n</code></pre>\n\n<p>Calling <code>ArrayList.add()</code> will add an item to the array list. If insufficient room exists in its storage area, the area reallocated double its previous size, and the information copied to the new storage area. With 50000 names, with an initial allocated space of 8 items, you will go through 13 reallocations of the <code>inputPairs</code> and <code>nameIterList</code> containers.</p>\n\n<p>The <code>HashMap</code> stores its information differently, but it will suffer from the same doubling of capacity steps, with an additional penalty of \"rebinning\" the contents into the proper bins.</p>\n\n<p>All of this takes time, and all of this can all be avoided by pre-allocating your storage container sizes. You know what the limit is: 50000. Alternately, you can read in <code>N</code> and then allocate properly sized storage containers.</p>\n\n<pre><code> int count = sc.nextInt();\n ArrayList<List<Object>> inputPairs = new ArrayList<>(count);\n ArrayList<String> nameIterList = new ArrayList<>(count);\n HashMap<String, Integer> dupeCount = new HashMap<>(count*2);\n</code></pre>\n\n<p>A <code>HashMap</code> will rebin by default at 75% capacity, so I've initialized it at double the required capacity, so it won't exceed the limit.</p>\n\n<hr>\n\n<p><code>ArrayList<List<Object>></code> may not be the worst storage structure to use, but it comes close. <code>List.of(score,name)</code> should allocate a specialized, immutable two-member structure to use for the list, but you still have to go through the overhead of the <code>List</code> interface to <code>.get()</code> at the members. Worst, the <code>score</code> has to be boxed from an efficient <code>int</code> into a full blown <code>Integer</code> object. This auto boxing takes both time and space. Worse, the additional object allocations will cause additional cache misses, slowing down the program. True, the <code>Integer</code> objects will probably all be interned varieties, due to their restricted range, but it all adds up to your time-limit-exceeded issue.</p>\n\n<p><code>List.of(score, name)</code> was used to avoid creating your own simple class:</p>\n\n<pre><code>class StudentRecord {\n String name;\n int score;\n}\n</code></pre>\n\n<p>Instead of 3 objects (at least) per student, you only have two: the <code>StudentRecord</code> and the <code>name</code>. Access to the member fields is fast; no <code>.get(int)</code> overhead. (But even this is overhead that you don't need!)</p>\n\n<hr>\n\n<p>Checking for duplicate names, and creating fake names to avoid the duplicates is a time wasting operation. We can avoid it, with a smarter algorithm.</p>\n\n<hr>\n\n<h3>The better way</h3>\n\n<p>First: let's simplify the data down to the bare minimum...</p>\n\n<pre><code>int count = sc.nextInt();\nString[] names = new String[count];\nint[] score = new int[count];\n</code></pre>\n\n<p>... two parallel arrays, one containing the student names (in order), and one containing the scores (in order).</p>\n\n<p>Let's jump to the middle...</p>\n\n<pre><code>int[] rank = new int[110];\n</code></pre>\n\n<p>You have 110 possible score values, each which corresponds to exactly one rank. If you have 5 students with a score of 109 and one student with a score of 108, then <code>rank[109]</code> should contain <code>1</code>, and <code>rank[108]</code> should contain <code>6</code>.</p>\n\n<p>Jumping to the end...</p>\n\n<pre><code>for(int i=0; i<count; i++) {\n System.out.printf(\"%s %d\\n\", name[i], rank[score[i]]);\n}\n</code></pre>\n\n<p>... prints out the student, looks up the rank corresponding to their score and prints that as well.</p>\n\n<h3>Creation of the <code>rank[]</code> array</h3>\n\n<p>Since this is a programming challenge, I'll leave this up to you. There are several ways to do it. Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:24:17.297",
"Id": "416595",
"Score": "0",
"body": "Hi, I like your ideas. Unfortunately, I have a small typo in my question that might cause a huge change to the solution. The range is 10^9 instead of 109, so I think the rank[] array now has to become a HashMap to handle a SparseMatrix representation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:47:02.617",
"Id": "416598",
"Score": "0",
"body": "For this scenario caused by the typo, I do think your scenario can work. In particular, using an array to store names did better than using an encryption mechanism to make unique names, I imparted your idea to the real problem and modified accordingly and it works. I will accept your answer here for someone who meets with similar problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T13:36:53.367",
"Id": "416633",
"Score": "0",
"body": "That’s a pretty big small typo. :-) Make sure you pre-allocate the required capacity in your sparse matrix `HashMap` for maximum efficiency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:13:57.273",
"Id": "416638",
"Score": "0",
"body": "Hmm, even in the previous implementation which has exceeded time limit, increasing the capacity still fails. My current implementation can pass the time limit even without allocating capacity, but thanks for the reminder"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T05:26:52.013",
"Id": "215396",
"ParentId": "215393",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "215396",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T03:51:15.897",
"Id": "215393",
"Score": "3",
"Tags": [
"java",
"algorithm",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Ranking Score System"
} | 215393 |
<h3>Functionality:</h3>
<p>This method removes a list of specific terms (e.g., LLC, INC, Inc, Company, etc.) from a list of public companies names. It is part of a class that can be viewed in this <a href="https://github.com/emarcier/usco/blob/master/master/cron/equity/EQ.php" rel="nofollow noreferrer">link</a>.</p>
<p>I'd appreciate it if you would possibly review it for best coding practices and efficiency. </p>
<h3>Method:</h3>
<pre><code>/**
*
* @return a string of company name without common words to be embedded in the URL
*/
public static function slugCompany($c){
$c=strtolower($c);
$c=preg_replace('/[^\da-z\s]/i', '', $c);
$words=self::COMPANY_STOPWORDS;
$c=preg_replace('/\b('.$words.')\b/i', '', $c);
$c=preg_replace('/(\s+)/i', '-', trim($c));
return $c;
}
</code></pre>
<h3>Constant:</h3>
<blockquote>
<p>const COMPANY_STOPWORDS =
'11000th|american|and|a|beneficial|bond|b|class|common|company|corporation|corp|commodity|cumulative|co|c|daily|dep|depositary|depository|debentures|diversified|due|d|each|etf|equal|equity|exchange|e|financial|fund|fixedtofloating|fixed|floating|f|group|g|healthcare|holdings|holding|h|inc|incorporated|interests|interest|in|index|income|i|junior|j|k|liability|limited|lp|llc|ltd|long|l|markets|maturity|municipal|muni|monthly|m|noncumulative|notes|no|n|of|one|or|o|portfolio|pay|partnership|partner|par|perpetual|per|perp|pfd|preference|preferred|p|q|redeemable|repstg|representing|represents|rate|r|sa|smallcap|series|shs|shares|share|short|stock|subordinated|ser|senior|s|the|three|term|to|traded|trust|two|t|ultrashort|ultra|u|value|v|warrant|weight|w|x|y|z';</p>
</blockquote>
<h3>Function Call:</h3>
<pre><code>$cn=strtolower(UpdateStocks::slugCompany($s["quote"]["companyName"]));
</code></pre>
<h3>Example Input:</h3>
<pre><code>AGILENT TECHNOLOGIES INC
ALCOA CORP
PERTH MINT PHYSICAL GOLD ETF
</code></pre>
<h3>Example Output:</h3>
<pre><code>agilent-technologies
alcoa
perth-mint-physical-gold
</code></pre>
<p>PHP7.1 </p>
| [] | [
{
"body": "<p>I would clean it up a bit:</p>\n\n<pre><code>public static function slugCompany($company){\n $replace = [\n '/[^\\da-z\\s]/i' => '', //remove punctuation I guess\n '/\\b('.self::COMPANY_STOPWORDS.')\\b/i' => '', //remove these companies\n '/^\\s+|\\s+$/' => '', //trim\n '/\\s+/' => '-' //replace space with -\n ];\n\n return preg_replace(array_keys($replace), $replace, strtolower($company));\n}\n</code></pre>\n\n<p>I cleaned up all these local variables, got rid of a few repetitive calls. The <code>array_keys</code> and array structure are mainly for readability reasons and ease of use. For example now you can easly add replacements if you need to because they use a common array for the replacements. </p>\n\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/3559ca89d8a68fdd7f0040f35018a1016f9edc4c\" rel=\"nofollow noreferrer\">Sandbox</a></p>\n\n<p>Its more of a readability fix as it's hard to know all the input you may have so I have to trust that you covered all the edge cases.</p>\n\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/336921b29a4d6e5207965a253dff4c64a1803840\" rel=\"nofollow noreferrer\">Your code</a></p>\n\n<p>Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T15:23:48.287",
"Id": "416859",
"Score": "1",
"body": "Sure all I did is re-arange some stuff. I usually write my own code 3 or 4 times before I am happy with it. Once to get it working, once to make it readable and once to improve the performance. Don't be afraid to say this is too much I need to simplify it. Its a process like writing an English paper."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T09:53:27.410",
"Id": "215489",
"ParentId": "215394",
"Score": "4"
}
},
{
"body": "<p>There are several things to point out here.</p>\n\n<p>For the record, I rewrote and tested the process without a class on my localhost -- the adjustment for you to convert my snippet to suit your class should be simple.</p>\n\n<p>New Snippet:</p>\n\n<pre><code>$slugs = <<<SLUGS\nAMERIS BANCORP\nALCENTRA CAPITAL CORP\nABEONA THERAPEUTICS INC\nSLUGS; // yes, I tested the entire battery\n\nconst COMPANY_STOPWORDS = '11000th|american|and|beneficial|bond|class|common|company|corporation|corp|commodity|cumulative|co|daily|dep|depositary|depository|debentures|diversified|due|each|etf|equal|equity|exchange|financial|fund|fixedtofloating|fixed|floating|group|healthcare|holdings|holding|inc|incorporated|interests|interest|in|index|income|junior|liability|limited|lp|llc|ltd|long|markets|maturity|municipal|muni|monthly|noncumulative|notes|no|of|one|or|portfolio|pay|partnership|partner|par|perpetual|per|perp|pfd|preference|preferred|redeemable|repstg|representing|represents|rate|sa|smallcap|series|shs|shares|share|short|stock|subordinated|ser|senior|the|three|term|to|traded|trust|two|ultrashort|ultra|value|warrant|weight|[a-z]';\n\nfunction slugCompany($slug){\n return trim(preg_replace(['/[^\\da-z\\s]+|\\b(?:' . COMPANY_STOPWORDS . ')\\b/', '/\\s+/'], ['', '-'], strtolower($slug)), '-');\n}\n\nforeach (explode(PHP_EOL, $slugs) as $slug) {\n echo \"<div>$slug => \" , slugCompany($slug) , \"</div>\";\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>AMERIS BANCORP => ameris-bancorp\nALCENTRA CAPITAL CORP => alcentra-capital\nABEONA THERAPEUTICS INC => abeona-therapeutics\n</code></pre>\n\n<hr>\n\n<p>First about your code...</p>\n\n<pre><code>public static function slugCompany($c){\n $c=strtolower($c);\n $c=preg_replace('/[^\\da-z\\s]/i', '', $c);\n $words=self::COMPANY_STOPWORDS;\n $c=preg_replace('/\\b('.$words.')\\b/i', '', $c);\n $c=preg_replace('/(\\s+)/i', '-', trim($c));\n return $c; \n}\n</code></pre>\n\n<ul>\n<li>You are making three separate passes through the string(s).</li>\n<li>You are inefficiently finding-replacing each individual \"non-digit/non-alpha/non-space\" character.</li>\n<li>You are making case-insensitive matching, but you know everything is already lowercase.</li>\n<li>The capture group on the third <code>preg_replace()</code> call is unnecessary.</li>\n<li>You should use one space on either side of the <code>=</code> assignment operator.</li>\n</ul>\n\n<hr>\n\n<p>Regarding ArtisticPhoenix's post, it makes a single <code>preg_replace()</code> call and places some importance on readability, but...</p>\n\n<pre><code>public static function slugCompany($company){\n $replace = [\n '/[^\\da-z\\s]/i' => '', //remove punctuation I guess\n '/\\b('.self::COMPANY_STOPWORDS.')\\b/i' => '', //remove these companies\n '/^\\s+|\\s+$/' => '', //trim\n '/\\s+/' => '-' //replace space with -\n ];\n\n return preg_replace(array_keys($replace), $replace, strtolower($company));\n}\n</code></pre>\n\n<ul>\n<li><code>preg_replace()</code> is making too many separate passes through the string(s).</li>\n<li>Case-insensitive matching is used, but everything is already lowercase.</li>\n</ul>\n\n<hr>\n\n<p>Some basic principles:</p>\n\n<ol>\n<li>Avoid using regular expressions if there is a single non-regex function that can do the same job in a sensible/readable manner. In my snippet, I am using <code>trim(..., '-')</code> to trim the leading/trailing hyphens rather than another replacement pass of <code>~^-+|-+$~</code>.</li>\n<li>Endeavor to reduce total function calls where it doesn't negatively impact your script logic. In this case, there is no use in calling <code>preg_replace()</code> multiple times because the function is happy to receive an array of patterns and an array of replacements.</li>\n<li>When multiple patterns share a duplicate replacement string, try to merge the two patterns -- this means the task is completed in one pass.</li>\n<li>When the intention is to matching multiple characters that may possibly be side-by-side, match as many as possible. <strong>Consider this scenario, you are standing over an open carton of eggs. I ask you to pick up all the eggs. Doing 12 squats to extract each egg individually (while good for personal health) is an obviously inefficient choice. Just reach down one time and pick up the whole carton -- done in one pass.</strong></li>\n<li>Don't use capture groups unless you actually need to capture substrings. While this extends the pattern length by 2 characters, it is a clear indication of pattern intention and removes the possibility of numbered backreferences associated with capture groups. In other words, use <code>(?:...)</code> versus <code>(...)</code>.</li>\n<li>Avoid declaring single-use variables. There are a few exceptions to this rule (like adding clarity to a line of code via a descriptive variable name AND to reduce horizontal scrolling in a script for devs), but in this case I felt returning a one-liner was tolerable.</li>\n<li>You can condense 26 of the alternatives in your <code>const</code> by writing <code>[a-z]</code> versus individually listing letters. This will improve pattern efficiency and pattern length.</li>\n<li>If pattern efficient is the highest priority <strong>AND</strong> the piped <code>const</code> values are very rarely modified, you <em>could</em> go the extra mile and try to reduce the number of \"alternatives\". For instance, you can combine <code>...|of|or|o|...</code> to be <code>...|o[fr]?|...</code> and so on. Some would say that this comes at a cost of readability/maintainability.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T08:05:13.710",
"Id": "217608",
"ParentId": "215394",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "215489",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T04:21:37.247",
"Id": "215394",
"Score": "-1",
"Tags": [
"performance",
"beginner",
"php",
"strings",
"regex"
],
"Title": "Sanitizing name strings using PHP"
} | 215394 |
<p>I implemented a 2D counterpart of <a href="https://en.cppreference.com/w/cpp/container/array" rel="noreferrer"><code>std::array</code></a> named <code>array2d</code> in C++17. It is an aggregate like <code>std::array</code>, and provides similar interface. The goal is that if you know how to use <code>std::array</code>, then you will find yourself at home using <code>array2d</code>. Any comments are welcome :) For better viewing experience with highlighting, you can refer to <a href="https://github.com/Lingxi-Li/Modern_CPP_Challenge_Solution/blob/master/17_array2d.hpp" rel="noreferrer">this</a> GitHub page.</p>
<pre><code>#include <cstddef>
#include <array>
#include <iterator>
template <typename T, std::size_t N0, std::size_t N1>
struct array2d {
using row_t = std::array<T, N1>;
inline static constexpr std::array sizes{ N0, N1 };
static constexpr std::size_t size() noexcept { return N0 * N1; }
static constexpr bool empty() noexcept { return !size(); }
T& at(std::size_t i, std::size_t j) { return data_.at(i).at(j); }
const T& at(std::size_t i, std::size_t j) const { return data_.at(i).at(j); }
row_t& operator[](std::size_t i) noexcept { return data_[i]; }
const row_t& operator[](std::size_t i) const noexcept { return data_[i]; }
T& front() { return data_.front().front(); }
const T& front() const { return data_.front().front(); }
T& back() { return data_.back().back(); }
const T& back() const { return data_.back().back(); }
T* data() noexcept { return data_.data()->data(); }
const T* data() const noexcept { return data_.data()->data(); }
T* begin() noexcept { return data(); }
const T* begin() const noexcept { return data(); }
T* end() noexcept { return data() + size(); }
const T* end() const noexcept { return data() + size(); }
auto rbegin() noexcept { return std::make_reverse_iterator(end()); }
auto rbegin() const noexcept { return std::make_reverse_iterator(end()); }
auto rend() noexcept { return std::make_reverse_iterator(begin()); }
auto rend() const noexcept { return std::make_reverse_iterator(begin()); }
void fill(const T& v) {
for (auto& row : data_) {
row.fill(v);
}
}
friend void swap(array2d& a, array2d& b) { a.data_.swap(b.data_); }
std::array<row_t, N0> data_;
};
</code></pre>
| [] | [
{
"body": "<p>Let me collect a couple of thoughts here.</p>\n\n<ul>\n<li><p>Aggregate initialization currently works like this:</p>\n\n<pre><code>array2d<int, 2, 2> a{{1, 2, 3, 4}};\n</code></pre>\n\n<p>but wouldn't it be favorable to allow for</p>\n\n<pre><code>array2d<int, 2, 2> a{{1, 2}, {3, 4}};\n</code></pre></li>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/container/array/at\" rel=\"noreferrer\">std::array::at</a> performs bound checking and throws upon an out of bounds index. When your intention is to stick with the <code>std::array</code> interface, you should do the same.</p></li>\n<li><p>If you want the container to be standard-compliant, there are some type aliases missing and maybe more. In particular, there are no <code>cbegin()</code>, <code>cend()</code>, <code>crbegin()</code>, <code>crend()</code> member functions. Is this intended?</p></li>\n<li><p>You implicitly use row-major order. Are you sure everyone expects this? Users familiar with Eigen and their fixed size matrices might at least want to customize row-/column-major ordering, e.g. <code>Eigen::Matrix<int, 2, 2, Eigen::ColMajor> m;</code></p></li>\n<li><p>A range based for loop will considerably differ from a manual loop over rows and columns. Example:</p>\n\n<pre><code>// Loop over elements, transposed access. Requires nested loop.\nfor (std::size_t i = 0; i < 2; ++i)\n for (std::size_t j = 0; j < 2; ++j)\n std::cout << a[j][i] << \"\\n\";\n\n// Loop over elements, tranposed access impossible. Only one loop.\nfor (const auto& i : d)\n std::cout << i << \"\\n\";\n</code></pre>\n\n<p>This is slightly unintuitive. Shouldn't the range based for loop require a nested loop as well?</p></li>\n<li><p>The static data member <code>sizes</code> is not used anywhere.</p></li>\n</ul>\n\n<p>Getting a two-dimensional array to work is not that much of an effort. Getting the semantics right is hard. Sticking to the <code>std::array</code> interface is a good goal when ease of use is intended for those familiar with the <code>std::array</code> template. But the additional dimension pulls in requirements that can't be tackled with the concepts of <code>std::array</code>. I would recommend having a look at established linear algebra libraries and their fixed size matrices. Also, the <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0009r6.html\" rel=\"noreferrer\">mdspan proposal</a> for a multi-dimensional view on array types might be a good read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T11:16:04.427",
"Id": "416615",
"Score": "0",
"body": "Thanks for reviewing my code.\n\n1) You can `a{1, 2, 3, 4}` and make a new line as you see fit.\n\n2) `array2d::at` does bounds checking too, for `array::at` is called under the hood ^_^\n\n3) You are right they are missing. I think they are tedious and not very useful in practice. But again, the `array2d` is not very useful either XD\n\n4) It is by design that the layout aligns with built-in two-dimensional array.\n\n5) I intend the loop to be similar to what it does with `array`. User needs to use other interface if different traversal is desired.\n\n6) `sizes` is part of the interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T11:16:12.250",
"Id": "416616",
"Score": "0",
"body": "`array2d` is not meant to model matrix in linear algebra. Just like `array` and `vector` are not meant to model vector in linear algebra. By design, it's only meant to serve the role of a basic fixed-size 2D container. Hopefully more convenient to use than built-in 2D array and nested `array`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T11:28:45.167",
"Id": "416618",
"Score": "0",
"body": "You're right with the bounds checking of course :) Also, the point that `array2d` is not meant to be used as a linear algebra vocabulary type is obviously valid. I do see two issues with that, though: if you introduce `array2d` to a code base, developers might use it for linear algebra despite the fact that you didn't design it to fit these requirements. And, I personally use two-dimensional arrays for linear algebra and nothing else. If I need more that one dimension, I often find other data structures nearer to my intention."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:36:31.510",
"Id": "215403",
"ParentId": "215399",
"Score": "16"
}
},
{
"body": "<p>Looks good! Great job.</p>\n\n<ol>\n<li><p>To initialize the array completely I have to write:</p>\n\n<pre><code>array2d<int, 2, 2> Array{{{{1, 2}, {2, 3}}}};\n</code></pre>\n\n<p>The two extra sets of braces are horrible! If you instead have a <code>T[][]</code> data member one layer of braces falls of and you need only one set of braces just like <code>std::array</code>.</p>\n\n<pre><code>array2d<int, 2, 2> Array{{{1, 2}, {2, 3}}}; // manageable\n</code></pre></li>\n<li><p>Whatever happened to <code>constexpr</code> all the things? :)</p></li>\n<li><p>Nested <code>std::array</code>s are not guaranteed to be continuous (see <a href=\"https://stackoverflow.com/questions/9762662/is-the-data-in-nested-stdarrays-guaranteed-to-be-contiguous\">this post</a>), although in practice they probably are. Resolving point 1) also fixes this issue.</p></li>\n<li><p>IMO a <code>at</code> member that takes only one index and returns a row would make sense for consistency with your <code>operator[]</code>.</p></li>\n<li><p>Consider adding the various member types that a <a href=\"https://en.cppreference.com/w/cpp/named_req/Container\" rel=\"nofollow noreferrer\"><em>Container</em></a> is supposed to have (and also the other requirements, <code>cr[begin, end]</code>, <code>max_size</code>, member <code>swap</code>, ...).</p></li>\n<li><p>I mean sure, <code>size</code> and <code>empty</code> can be <code>static</code>, but really, conceptually this doesn't make much sense. <code>std::array</code>'s <code>empty</code> and <code>size</code> are not static too.</p></li>\n<li><p>How about providing various customization points of <code>std::get</code>, <code>std::tuple_size</code>, ... so that your array works with structured bindings.</p></li>\n<li><p>You didn't add any relational operators. Is this intentional?</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T01:56:10.523",
"Id": "416754",
"Score": "0",
"body": "Thanks for reviewing my code, Rakete. 1) Since C++14, you can simply `Array{1, 2, 4, 5}` without any nested braces. 2) You are right they are missing. It's tedious and a burden, and I don't think they are very useful in practice. So I don't bother :/ 3) Good catch. Today I learned. 4) On a second thought, agreed. We can have `at` overloads that take 1 and 2 indices ^_^ 5) Yes. For serious production code, they should be present. The boring part of writing C++ library code XD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T02:01:29.107",
"Id": "416755",
"Score": "0",
"body": "6) User can still invoke them the way as if they are non-static like `a.size()`. Making them `static` provides more possibilities, and removes the need to pass `this`. 7) You are right. 8) Not until [`operator<=>`](https://en.cppreference.com/w/cpp/language/default_comparisons) is practically supported by the compilers :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T09:04:36.337",
"Id": "416786",
"Score": "0",
"body": "@Lingxi 1) How did I not know that, thanks :) 2) you really should, it's only one keyword ;) 6) yeah, but still thinks it's weird. 8) that would require that T also has an operator<=>. If it has the traditional operators, then you won't be able to compare the array since operator<=> can't dispatch to the individual relational operators of T."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T07:03:18.993",
"Id": "460969",
"Score": "0",
"body": "@Rakete1111 I believe `operator<=>` can dispatch to the traditional operators now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T22:11:13.440",
"Id": "215456",
"ParentId": "215399",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T06:52:31.537",
"Id": "215399",
"Score": "15",
"Tags": [
"c++",
"library",
"template-meta-programming",
"c++17"
],
"Title": "2D counterpart of std::array in C++17"
} | 215399 |
<p>I have created an Angular pipe to suppress the sensitive information like credit cards, bank account, ABA numbers etc.</p>
<p>This is working fine but I would like to know if this is the best possible way to implement the logic. </p>
<p>Here is the Typescript code for pipe logic.</p>
<pre><code>export class SuppressInfoPipe implements PipeTransform {
transform(valueToSupress: string, unSuppressedCount?: number): string {
let suppressedOutput = '';
const valueToRemainUnsuppressed =
valueToSupress.substring(valueToSupress.length - unSuppressedCount, valueToSupress.length);
let astariskLength = valueToSupress.length - unSuppressedCount;
for ( let i = 0; i < astariskLength; i++) {
suppressedOutput = suppressedOutput.concat('*');
}
suppressedOutput = suppressedOutput.concat(valueToRemainUnsuppressed);
return suppressedOutput;
}
}
</code></pre>
<p>it takes the string input and the number of character they will no be hidden and then return the suppressed output.</p>
<p>Comments and suggestions are welcomed.</p>
| [] | [
{
"body": "<p>I would avoid the for loop to generate the \"suppressed string\".</p>\n\n<p>My approach would be:</p>\n\n<pre><code>export class SuppressInfoPipe implements PipeTransform {\n\n transform(valueToSupress: string, unSuppressedCount = 0): string {\n const suppressedCount = valueToSupress.length - unSuppressedCount;\n const valueToRemainUnsuppressed =\n valueToSupress.substring(suppressedCount, valueToSupress.length);\n\n return Array(suppressedCount + 1).join('*') + valueToRemainUnsuppressed; // suppressedCount + 1: since join will a string of length \"suppressedCount\"\n }\n}\n</code></pre>\n\n<p>In this case:</p>\n\n<pre><code>Array(n) will return an array of length n.\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/jKkgB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jKkgB.png\" alt=\"enter image description here\"></a></p>\n\n<p><code>.join(\"*\")</code> will join the list and return a string equivalent of length n-1.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T11:13:10.737",
"Id": "417445",
"Score": "0",
"body": "That's much better. Only thing I want to confirm is this changing the type of Array object when returning just like JavaScript does to variables depending upon the data being assigned ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T11:18:44.840",
"Id": "417446",
"Score": "0",
"body": "Updated my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T11:22:23.233",
"Id": "417448",
"Score": "0",
"body": "I got your point :) . Thanks for adding explanation to your answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T09:20:21.197",
"Id": "215735",
"ParentId": "215404",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215735",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T08:47:08.730",
"Id": "215404",
"Score": "0",
"Tags": [
"typescript",
"angular-2+"
],
"Title": "Angular pipe to suppress sensitive information"
} | 215404 |
<p>Since C# 8 and .Net Core 3 are going to be released sometime this year, I wanted to try and convert the library I made to make querying databases easier, implementing the already accepted features (using declarations, patterns, ranges, ...).</p>
<p>I'm going to pre-emptively say that parameters aren't here yet, because first I have to find a way to make them in a generic way (<code>IDataParameter</code>) and not have to add them one at a time (<code>IDbCommand.Parameters.AddRange</code>). I have some ideas, but those are for another thread.</p>
<p>If something isn't clear about the code below, tell me and I'll amend it.</p>
<pre><code>// Enum to indicate what kind of query it is.
public enum QueryType
{
Sql = 0,
Odbc = 1
}
public class Queries
{
/*Legend*/
// Retrieve = # of columns to consider or which column to pick.
// SplitBy = what to use to split the results.
/*******/
private readonly string _connectionString;
private readonly QueryType _type;
private readonly int _timeOut;
// Initialize a new instance of the class.
public Queries(
QueryType type,
string connectionString,
int timeOut = 60)
{
if (string.IsNullOrEmpty(connectionString))
throw new System.NullReferenceException(
"The connection string can't be empty");
_type = type;
_connectionString = connectionString;
_timeOut = timeOut;
// Test to see if connectionString is valid.
GetConnection();
}
private IDbConnection GetConnection()
{
IDbConnection dbConnection = null;
return _type switch
{
QueryType.Odbc => new OdbcConnection(_connectionString),
QueryType.Sql => new SqlConnection(_connectionString),
_ => dbConnection
};
}
private IDbCommand GetCommand(
string query,
IDbConnection connection)
{
IDbCommand idbCommand = null;
return _type switch
{
QueryType.Odbc => new OdbcCommand(
query,
(OdbcConnection)connection)
{ CommandTimeout = _timeOut },
QueryType.Sql => new SqlCommand(
query,
(SqlConnection)connection)
{ CommandTimeout = _timeOut },
_ => idbCommand
};
}
private IDbDataAdapter GetDataAdapter(
IDbCommand command)
{
IDbDataAdapter idbAdapter = null;
return _type switch
{
QueryType.Odbc => new OdbcDataAdapter((OdbcCommand)command),
QueryType.Sql => new SqlDataAdapter((SqlCommand)command),
_ => idbAdapter
};
}
// Execute commands, get number of affected rows in return.
public int Execute(
string query)
{
using var connection = GetConnection();
using var command = GetCommand(query, connection);
connection.Open();
return command.ExecuteNonQuery();
}
public IEnumerable<int> Execute(
List<string> query) =>
query.Select(item => Execute(item));
// Return only the first row in a single string.
public string SingleRowReader(
string query,
int retrieve,
string splitBy = "§")
{
using var connection = GetConnection();
using var command = GetCommand(query, connection);
connection.Open();
using var reader = command.ExecuteReader(CommandBehavior.SingleRow);
string result = null;
while (reader.Read())
for (var i = 0; i < retrieve; i++)
result += reader[i].ToString().Trim() + splitBy;
return result?[..^1];
}
public IEnumerable<string> SingleRowReader(
List<string> query,
int retrieve,
string splitBy = "§") =>
query.Select(item => SingleRowReader(item, retrieve, splitBy));
// Create a list out of the result of the query.
public List<string> ListReader(
string query,
int retrieve,
string splitBy = "§")
{
using var connection = GetConnection();
using var command = GetCommand(query, connection);
connection.Open();
using var reader = command.ExecuteReader();
var res = new List<string>();
while (reader.Read())
{
var row = "";
for (var y = 0; y < retrieve; y++)
row += reader[y].ToString().Trim() + splitBy;
res.Add(row?[..^1]);
}
return res;
}
public IEnumerable<List<string>> ListReader(
List<string> query,
int retrieve,
string splitBy = "§") =>
query.Select(item => ListReader(item, retrieve, splitBy));
// Create a dictionary with the row as key and the results as values.
public Dictionary<int, string> DictionaryReader(
string query,
int retrieve = 0,
string splitBy = "§")
{
var res = new Dictionary<int, string>();
var att = ListReader(query, retrieve, splitBy);
for (var i = 0; i < att.Count; i++)
res.Add(i, att[i]);
return res;
}
// Create a dictionary with the list of columns
// as keys and the results divided by row as values.
public Dictionary<string, List<string>> DictionaryReader(
string query,
List<string> retrieve)
{
using var connection = GetConnection();
using var command = GetCommand(query, connection);
connection.Open();
using var reader = command.ExecuteReader();
var res = new Dictionary<string, List<string>>();
foreach (var item in retrieve)
res.Add(item, new List<string>());
var row = 0;
while (reader.Read())
{
for (var y = 0; y < retrieve.Count; y++)
{
var value = reader[retrieve[y]].ToString().Trim();
res[retrieve[y]].Insert(row, value);
}
row++;
}
return res;
}
// Returns a table with the results of the query.
public DataTable Table(
string query)
{
using var connection = GetConnection();
using var command = GetCommand(query, connection);
connection.Open();
var dataAdapter = GetDataAdapter(command);
var dt = new DataTable() { Locale =
System.Globalization.CultureInfo.InvariantCulture };
switch (_type)
{
case QueryType.Odbc:
((OdbcDataAdapter)dataAdapter).Fill(dt);
break;
case QueryType.Sql:
((SqlDataAdapter)dataAdapter).Fill(dt);
break;
default:
break;
}
return dt;
}
}
// The class for SQL queries.
public class SQLQueries : Queries
{
public SQLQueries(
string connectionString,
int timeOut = 60) :
base(
QueryType.Sql,
connectionString,
timeOut)
{ }
}
// The class for ODBC queries.
public class ODBCQueries : Queries
{
public ODBCQueries(
string connectionString,
int timeOut = 60) :
base(
QueryType.Odbc,
connectionString,
timeOut)
{ }
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T13:31:11.530",
"Id": "416629",
"Score": "0",
"body": "FYI: https://www.codingame.com/playgrounds/3002/the-difference-between-string-and-stringbuilder-in-c/benchmarking-string-vs-stringbuilder Then again, this whole \"ORM\" seems pointless to me. You're pouring a lot of work into something that is far better solved by using the likes of Dapper. https://lostechies.com/jimmybogard/2012/07/24/dont-write-your-own-orm/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T08:45:37.610",
"Id": "416784",
"Score": "0",
"body": "@BCdotWEB Thank you very much for both sites, I'm gonna use Dapper now that I know it exists."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T10:35:28.600",
"Id": "215411",
"Score": "3",
"Tags": [
"c#",
"sql",
".net-core"
],
"Title": "Generic library for querying various kinds of databases"
} | 215411 |
<p>There are no requirements for this project nor will it ever be used for any purpose. </p>
<p>I used this project to cement my knowledge of basic programming skills, I got bored copying the examples and felt I would learn faster if I built everything into a functional program with a little complexity. It follows British registration number formatting in case you're curious</p>
<p>Any feedback is appreciated. The code is below, but I have it on github if you prefer to try it out yourself. </p>
<p><a href="https://github.com/Niall47/RubySomDemo" rel="nofollow noreferrer">https://github.com/Niall47/RubySomDemo</a> use (V3.rb)</p>
<pre><code>require 'json'
require 'colorize'
class Car
attr_accessor :vrm
attr_accessor :make
attr_accessor :model
attr_accessor :description
attr_accessor :colour
attr_accessor :date
def initialize(aMake, aModel, aDescription, aColour, aVRM, aManufactureDate)
@vrm = aVRM
@make = aMake
@model = aModel
@description = aDescription
@colour = aColour
@date = aManufactureDate
end
def text_format
return "#{@vrm} -- #{@make} #{@model} #{@date} (#{@description}, #{@colour})"
end
end
def save_to_file
@back_up = Hash.new
$all_vehicles.each do |a_vehicle |
#itterate through each record and create a hash with vrm as key
@back_up[a_vehicle[1].vrm] = a_vehicle[1].make, a_vehicle[1].model, a_vehicle[1].colour, a_vehicle[1]. description, a_vehicle[1].date
end
File.write("vehicles.json",@back_up.to_json)
p 'Saved records to \'vehicles.json\''
end
def open_file
$all_vehicles = {}
#If file exists itterate through records and recreate objects
if File.file?("vehicles.json")
File.open('vehicles.json') do |f|
@load_vehicles = JSON.parse(f.read)
end
@load_vehicles.each do |a_vehicle|
new_car = Car.new(a_vehicle[1][0], a_vehicle[1][1], a_vehicle[1][3], a_vehicle[1][2], a_vehicle[0], a_vehicle[1][4])
$all_vehicles[new_car.vrm] = new_car
end
count
else
p 'Unable to find file, creating blank file'
save_to_file
end
end
def count
p "You have #{$all_vehicles.count} records on file"
end
def gen_vrm(aManufactureDate)
suffix_age = { 1963 => "A",1964 => "B",1965 => "C",1966 => "D",1967 => "E",1968 => "F",1969 => "G",1970 => "H",1971 => "J",1972 => "K",
1973 => "M",1974 => "N",1975 => "P",1976 => "R",1977 => "S",1978 => "T",1979 => "V",1980 => "W",1981 => "X",1982 => "Y"}
prefix_age = { 1983 => "A",1984 => "B",1985 => "C",1986 => "D",1987 => "E",1988 => "F",1989 => "G",1990 => "H",1991 => "J",1992 => "K",
1993 => "L",1994 => "M",1995 => "N",1996 => "P",1997 => "R",1998 => "S",1999 => "T",2000 => "V",2001 => "W",}
if aManufactureDate.is_a?Integer
if (1983..2001).include?(aManufactureDate) #PREFIX STYLE
prefix = prefix_age[aManufactureDate]
numbers =('0'..'9').to_a.shuffle.first(3).join
suffix =('A'..'Z').to_a.shuffle.first(3).join
@vrm = (prefix.to_s + numbers +suffix.to_s)
elsif (1963..1982).include?(aManufactureDate) # SUFFIX STYLE
prefix =('A'..'Z').to_a.shuffle.first(3).join
numbers =('0'..'9').to_a.shuffle.first(3).join
suffix = suffix_age[aManufactureDate]
@vrm = (prefix.to_s + numbers + suffix.to_s)
elsif (1903..1962).include?(aManufactureDate) # HISTORIC
numbers =('0'..'9').to_a.shuffle.first(1).join
suffix =('A'..'Z').to_a.shuffle.first(3).join
if (1903..1930).include?(aManufactureDate)
@vrm = (numbers + suffix.to_s)
else
@vrm = (suffix.to_s + numbers)
end
elsif aManufactureDate > 2001 #CURRENT STYLE
prefix =('A'..'Z').to_a.shuffle.first(2).join
extract_year = aManufactureDate.to_s #Convert to string so we can grab the last 2 digits
extract_year.to_i
numbers = extract_year.chars.last(2).join
suffix =('A'..'Z').to_a.shuffle.first(3).join
@vrm = (prefix.to_s + numbers + suffix.to_s)
else #Q PLATE
prefix = "Q"
numbers =('0'..'9').to_a.shuffle.first(3).join
suffix =('A'..'Z').to_a.shuffle.first(3).join
@vrm = (prefix.to_s + numbers + suffix.to_s)
end
end
end
def check_valid?(aVRM, aManufactureDate)
#VRM should be unique, not be blank, not contain letter 'I'
#and only contain 'Q' as first character for vehicles with no manufacture date
bad_value = (aVRM.nil?) || (aVRM.include?("I"))
bad_q = aVRM.include?("Q") && (aVRM[0] != 'Q' || (aVRM[0] == "Q" && (1903..2019).include?(aManufactureDate)))
already_exists = $all_vehicles[aVRM]
return !(bad_value || bad_q || already_exists)
end
def add_new
p "Manufacture Date?"
aManufactureDate = gets.to_i
new_vrm = ''
30.times do
new_vrm = gen_vrm(aManufactureDate)
break if check_valid?(new_vrm, aManufactureDate)
new_vrm = ''
end
raise 'We were unable to generate a valid VRN' if new_vrm.empty?
p "New VRM generated: #{new_vrm}"
p 'Make?'
make = gets.chomp!
p 'Model?'
model = gets.chomp!
p 'Description?'
description = gets.chomp!
p 'Colour?'
colour = gets.chomp!
# Make the car object
new_car = Car.new(make, model, description, colour, new_vrm, aManufactureDate)
# Add the car to our big list
$all_vehicles[new_vrm] = new_car
p "We added #{new_car.text_format} to the list"
end
def show_registrations
p 'Printing all registration marks on file:'
p $all_vehicles.keys
end
def search
p 'Search by: [1]VRM, [2]Manufacture, [3]Model, [4]Year'
match_field = gets.to_i
p 'Enter the exact value to match against'
match_value = gets.chomp!
found_vehicle = nil
found_list = []
#Search stops when it finds VRM, but continues for everything else to generate a list
$all_vehicles.each do |a_vehicle|
case match_field
when 1
found_vehicle = a_vehicle if a_vehicle[1].vrm == match_value
when 2
found_list << a_vehicle if a_vehicle[1].make == match_value
when 3
found_list << a_vehicle if a_vehicle[1].model == match_value
when 4
found_list << a_vehicle if a_vehicle[1].date == match_value.to_i
else
p "There is no option #{match_field}"
break
end
break if found_vehicle
end
if found_vehicle
text = "Found a vehicle : #{found_vehicle}"
p found_vehicle[1].text_format
elsif found_list != []
p 'Found these vehicles'
found_list.each do |vehicles|
p vehicles[1].text_format
end
else
p "Unable to find a vehicle for #{match_value}"
end
end
def bulk_add
make_model = {
"audi" =>%w[A1 A3 A4 A5 A6 A7 A8 Allroad Quattro Cabriolet E-tron Fox Q2 Q3 Q5 Q7 Q8 R8 RS Q3 RS3 RS4 RS5 RS6 RS7 S1 S2 S3 S4 S5 S6 S7 S8 SQ5 SQ7 TT V8_Quattro],
"aston_martin" =>%w[DB11 DB4 DB5 DB6 DB7 DB9 DBS Lagonda_Rapide V12_Vanquish V8_Vanquish Vantage Virage Volante],
"bmw" =>%w[1_Series 2_Series 3_Series 4_Series 5_Series 6_Series 7_Series i3 i4 i8 M2 M3 M4 M5 M6 X1 X2 X3 X4 X5 X6 X7 Z3 Z4],
"citroen" =>%w[Ax Berlingo C2 C3 C4 C4 Aircross C4_Cactus C4_Picasso C5 C6 CX_D Dispatch DS DS3 DS4 DS5 C4_Picasso Xantia Xsara],
"daewoo" =>%w[Cielo Espero Kalos Korando Lacetti Lanos Leganza Matiz Musso Nubira Tacuma],
"fiat" =>%w[Argenta Croma Doblo DUCATO Freemont Panda PANORAMA Punto Regata Ritmo Scudo Superbrava],
"jauguar" =>%w[240 340 420 E_Type Majestic S-TYPE Sovereign V12_Vanden X-TYPE XE XF XJ XJ12 XJ6 XJ8 XJR XJS XJSC XK XK8 XKR],
"land_rover" =>%w[Defender Discovery Discovery_3 Discovery_4 Discovery_Sport Freelander Freelander_2 Range_Rover Range_Rover_Evoque Range_Rover_Sport],
"nissan" =>%w[300ZX 350Z 370Z Almera Altima Bluebird Cabstar Cedric Cube Dualis Elgrand Gazelle GT-R Homer Juke Leaf Maxima Micra Murano Navara Nomad NX-R Pathfinder Patrol Pintara Pulsar Qashqai Serena Skyline Stanza Sunny TERRANO_II Ute X-Trail],
"mercedes" =>%w[A150 C220 C230 C280 C320 C350 C43_AMG E63 S65 SLS Sprinter Valente Viano Vito],
"mitsubishi" =>%w[3000 Challenger Colt Cordia D50 Eclipse Cross Express Galant Grandis L200 L300 Lancer Magna Mirage Nimbus Outlander Pajero Pajero_Sport Sigma Starion Triton Verada],
"renault" =>%w[Alaskan Captur Caravelle Clio Clio_RS Dauphine Floride Fluence Fuego Grand_Scenic Kadjar Kangoo Koleos Laguna Latitude Master Megane RS R25 R4 R8 Scenic Trafic Virage Zoe],
"vauxhall" =>%w[Astra Corsa Insignia Zafira],
"vw" =>%w[Amarok Arteon Beetle Bora Caddy Caravelle Citivan CRAFTER Eos Golf Jetta Karmann Kombi Multivan Passat Polo Scirocco T-CROSS Tiguan Touareg Transporter Up! Vento]
}
description = %w[fast slow low broken stolen slammed undercover untaxed exported cloned]
colour = %w[blue red green silver grey white black]
p 'How many records are we generating?'
count = gets.chomp.to_i
count.times do |index|
@aManufactureDate = rand(1903..2019).to_i # in theory no Q plates
#if we don't get a valid vrm after 30 tries then something is wrong
30.times do
@new_vrm = gen_vrm(@aManufactureDate)
break if check_valid?(@new_vrm, @aManufactureDate)
@new_vrm = ''
end
raise 'We were unable to generate a valid VRN' if @new_vrm.empty?
make = make_model.keys.sample
model = make_model[make].sample
new_car = Car.new(make, model, description.sample, colour.sample, @new_vrm, @aManufactureDate)
$all_vehicles[@new_vrm] = new_car
p "We added #{new_car.text_format} to the list"
end
end
def help
p ("new - adds new record")
p ("search - allows you to search by VRM, make, model and manufacture date")
p ("save - backs up all records to vehicles.json")
p ("vrm - displays all VRMs currently on file")
p ("count - displays number of current records")
p ("bulk - generates new records")
end
def ascii_intro
if File.file?("intro.txt") #print from a file so ruby can't parse through and ruin it
File.open('intro.txt').each do |line|
print line.red
end
end
end
######################## Program starts here ########################
default_message = 'OPTIONS: new, search, save, bulk, vrm, count, help & exit'
$all_vehicles = {}
input = nil
ascii_intro
open_file
while input != ("exit")
p default_message
input = gets.downcase.chomp!
case input
when "new"
add_new
when "help"
help
when "search"
search
when "count"
count
when "bulk"
bulk_add
when "vrm"
show_registrations
when "save"
save_to_file
when "exit"
exit
end
end
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T12:07:46.127",
"Id": "215416",
"Score": "3",
"Tags": [
"beginner",
"ruby"
],
"Title": "Ruby - Core skills example project (command line vehicle registry)"
} | 215416 |
<p>When <a href="https://github.com/zspitz/ExpressionToString" rel="noreferrer">generating a string representation of expression trees</a>, I would like to render calls to <code>String.Format</code> with a constant string as the first parameter, as interpolated strings (<a href="https://github.com/zspitz/ExpressionToString/issues/37" rel="noreferrer">link</a>). In order to do so, I have to parse the compiler-generated composite format string.</p>
<p>I've written the following function for this purpose, based on the <a href="https://referencesource.microsoft.com/#mscorlib/system/text/stringbuilder.cs,1322" rel="noreferrer">.NET Core parsing function</a>. I am looking primarily for review in:</p>
<ul>
<li>correctness, even in edge cases</li>
<li>clarity / readability</li>
</ul>
<hr>
<p>The function returns an array of tuples. Each tuple contains the following elements:</p>
<ol>
<li>literal string until the next placeholder</li>
<li>index of placeholder</li>
<li>alignment</li>
<li>item format</li>
</ol>
<p>If there is literal text after the last placeholder, it will be added as the last tuple of the array (other elements of the tuple will be <code>null</code>).</p>
<hr>
<p>The function defines 3 local functions:</p>
<ul>
<li><code>advanceChar</code> -- advances the current position (<code>pos</code>) by one character, and stores the current character (<code>ch</code>)</li>
<li><code>skipWhitespace</code> -- advances the current position as long as the current character is a space</li>
<li><code>getNumber</code> -- gets a multi-digit number starting from the current position; ignores leading/trailing whitespace</li>
</ul>
<hr>
<pre><code>public static (string literal, int? index, int? alignment, string itemFormat)[] ParseFormatString(string format) {
const int indexLimit = 1000000;
const int alignmentLimit = 100000;
int pos = -1;
char ch = '\x0';
int lastPos = format.Length - 1;
var parts = new List<(string literal, int? index, int? alignment, string itemFormat)>();
while (true) {
// Parse literal until argument placeholder
string literal = "";
while (pos < lastPos) {
advanceChar();
if (ch == '}') {
advanceChar();
if (ch == '}') {
literal += '}';
} else {
throw new Exception("Mismatched end brace");
}
} else if (ch == '{') {
advanceChar();
if (ch == '{') {
literal += '{';
} else {
break;
}
} else {
literal += ch;
}
}
if (pos == lastPos) {
if (literal != "") {
parts.Add((literal, (int?)null, (int?)null, (string)null));
}
break;
}
// Parse index section; required
int index = getNumber(indexLimit);
// Parse alignment; optional
int? alignment = null;
if (ch == ',') {
advanceChar();
alignment = getNumber(alignmentLimit, true);
}
// Parse item format; optional
string itemFormat = null;
if (ch == ':') {
advanceChar();
if (ch == '{') {
advanceChar();
if (ch == '{') {
itemFormat += '{';
} else {
throw new Exception("Nested placeholders not allowed");
}
} else if (ch == '}') {
advanceChar();
if (ch=='}') {
itemFormat += '}';
} else {
break;
}
} else {
itemFormat += ch;
}
}
parts.Add((literal, index, alignment, itemFormat));
}
return parts.ToArray();
void advanceChar(bool ignoreEnd = false) {
pos += 1;
if (pos <= lastPos) {
ch = format[pos];
} else if (ignoreEnd) {
ch = '\x0';
} else {
throw new Exception("Unexpected end of text");
}
}
void skipWhitespace() {
while (ch == ' ') {
advanceChar(true);
}
}
int getNumber(int limit, bool allowNegative = false) {
skipWhitespace();
bool isNegative = false;
if (allowNegative && ch == '-') {
isNegative = true;
advanceChar();
}
if (ch < '0' || ch > '9') { throw new Exception("Expected digit"); }
int ret = 0;
do {
ret = ret * 10 + ch - '0';
advanceChar();
} while (ch >= '0' && ch <= '9' && ret < limit);
skipWhitespace();
return ret * (isNegative ? -1 : 1);
}
}
</code></pre>
| [] | [
{
"body": "<h3>Problems:</h3>\n\n<p>Item format parsing is broken:</p>\n\n<ul>\n<li><code>\"{0:X2}\"</code> fails with an 'Unexpected end of text' exception, while <code>\"{0:X2}a\"</code> fails with a 'Mismatched end brace' exception. Both are valid formats.</li>\n<li><code>\"{0:}\"</code> also fails with an 'Unexpected end of text' exception, but <code>\"{0:}a\"</code> returns an empty array instead. Both are valid formats.</li>\n<li><code>\"{0:{{\"</code> and <code>\"{0:}}\"</code> are parsed successfully. Both should be rejected as invalid.</li>\n</ul>\n\n<h3>Improvements:</h3>\n\n<ul>\n<li>The index and alignment limits seem fairly arbitrary. If they're based on an actual limit it would be a good idea to document that. Also, exceeding those limits results in a misleading 'Mismatched end brace' error.</li>\n<li>I'd recommend using a more specific exception exception type. The existing <code>FormatException</code> seems appropriate here.</li>\n<li>For repeated string concatenation, a <code>StringBuilder</code> is (significantly) more efficient.</li>\n<li>The exceptions don't provide much detail. It would be useful to know at what index the problem was detected, or what the parser was expecting when it hit the end of the input.</li>\n<li>The main while loop body is fairly drawn out. If you're using local functions anyway, why not split things up further into a <code>ParseLiteralPart</code> and <code>ParseFormatPart</code> function?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T15:08:22.370",
"Id": "416651",
"Score": "2",
"body": "mhmm... based on your findings I'm thinking of flagging the question as not-working-code..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T22:46:05.637",
"Id": "416749",
"Score": "0",
"body": "@t3chb0t I've identified and fixed the problems (still working on the improvements); should I edit the code in the question? Should I close this and reopen another question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T09:17:40.260",
"Id": "416789",
"Score": "0",
"body": "@ZevSpitz nope, editing the code is not allowed when there are already answers. What you can do is to either add a self-answer or ask a follow-up question if you'd like to have another review."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T13:33:31.963",
"Id": "215421",
"ParentId": "215417",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "215421",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T12:08:21.297",
"Id": "215417",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Function to parse .NET composite string format"
} | 215417 |
<p>I have a solution, which compares 2 given strings and returns the number of total matching characters.</p>
<p>I know I haven't initialized the variables and arrays and that this (correctly) yields warnings. I know the variables aren't self-explanatory as they should be. </p>
<pre><code>function commonCharacterCount($s1, $s2) {
$a = (strlen($s1) > strlen($s2)) ? $s2 : $s1;
$b = (strlen($s1) > strlen($s2)) ? $s1 : $s2;
foreach(count_chars($a, 1) as $i => $v) {
$c[chr($i)] = $v;
}
foreach (count_chars($b, 1) as $i => $v) {
$d[chr($i)] = $v;
}
$t = 0;
foreach($c as $k => $v) {
if($c[$k] <= $d[$k]) {
$t += $c[$k];
} else {
$t += $d[$k];
}
}
return $t;
}
</code></pre>
<p>For instance, I have the two strings:</p>
<p><code>$s1 = "abacadeee";</code> and <code>$s2 = "aabbccddee";</code>, the expected output would be <code>7</code>.</p>
<p>As required, this solution works so far and you can test it here:
<a href="http://sandbox.onlinephpfunctions.com/code/bc4c07ec985c219b820ce93eba3eb71609404cde" rel="nofollow noreferrer">sandbox</a></p>
<p>Which steps are unnecessary and how can I improve this algorithm?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T15:22:41.167",
"Id": "416652",
"Score": "1",
"body": "what is the logic of common character count? from you test data characters that matches are a, b, c, d, e = 5. Again if I count occurrence the value is not 7. or even i count maximum occurrence the value is not 7"
}
] | [
{
"body": "<p>I would recommend a process like this:</p>\n\n<p>Code: (<a href=\"https://3v4l.org/RA6WL\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$string1 = \"abacadeee\";\n$string2 = \"aabbccddee\";\n\n$counts2 = count_chars($string2, 1);\n\n$tally = 0;\nforeach (array_intersect_key(count_chars($string1, 1), $counts2) as $charcode1 => $count1) {\n $tally += min($counts2[$charcode1], $count1);\n}\necho $tally;\n</code></pre>\n\n<p><code>count_chars()</code> lends itself beautifully to this task, so using array functions onward is a sensible choice.</p>\n\n<p>It is important to try to minimize iterations and not perform any useless iterations. By calling <code>array_intersect_key()</code> on the two <code>count_chars()</code> results, the <code>foreach()</code> loop is only going to iterate elements with keys which are shared between the two arrays. In doing this, you don't need to check which array is smaller (which is otherwise how you would choose which array to iterate).</p>\n\n<p><code>$tally</code> is incremented by the lesser of the two counts for each char.</p>\n\n<p>p.s. calling <code>chr()</code> is irrelevant to your objective.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T12:50:12.657",
"Id": "215673",
"ParentId": "215420",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T13:24:46.927",
"Id": "215420",
"Score": "1",
"Tags": [
"performance",
"php"
],
"Title": "Find same characters in 2 strings"
} | 215420 |
<p>I have an assignment to solve this problem. I’m not too sure how permutate works by tracing, just tried on inspiration and it works. This code runs on all provided test cases, but I’m just trying to look for ways of improvement in terms of time efficiency, space efficiency and styling.</p>
<blockquote>
<p><strong>Question Description</strong></p>
<p>Bob the Dog has a word <strong>W</strong> containing <strong>N</strong> distinct lowercase
letters (‘a’ to ‘z’). </p>
<p>Bob the Dog would like you to generate all possible permutations of
the <strong>N</strong> letters followed by all possible sub-sequences of the
<strong>N</strong> letters. </p>
<p>A permutation of the letters in <strong>W</strong> is generated by reordering the
letters in <strong>W</strong>. You are to print all possible such re-orderings.
For example, permutations of ‘cat’ are ‘cta’, ‘cat’, ‘atc’, ‘act’,
‘tac’, ‘tca’. </p>
<p>A sub-sequence of the letters in <strong>W</strong> is generated by choosing a
non-empty subset of letters in W, without changing their relative
order in <strong>W</strong>. For example, sub-sequences of ‘cat’ are ‘c’, ‘a’, ‘t’,
‘ca’, ‘at’, ‘ct’, ‘cat’. </p>
<p>The permutations should be printed in increasing lexicographical
order, followed by the sub- sequences in increasing lexicographical
order as well. In order to sort a list of strings in lexicographical
order, you can simply utilize <strong>Collections.sort</strong> on a list of
<strong>Strings</strong>. The default compareTo function in String class is already comparing in lexicographical order. </p>
<p><strong>Input</strong></p>
<p>The input contains a single line, containing the word <strong>W</strong> of length
<strong>N</strong>. </p>
<p><strong>Output</strong></p>
<p>The output should contain <strong>(N!) + 2^N – 1</strong> lines.</p>
<p>The first <strong>N!</strong> lines should contain all possible permutations of the
letters in W, printed in increasing lexicographical order.</p>
<p>The next <strong>2^N-1</strong> lines should contain all possible sub-sequences of
the letters in W, printed in increasing lexicographical order as
well. </p>
<p><strong>Limits</strong></p>
<p>• 1≤N≤9 </p>
<p>• <strong>W</strong> will only contain distinct lowercase letters (‘a’ to ‘z’).</p>
</blockquote>
<p>Here is my attempt, do inform me if any more information is needed.Thanks.</p>
<pre><code>import java.util.*;
import java.util.stream.Collectors;
public class Generate {
private void run() {
Scanner sc = new Scanner(System.in);
String inputs = sc.next();
List<String> sortedString = inputs.codePoints()//split into ASCII int
.sorted()
.mapToObj(x->String.valueOf((char)x))//changes to String
.collect(Collectors.toList());
//breaks the string into an array of String and sort a smaller list
permutate(sortedString, new boolean[sortedString.size()],0,new StringBuilder());
subSequence(inputs);//order requires the original string
}
public static void main(String[] args) {
Generate newGenerate = new Generate();
newGenerate.run();
}
//uses a flag Array to note which character is used before instead of making new String arrays
public static void permutate(List<String> lst, boolean [] used, int numUsed,StringBuilder builder) {
if (lst.size()==numUsed) {
System.out.println(builder);//each permutation must be as long as the input size
return;
}
for (int i=0;i<lst.size();i++) { //For each loop, 1 case will use the character, the other wouldn't
if (used[i]) {
continue;
}
String current = lst.get(i);
StringBuilder copiedBuilder = new StringBuilder(builder.toString());//shallow copy of a String,
//Builders are generally faster than concatenation
boolean [] copied = Arrays.copyOf(used,lst.size());//duplicate 1 flag array for the other case
copied[i]=true; //update only one of them
copiedBuilder.append(current);
permutate(lst,copied,numUsed+1,copiedBuilder);
}
}
//helper method that fills the results list with StringBuilders to be sorted
public static void basicSubSequence(String input,StringBuilder builder, int position,ArrayList<String> results) {
if (position==input.length()) {//no more characters in input is left
if (builder.length()==0) {//excludes the empty String as a subsequence
return;
}
results.add(builder.toString());
return;
}
//similarly, make a copy of builder and update only the copy
StringBuilder copiedBuilder = new StringBuilder(builder.toString());
char current = input.charAt(position);
copiedBuilder.append(current);
basicSubSequence(input,copiedBuilder,position+1,results);
basicSubSequence(input,builder,position+1,results);
}
public static void subSequence(String inputs) {
ArrayList<String> seqResults = new ArrayList<>();//creates a result list
basicSubSequence(inputs, new StringBuilder(),0,seqResults);//fills up the list
Collections.sort(seqResults);//sorts the list
for (String str: seqResults) {
System.out.println(str);
}
}
}
</code></pre>
<p><strong>Sample Input</strong></p>
<pre><code>tan
</code></pre>
<p><strong>Output</strong></p>
<pre><code>ant
atn
nat
nta
tan
tna
a
an
n
t
ta
tan
tn
</code></pre>
<p> </p>
<p><strong>Disclaimer</strong></p>
<p>There are some concerns regarding the use of words like "subsequence", which might include some cases that are not included here. However, this code works for all the test cases provided, which means my interpretation of it matches the meaning of the author's, that of which I cannot control. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T19:21:28.357",
"Id": "416711",
"Score": "0",
"body": "Your output is incorrectly missing `na` and `nt` and incorrectly contains a duplicated `tan`, which is not a subsequence that is shorter than the complete alphabet. As such your code is not accomplishing the goal it was written for and therefore the question is unfortunately off-topic for this site. For more information, see the [help/on-topic]. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T23:01:52.653",
"Id": "416750",
"Score": "1",
"body": "Actually my code fits the question's description, there are 6 permutations and (2^3-1) subsequences. I'm not sure if subsequence's common usage should include the input term itself, but this is consistently the interpretation for all test cases.\n\n'na` and `nt` will not happen because it is sequentially impossible in `tan`, the original input. `a` always comes before `n` and `t` always comes before `n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T19:16:07.170",
"Id": "416924",
"Score": "0",
"body": "you are right. in my defense: the formal strictness of the problem formulation leaves a lot to be desired..."
}
] | [
{
"body": "<p>The question states you get one line but you operate on a list of strings.</p>\n\n<p>Don't use end-of-line comments. They're hard to read and impossible to format.</p>\n\n<p>Permutations can be generated with a simple recursive divide-and-conquer algorithm:</p>\n\n<ol>\n<li>If string length is 1, there is only one permutation.</li>\n<li>For each character in the string\n\n<ol>\n<li>Swap character and the first one</li>\n<li>Generate permutations for substring after first character</li>\n</ol></li>\n</ol>\n\n<p>You need to pass the string, the index of the start of the substring and a collection where you collect the results through the recursions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T10:53:24.853",
"Id": "416801",
"Score": "0",
"body": "Sorry, I don't really understand what you meant by swapping character and the first one in ur pseudocode, can you illustrate with the test case?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T10:47:27.503",
"Id": "215496",
"ParentId": "215425",
"Score": "2"
}
},
{
"body": "<p>Your algorithm is single threaded, and does not modify the partial solution; so you need not copy about stuff. You can instead just undo what you modified in each step, namely remove the letter you appended and mark it unused.</p>\n\n<p>There is also no reason to convert chars to strings.</p>\n\n<pre><code>private static void permutate2(char[] letters, boolean[] used, int numUsed, StringBuilder builder) {\n if (used.length == numUsed) {\n System.out.println(builder);\n return;\n }\n\n for (int i = 0; i < used.length; i++) {\n if (used[i]) {\n continue;\n }\n\n char current = letters[i];\n\n used[i] = true;\n builder.append(current);\n permutate2(letters, used, numUsed + 1, builder);\n used[i] = false;\n builder.setLength(builder.length() - 1);\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T12:53:11.893",
"Id": "215503",
"ParentId": "215425",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:42:46.150",
"Id": "215425",
"Score": "1",
"Tags": [
"java",
"algorithm",
"programming-challenge"
],
"Title": "Permutation and subsequences of string"
} | 215425 |
<p>I've created a script in Python to log into stackoverflow.com using credentials and fetch the profilename once logged in. I've tried to do it using class. I created the methods within that class in such a way so that they work like chain. Should I stick to this design or there is anything better I can pursue? Whatever it is I would like this <code>get_profile()</code> method to be seperated like how it is now.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
class StackOverflowBot(object):
login_url = "https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f"
def __init__(self,session,username,password):
self.session = session
self.username = username
self.password = password
self.login(self.session,self.username,self.password)
def login(self,session,username,password):
session.headers['User-Agent'] = 'Mozilla/5.0'
req = session.get(self.login_url)
soup = BeautifulSoup(req.text, "lxml")
payload = {
"fkey": soup.select_one("[name='fkey']")["value"],
"email": username,
"password": password,
}
req = session.post(self.login_url,data=payload)
return self.get_profile(req.text)
def get_profile(self,htmlcontent):
soup = BeautifulSoup(htmlcontent,"lxml")
item = soup.select_one("[class^='gravatar-wrapper-']").get('title')
print(item)
if __name__ == '__main__':
with requests.Session() as session:
StackOverflowBot(session,"username","password")
</code></pre>
| [] | [
{
"body": "<p>IMO the answer highly depends on how you are planning to extend the functionality of your class.\nIf its only <strong>function</strong> is fetching the username, it's probably better to transform it into a <strong>function</strong>. Class is an overkill.</p>\n\n<p>A few thoughts if you're going to expand it:</p>\n\n<ol>\n<li>You can take a look at the <a href=\"https://api.stackexchange.com\">Stack Exchange API</a> and see if it matches your needs if you haven't already.</li>\n<li>You can cache user data in the class fields.</li>\n<li>If you don't care too much about making one extra request, you can make one when you call <code>get_profile</code>. For this, you'll probably need to store the session credentials.</li>\n<li>You can try using <code>HEAD</code> method instead of <code>GET</code> when you don't need the body (dunno though if the site will handle it as intended).</li>\n</ol>\n\n<p>Also, in Python 3 there is no reason to extend <code>object</code> for new classes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T12:16:06.747",
"Id": "215607",
"ParentId": "215428",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T16:10:06.847",
"Id": "215428",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"web-scraping",
"stackexchange"
],
"Title": "Scraper to grab a Stack Overflow profile name"
} | 215428 |
<p>A C# WPF user interface has been developed for the Book Inventory MySQL database previously shown in <a href="https://codereview.stackexchange.com/questions/196988/science-fiction-wall-of-fame-shame">this question</a>. Since the database had already been developed this was a database first implementation.</p>
<p>I did find that additional stored procedures were necessary to implement the Add Book dialog, due to the table normalization strategy used in the design of the database I was unable to utilize the stored procedures of adding a book to the library or buying a book.
This question is specifically about the database interaction model.</p>
<p><strong>Why didn’t I use the Entity Framework?</strong></p>
<ul>
<li>At the time I started creating the models I didn’t know the entity
framework could use stored procedures. I learned this after half the
data table models were created.</li>
<li>I looked through the code generated
for the entity framework and didn’t see how I could implement the
early error checking I wanted to perform. I really didn’t want to
catch database errors for every possible problem to perform error
checking.</li>
</ul>
<p><strong>Questions</strong></p>
<ul>
<li>Was inheritance abused or over used?</li>
<li>Is this a <a href="https://en.wikipedia.org/wiki/SOLID" rel="nofollow noreferrer">SOLID</a> OOP design?</li>
<li>Are there any odors?</li>
<li>Were C# parameters used correctly?</li>
<li>Are there any possible performance issues?</li>
<li>Are the methods for Dictionaries or Lists that I didn’t use that would have reduced the amount of code or simplified the code?</li>
</ul>
<p>The entire code for this project can be found on <a href="https://github.com/pacmaninbw/ExperimentSimpleBkLibInvTool" rel="nofollow noreferrer">GitHub</a>, including a newer version of the SQL files that create the database.</p>
<p><a href="https://i.stack.imgur.com/EMmDa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EMmDa.png" alt="Select Author control."></a> </p>
<p>Figure 1 Select Author control.</p>
<p>The Select Author control, the Select Author Series List Box, each button in the more options group and each list box on the Add Book dialog all represent tables in the database. The values of each list box are stored as foreign keys in some of the tables.</p>
<p><a href="https://i.stack.imgur.com/vzBTs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vzBTs.png" alt="Add Book Dialog"></a></p>
<p>Figure 2 Add Book Dialog</p>
<p>The architecture of the application is divided into models and views to separate the data and business model from the user interface. Within the models there is an additional division, there are models that represent the database tables and there are models that represent a row of data within each database table. A specialized super class was developed for the tables that contain the data for the list boxes in the Add Book dialog except for the Select Author List Box and the Select Author Series List Box, these are called dictionary table models as a class.</p>
<p>The database table models provide the actual interface to the database. In addition to calling stored procedures to store and retrieve the data they provide data about each table and stored procedure to the row data models for early error checking and validation. The database table models always reside in memory, but the data from the database is retrieved as necessary.</p>
<p>The database row data models provide storage of data until the data is inserted and perform error checking on the data as it is added to the row data model and prior to the insertion into the database. The base class for each database row data model is the <code>DataTableItemBaseModel</code> class.</p>
<p>The <code>CDataTableModel</code> is the base class for all database table classes. It
contains aggregations of the <code>DbColumnParameterData</code> and <code>SqlCmdParameter</code>
classes. The purpose of the <code>DbColumnParameterData</code> class is to provide
necessary information for each column in a database table. The purpose of the
<code>SqlCmdParameter</code> class is to provide information about every parameter in a
stored procedure call. The three dictionaries in each <code>CDataTableModel</code> provide
quick look up for the <code>SqlCmdParameter</code> aggregations based on 3 different naming
schemes, the common name within the application, the column name in the
database table and the parameter name in the stored procedure. This file
contains almost all the calls to stored procedure. Each class that inherits
from this class defines the names of the tables and the stored procedures.
This allows for generic SQL database calls.</p>
<p><a href="https://i.stack.imgur.com/K8hoz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K8hoz.png" alt="Class diagram for CDataTableModel, DbColumnParameterData and SqlCmdParameter"></a></p>
<p>Figure 3 Class diagram for CDataTableModel, DbColumnParameterData and SqlCmdParameter</p>
<p>Each instance of a database table row model references its data table model to acquire the <code>DbColumnParameterData</code> and the <code>SqlCmdParameter</code> for error checking and validation purposes.</p>
<p><a href="https://i.stack.imgur.com/j7bM7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j7bM7.png" alt="The CDataTableModel and the DataTableItemBaseModel both aggregate the SqlCmdParameter class"></a></p>
<p>Figure 4 The <code>CDataTableModel</code> and the <code>DataTableItemBaseModel</code> both aggregate the <code>SqlCmdParameter</code> class</p>
<p>Each public parameter in a <code>DataTableItemBaseModel</code> super class references an instance of the <code>SqlCmdParameter</code> class.</p>
<p><a href="https://i.stack.imgur.com/BFhDb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BFhDb.png" alt="All of the super classes of the DataTableItemBaseModel currently in use"></a></p>
<p>Figure 5 All of the super classes of the <code>DataTableItemBaseModel</code> currently in use</p>
<p><a href="https://i.stack.imgur.com/HKv1a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HKv1a.png" alt="All of the Data Table Models and Inheritance"></a></p>
<p>Figure 6 All of the Data Table Models and Inheritance</p>
<p><strong>The Code:</strong></p>
<p><em>CategoryTableModel.cs</em></p>
<p>This is an example of a super class of the <code>DictionaryTableModel</code>. In the user
interface category was renamed as Genre.</p>
<pre><code>using System.Data;
using MySql.Data.MySqlClient;
using ExperimentSimpleBkLibInvTool.ModelInMVC.DictionaryTabelBaseModel;
namespace ExperimentSimpleBkLibInvTool.ModelInMVC.Category
{
public class CategoryTableModel : DictionaryTableModel
{
public DataTable CategoryTable { get { return DataTable; } }
public CategoryTableModel() : base("bookcategories", "getAllBookCategoriesWithKeys", "addCategory")
{
}
public string CategoryTitle(uint Key)
{
return KeyToName(Key);
}
public uint CategoryKey(string CategoryTitle)
{
return NameToKey(CategoryTitle);
}
public void AddCategory(CategoryModel Category)
{
AddItemToDictionary(Category);
}
protected override void InitializeSqlCommandParameters()
{
MySqlParameterCollection parameters = AddItemParameters;
_addSqlCommandParameter("Name", GetDBColumnData("CategoryName"), parameters["@categoryName"]);
_addSqlCommandParameter("Primary Key", GetDBColumnData("idBookCategories"), parameters["@primaryKey"]);
}
}
}
</code></pre>
<p><em>AuthorTableModel.cs</em></p>
<p>This is an example of one of the more complex implementations of the
<code>CDataTableModel</code> class.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using MySql.Data.MySqlClient;
using ExperimentSimpleBkLibInvTool.ModelInMVC.DataTableModel;
namespace ExperimentSimpleBkLibInvTool.ModelInMVC.Author
{
public class AuthorTableModel : CDataTableModel
{
private int AuthorIDColumnIndex;
private int LastNameColumnIndex;
private int FirstNameColumnIndex;
private int MiddleNameColumnIndex;
private int DobColumnIndex;
private int DodColumnIntex;
public DataTable AuthorTable { get { return DataTable; } }
public AuthorTableModel() : base("authorstab", "getAllAuthorsData", "addAuthor")
{
AuthorIDColumnIndex = GetDBColumnData("idAuthors").IndexBasedOnOrdinal;
LastNameColumnIndex = GetDBColumnData("LastName").IndexBasedOnOrdinal;
FirstNameColumnIndex = GetDBColumnData("FirstName").IndexBasedOnOrdinal;
MiddleNameColumnIndex = GetDBColumnData("MiddleName").IndexBasedOnOrdinal;
DobColumnIndex = GetDBColumnData("YearOfBirth").IndexBasedOnOrdinal;
DodColumnIntex = GetDBColumnData("YearOfDeath").IndexBasedOnOrdinal;
}
public bool AddAuthor(AuthorModel NewAuthor)
{
return addItem(NewAuthor);
}
#region Author Selector tool support
public DataRow[] FindAuthors(string lastName, string firstname=null)
{
DataTable dt = AuthorTable;
string filterString = "LastName LIKE '" + lastName + "*'";
DataRow[] authors = dt.Select(filterString);
return authors;
}
public uint AuthorKey(AuthorModel author)
{
uint key = author.AuthorId;
if (key < 1)
{
DataTable dt = AuthorTable;
string filterString = "LastName = '" + author.LastName + "' AND FirstName = '" + author.FirstName + "' AND MiddleName Like '" + author.MiddleName + "'";
DataRow[] authors = dt.Select(filterString);
if (authors.Length > 0)
{
if (!uint.TryParse(authors[0][AuthorIDColumnIndex].ToString(), out key))
{
key = 0;
}
}
else
{
key = 0;
}
}
return key;
}
public AuthorModel GetAuthorFromId(uint key)
{
AuthorModel author = null;
DataTable dt = AuthorTable;
string filterString = "idAuthors = '" + key.ToString() + "'";
DataRow[] authors = dt.Select(filterString);
if (authors.Length > 0)
{
author = ConvertDataRowToAuthor(authors[0]);
}
return author;
}
// Keeping all internal information about columns and rows encapsulated.
public AuthorModel ConvertDataRowToAuthor(DataRow AuthorInfo)
{
AuthorModel author = new AuthorModel(AuthorInfo[AuthorIDColumnIndex].ToString(), AuthorInfo[FirstNameColumnIndex].ToString(), AuthorInfo[LastNameColumnIndex].ToString(), AuthorInfo[MiddleNameColumnIndex].ToString(),
AuthorInfo[DobColumnIndex].ToString(), AuthorInfo[DodColumnIntex].ToString());
return author;
}
public List<string> AuthorNamesForSelector(DataRow[] AuthorDataRows)
{
List<string> authorNames = new List<string>();
foreach (DataRow author in AuthorDataRows)
{
string LastFirstMiddle = author[LastNameColumnIndex].ToString() + ", " + author[FirstNameColumnIndex].ToString() + " " + author[MiddleNameColumnIndex].ToString();
authorNames.Add(LastFirstMiddle);
}
return authorNames;
}
public string AuthorNamesCombinedString(DataRow author)
{
string LastFirstMiddle = author[LastNameColumnIndex].ToString() + ", " + author[FirstNameColumnIndex].ToString() + " " + author[MiddleNameColumnIndex].ToString();
return LastFirstMiddle;
}
protected override void InitializeSqlCommandParameters()
{
MySqlParameterCollection parameters = AddItemParameters;
_addSqlCommandParameter("Last Name", GetDBColumnData("LastName"), parameters["@authorLastName"]);
_addSqlCommandParameter("First Name", GetDBColumnData("FirstName"), parameters["@authorFirstName"]);
_addSqlCommandParameter("Middle Name", GetDBColumnData("MiddleName"), parameters["@authorMiddleName"]);
_addSqlCommandParameter("Year of Birth", GetDBColumnData("YearOfBirth"), parameters["@dob"]);
_addSqlCommandParameter("Year of Death", GetDBColumnData("YearOfDeath"), parameters["@dod"]);
_addSqlCommandParameter("ID", GetDBColumnData("idAuthors"), parameters["@primaryKey"]);
}
#endregion
}
}
</code></pre>
<p><em>AuthorModel.cs</em> </p>
<p>This is the implementation of the <code>DataTableItemBaseModel</code> for the previous
table.</p>
<pre><code>using System.Windows;
using ExperimentSimpleBkLibInvTool.ModelInMVC.ItemBaseModel;
namespace ExperimentSimpleBkLibInvTool.ModelInMVC.Author
{
public class AuthorModel : DataTableItemBaseModel, IAuthorModel
{
private bool errorWasReported;
public string FirstName {
get { return GetParameterValue("First Name"); }
set { SetFirstName(value); }
}
public string MiddleName {
get { return GetParameterValue("Middle Name"); }
set { SetParameterValue("Middle Name", value); }
}
public string LastName {
get { return GetParameterValue("Last Name"); }
set { SetLastName(value); }
}
public string YearOfBirth {
get { return GetParameterValue("Year of Birth"); }
set { SetParameterValue("Year of Birth", value); }
}
public string YearOfDeath {
get { return GetParameterValue("Year of Death"); }
set { SetParameterValue("Year of Death", value); }
}
public uint AuthorId {
get { return GetParameterKValue("ID"); }
private set { SetParameterValue("ID", value); }
}
public AuthorModel()
: base(((App)Application.Current).Model.AuthorTable)
{
errorWasReported = false;
AuthorId = 0;
}
public AuthorModel(string firstName, string lastName, string middleName=null, string yearOfBirth=null, string yearOfDeath=null)
: base(((App)Application.Current).Model.AuthorTable)
{
errorWasReported = false;
AuthorId = 0;
FirstName = firstName;
LastName = lastName;
if (!string.IsNullOrEmpty(middleName))
{
MiddleName = middleName;
}
if (!string.IsNullOrEmpty(yearOfBirth))
{
YearOfBirth = yearOfBirth;
}
if (!string.IsNullOrEmpty(yearOfDeath))
{
YearOfDeath = yearOfDeath;
}
}
public AuthorModel(string idAuthor, string firstName, string lastName, string middleName = null, string yearOfBirth = null, string yearOfDeath = null)
: base(((App)Application.Current).Model.AuthorTable)
{
errorWasReported = false;
uint IdAuthor;
uint.TryParse(idAuthor, out IdAuthor);
AuthorId = IdAuthor;
FirstName = firstName;
LastName = lastName;
if (!string.IsNullOrEmpty(middleName))
{
MiddleName = middleName;
}
if (!string.IsNullOrEmpty(yearOfBirth))
{
YearOfBirth = yearOfBirth;
}
if (!string.IsNullOrEmpty(yearOfDeath))
{
YearOfDeath = yearOfDeath;
}
}
public override bool AddToDb()
{
return ((App)Application.Current).Model.AuthorTable.AddAuthor(this);
}
private void SetFirstName(string textBoxInput)
{
if (string.IsNullOrEmpty(textBoxInput))
{
string errorMsg = "The first name of the author is a required field!";
MessageBox.Show(errorMsg);
errorWasReported = true;
}
else
{
SetParameterValue("First Name", textBoxInput);
}
}
private void SetLastName(string textBoxInput)
{
if (string.IsNullOrEmpty(textBoxInput))
{
string errorMsg = "The last name of the author is a required field!";
MessageBox.Show(errorMsg);
errorWasReported = true;
}
else
{
SetParameterValue("Last Name", textBoxInput);
}
}
protected override bool _dataIsValid()
{
bool isValid = _defaultIsValid();
if (isValid)
{
return isValid;
}
isValid = GetParameterIsValid("First Name");
if (isValid)
{
isValid = GetParameterIsValid("Last Name");
}
if (!isValid && !errorWasReported)
{
string errorMsg = "Add Series error: The first and last names of the author are required fields";
MessageBox.Show(errorMsg);
}
return isValid;
}
}
}
</code></pre>
<p><em>SqlCmdParameter.cs</em> </p>
<pre><code>using System;
using System.Data;
using System.Windows;
using MySql.Data.MySqlClient;
/*
* This class is used to generate SQL command parameters to a call of a
* stored procedure.
*
* This class is a data value for a single column in a single row of data.
* Incoming data will generally be user input and there will be 2 forms of input, either
* a string from a text field or a boolean value from a checkbox.
*
* During the creation of the SQL command parameter the data will be returned as the proprer
* type for the stored procedure. The coversion from input string to the expected SQL type
* will occur during the input phase as an additional check on the validity of the input.
*/
namespace ExperimentSimpleBkLibInvTool.ModelInMVC.DataTableModel
{
public class SqlCmdParameter
{
protected string _publicName; // The name the user knows this field by
protected string _dataBaseColumnName;
protected string _storedProcedureParameterName;
protected ParameterDirection _direction;
protected int _valueInt;
protected string _value; // used for input as the basis of the conversion, and storage for string parameters.
protected double _valueDouble;
protected uint _valueKey;
protected bool _isRequired; // Is this field required to have a value in the database? This is used in the validity check
protected MySqlDbType _type;
protected bool _isValueSet; // internal, used in the validity check
protected bool _skipInsertOfPrimaryKey;
public SqlCmdParameter(string PublicName, string DataBaseColumnName, string SBParamName, MySqlDbType Type, bool IsRequired = false, ParameterDirection Direction=ParameterDirection.Input, bool SkipInserOfPrimaryKey=false)
{
if (string.IsNullOrEmpty(PublicName))
{
ArgumentNullException ex = new ArgumentNullException("PublicName");
throw ex;
}
if (string.IsNullOrEmpty(SBParamName))
{
ArgumentNullException ex = new ArgumentNullException("SBParamName");
throw ex;
}
switch (Type)
{
case MySqlDbType.Int16:
case MySqlDbType.Int32:
case MySqlDbType.Double:
case MySqlDbType.String:
case MySqlDbType.UInt32:
case MySqlDbType.Byte: // TinyInt for boolean representation
break;
case MySqlDbType.VarChar:
case MySqlDbType.Date:
// In the user interface handle VarChar as a string.
Type = MySqlDbType.String;
break;
default:
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("Type");
throw ex;
}
_publicName = PublicName;
_storedProcedureParameterName = SBParamName;
_direction = Direction;
_isRequired = IsRequired;
_type = Type;
_isValueSet = false;
_value = null;
_valueKey = 0;
_valueInt = 0;
_valueDouble = 0.0;
_skipInsertOfPrimaryKey = SkipInserOfPrimaryKey;
}
public SqlCmdParameter(SqlCmdParameter original)
{
_publicName = original._publicName;
_storedProcedureParameterName = original._storedProcedureParameterName;
_direction = original._direction;
_isRequired = original._isRequired;
_type = original._type;
_isValueSet = original._isValueSet;
_value = original._value;
_valueKey = original._valueKey;
_valueInt = original._valueInt;
_valueDouble = original._valueDouble;
_skipInsertOfPrimaryKey = original._skipInsertOfPrimaryKey;
}
public string PublicName
{
get { return _publicName; }
}
public ParameterDirection Direction
{
get { return _direction; }
set { _direction = value; }
}
public bool IsValid { get { return _dataIsValid(); } }
public bool IsRequired
{
get { return _isRequired; }
set { _isRequired = value; }
}
public string Value
{
get { return _value; }
set { SetValue(value); }
}
public bool BValue
{
get { return (_valueInt > 0); }
set { SetValue(value); }
}
public uint KeyValue
{
get { return _valueKey; }
set { _valueKey = value; }
}
public MySqlDbType Type
{
get { return _type; }
}
public bool AddParameterToCommand(MySqlCommand cmd)
{
if (_skipInsertOfPrimaryKey)
{
return true;
}
// If it is an output variable validity doesn't matter.
if (_direction != ParameterDirection.Input)
{
string IndexByNameValue = _storedProcedureParameterName;
cmd.Parameters.Add(new MySqlParameter(IndexByNameValue, _type));
cmd.Parameters[IndexByNameValue].Direction = _direction;
return true;
}
if (!IsValid)
{
return IsValid;
}
switch (_type)
{
case MySqlDbType.Byte:
case MySqlDbType.Int16:
case MySqlDbType.Int32:
cmd.Parameters.AddWithValue(_storedProcedureParameterName, _valueInt);
break;
case MySqlDbType.Double:
cmd.Parameters.AddWithValue(_storedProcedureParameterName, _valueDouble);
break;
case MySqlDbType.UInt32:
cmd.Parameters.AddWithValue(_storedProcedureParameterName, _valueKey);
break;
case MySqlDbType.String:
cmd.Parameters.AddWithValue(_storedProcedureParameterName, _value);
break;
}
return true;
}
protected void SetValue(string value)
{
if (string.IsNullOrEmpty(value))
{
return;
}
_value = value;
string eMsg = null;
switch (_type)
{
case MySqlDbType.Int16:
case MySqlDbType.Byte:
bool tmp = false;
if (!bool.TryParse(_value, out tmp))
{
eMsg = _publicName + ": Value is not True or False";
}
_valueInt = (tmp) ? 1 : 0;
break;
case MySqlDbType.Int32:
if (!int.TryParse(_value, out _valueInt))
{
eMsg = _publicName + ": Value is not in the proper format of an integer";
}
break;
case MySqlDbType.Double:
if (!double.TryParse(_value, out _valueDouble))
{
eMsg = _publicName + ": Value is not in the proper format of an floating point number";
}
break;
case MySqlDbType.UInt32:
_valueKey = Convert.ToUInt32(value);
if (!uint.TryParse(_value, out _valueKey))
{
eMsg = _publicName + ": Value is not in the proper format of an unsigned integer";
}
break;
case MySqlDbType.String:
default:
break;
}
if (eMsg != null)
{
MessageBox.Show(eMsg);
_isValueSet = false;
}
else
{
_isValueSet = true;
}
}
protected void SetValue(bool InVal)
{
_value = (InVal) ? "true" : "false";
if (_type == MySqlDbType.Int16 || _type == MySqlDbType.Byte)
{
_valueInt = (InVal) ? 1 : 0;
}
_isValueSet = true;
}
protected bool _dataIsValid()
{
bool dataIsValid = true;
if (_direction == ParameterDirection.Input && _isRequired && !_isValueSet)
{
dataIsValid = false;
}
return dataIsValid;
}
}
}
</code></pre>
<p><em>DBColParameterData.cs</em> </p>
<pre><code>using System.Data;
namespace ExperimentSimpleBkLibInvTool.ModelInMVC
{
public class DbColumnParameterData
{
public DbColumnParameterData(DataRow ColumnData)
{
bool parseWorked = true;
ColumnName = ColumnData[0].ToString();
parseWorked = int.TryParse(ColumnData[1].ToString(), out int ordinalPosition);
Ordinal_Posistion = ordinalPosition;
IsNullable = true;
}
public DbColumnParameterData(string columnName, int ordinal_Posistion, bool isNullable)
{
ColumnName = columnName;
Ordinal_Posistion = ordinal_Posistion;
IsNullable = isNullable;
}
public string ColumnName { get; private set; }
public int Ordinal_Posistion { get; private set; }
public bool IsNullable { get; private set; }
public int IndexBasedOnOrdinal { get { return Ordinal_Posistion - 1; } }
}
}
</code></pre>
<p><em>DataTableModel.cs</em> </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Windows;
using MySql.Data.MySqlClient;
using ExperimentSimpleBkLibInvTool.ModelInMVC.ItemBaseModel;
/*
*
* This file provides the database interface layer. All data retrieval and inserts
* are performed in this file. Information about each table is stored in the
* super classes that inherit from this class, but the data structures are located
* in this base class.
*
*/
namespace ExperimentSimpleBkLibInvTool.ModelInMVC.DataTableModel
{
public abstract class CDataTableModel : ObservableModelObject
{
protected string _dbConnectionString;
protected string _getTableStoredProcedureName;
protected string _addItemStoredProcedureName;
protected string _tableName;
protected uint _newKeyValue;
protected MySqlParameterCollection _addItemStoredProcedureParameters;
protected List<DbColumnParameterData> _parameterProperties;
protected Dictionary<string, int> ParametersIndexedByPublicName;
protected Dictionary<string, int> ParametersIndexedByDatabaseTableName;
protected Dictionary<string, int> ParametersIndexedByParameterName;
private List<SqlCmdParameter> _sqlCmdParameters;
public uint NewKeyValue { get { return _newKeyValue; } }
public MySqlParameterCollection AddItemParameters { get { return _addItemStoredProcedureParameters; } }
public List<DbColumnParameterData> ColumnParameterData { get; private set; }
protected DataTable DataTable { get { return getDataTable(); } }
// The impementation of this function requires detailed knowlege of the columns in the table
// and the parameters of the stored procedure.
protected abstract void InitializeSqlCommandParameters();
public DbColumnParameterData GetDBColumnData(string columnName)
{
return ColumnParameterData.Find(x => x.ColumnName == columnName);
}
public List<SqlCmdParameter> SQLCommandParameters { get { return _sqlCmdParameters; } }
public Dictionary<string, int> PublicNameParameterIndex { get { return ParametersIndexedByPublicName; } }
public Dictionary<string, int> ParametersIndexByDbColumnName { get { return ParametersIndexedByDatabaseTableName; } }
public Dictionary<string, int> ParametersIndexByStoredProcedureName { get { return ParametersIndexedByParameterName; } }
protected CDataTableModel(string TableName, string GetTableStoredProcedureName, string AddItemToTableStoredProcedureName=null)
{
_newKeyValue = 0;
_tableName = TableName;
_getTableStoredProcedureName = GetTableStoredProcedureName;
_addItemStoredProcedureName = AddItemToTableStoredProcedureName;
_dbConnectionString = ConfigurationManager.ConnectionStrings["LibInvToolDBConnStr"].ConnectionString;
_sqlCmdParameters = new List<SqlCmdParameter>();
ParametersIndexedByPublicName = new Dictionary<string, int>();
ParametersIndexedByDatabaseTableName = new Dictionary<string, int>();
ParametersIndexedByParameterName = new Dictionary<string, int>();
// Not all datatable classes can add items, 2 examples are the status table and the condition table.
if (!string.IsNullOrEmpty(AddItemToTableStoredProcedureName))
{
GetParametersNamesFromAddCommand();
ColumnParameterData = GetColumnParameterProperties();
InitializeSqlCommandParameters();
ValidateParameterCount();
}
}
protected bool addItem(DataTableItemBaseModel NewDataItem)
{
bool canAddItemToTable = true;
canAddItemToTable = NewDataItem.IsValid;
if (canAddItemToTable)
{
canAddItemToTable = dbAddItem(NewDataItem);
}
return canAddItemToTable;
}
protected bool _addParametersInOrder(MySqlCommand cmd, DataTableItemBaseModel NewDataItem)
{
foreach (MySqlParameter parameter in _addItemStoredProcedureParameters)
{
if (!NewDataItem.AddParameterToCommand(cmd, parameter.ParameterName))
{
return false;
}
}
return true;
}
protected void _addSqlCommandParameter(string PublicName, DbColumnParameterData ColumnData, MySqlParameter parameter)
{
bool isRequired = false;
string DBColumnName = (ColumnData != null) ? ColumnData.ColumnName : "primaryKey";
if (!ParameterIsValid(PublicName, DBColumnName, parameter.ParameterName))
{
return;
}
if (ColumnData == null || ColumnData.IsNullable)
{
isRequired = false;
}
else
{
isRequired = true;
}
SqlCmdParameter NewParameter = new SqlCmdParameter(PublicName, DBColumnName, parameter.ParameterName, parameter.MySqlDbType, isRequired, parameter.Direction);
ParametersIndexedByPublicName.Add(PublicName, _sqlCmdParameters.Count);
ParametersIndexedByDatabaseTableName.Add(DBColumnName, _sqlCmdParameters.Count);
ParametersIndexedByParameterName.Add(parameter.ParameterName, _sqlCmdParameters.Count);
_sqlCmdParameters.Add(NewParameter);
}
private bool dbAddItem(DataTableItemBaseModel NewDataItem)
{
bool AddItemSuccess = true;
if (ReportProgrammerError(_addItemStoredProcedureName, "_addItemStoredProcedureName is not set!"))
{
return false;
}
using (MySqlConnection conn = new MySqlConnection(_dbConnectionString))
{
try
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = _addItemStoredProcedureName;
if (_addParametersInOrder(cmd, NewDataItem))
{
cmd.ExecuteNonQuery();
// Some of the stored procedures return the new key in the last parameter
// in those cases get the returned key so that the new row can be accessed.
int paramtercount = cmd.Parameters.Count - 1; // indexing starts at 0 ends at count - 1
if (cmd.Parameters[paramtercount].Direction != ParameterDirection.Input)
{
uint.TryParse(cmd.Parameters[paramtercount].Value.ToString(), out _newKeyValue);
}
OnPropertyChanged();
}
else
{
AddItemSuccess = false;
}
}
}
catch (Exception ex)
{
string errorMsg = "Database Error: " + ex.Message;
MessageBox.Show(errorMsg);
AddItemSuccess = false;
}
}
return AddItemSuccess;
}
private DataTable getDataTable()
{
int ResultCount = 0;
DataTable Dt = new DataTable();
if (!ReportProgrammerError(_getTableStoredProcedureName, "_getTableStoredProcedureName is not set!"))
{
try
{
using (MySqlConnection conn = new MySqlConnection(_dbConnectionString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = _getTableStoredProcedureName;
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
ResultCount = sda.Fill(Dt);
OnPropertyChanged();
}
}
}
catch (Exception ex)
{
string errorMsg = "Database Error: " + ex.Message;
MessageBox.Show(errorMsg);
}
}
return Dt;
}
private void GetParametersNamesFromAddCommand()
{
if (!string.IsNullOrEmpty(_addItemStoredProcedureName))
{
// Neither the status table or the condition table have stored procedures to
// add data to the tables, these tables are included in add book.
try
{
using (MySqlConnection conn = new MySqlConnection(_dbConnectionString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = _addItemStoredProcedureName;
cmd.Connection = conn;
MySqlCommandBuilder.DeriveParameters(cmd);
_addItemStoredProcedureParameters = cmd.Parameters;
}
}
}
catch (Exception ex)
{
string errorMsg = "Table: " + _tableName + " Stored Procedure: " + _addItemStoredProcedureName + "\nDatabase Error Initializing Command Parameter Properties: ";
errorMsg += ex.Message;
MessageBox.Show(errorMsg, "Database Error:", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
// Due to bugs/unimplemented features in MySQL MySqlCommandBuilder.DeriveParameters(Command)
// such as IsNullable will always be false this provides a workaround for getting additional
// information about each parameter
private List<DbColumnParameterData> GetColumnParameterProperties()
{
List<DbColumnParameterData> columnSchemaDetails = new List<DbColumnParameterData>();
DataTable Dt = new DataTable();
int ResultCount = 0;
if (!ReportProgrammerError(_tableName, "_tableName is not set!"))
{
try
{
using (MySqlConnection conn = new MySqlConnection(_dbConnectionString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "getTableColumnData";
cmd.Parameters.AddWithValue("tableName", _tableName);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
ResultCount = sda.Fill(Dt);
}
}
foreach (DataRow dataRow in Dt.Rows)
{
columnSchemaDetails.Add(new DbColumnParameterData(dataRow));
}
}
catch (Exception ex)
{
string errorMsg = "Database Error Initializing Parameter Properties: " + ex.Message;
MessageBox.Show(errorMsg, "Database Error:", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return columnSchemaDetails;
}
private bool ReportProgrammerError(string nameToCheck, string errorMessage)
{
if (string.IsNullOrEmpty(nameToCheck))
{
#if DEBUG
string errorMsg = "Programmer ERROR : " + errorMessage;
MessageBox.Show(errorMsg, "Programmer ERROR", MessageBoxButton.OK, MessageBoxImage.Error);
#endif
return true;
}
return false;
}
private bool ParameterIsValid(string PublicName, string DataBaseColumnName, string StoredProcedureParamName)
{
bool isValid = true;
if (ReportProgrammerError(PublicName, "PublicName is null or empty in _addSqlCommandParameter"))
{
isValid = false;
}
if (ReportProgrammerError(DataBaseColumnName, "DataBaseColumnName is null or empty in _addSqlCommandParameter"))
{
isValid = false;
}
if (ReportProgrammerError(StoredProcedureParamName, "SBParamName is null or empty in _addSqlCommandParameter"))
{
isValid = false;
}
return isValid;
}
private bool ValidateParameterCount()
{
bool validCount = _sqlCmdParameters.Count == _addItemStoredProcedureParameters.Count;
#if DEBUG
if (!validCount)
{
string eMsg = "Stored Procedure: " + _addItemStoredProcedureName + " Expected parameter count is " + _addItemStoredProcedureParameters.Count.ToString() +
" Actual parameter count is " + _sqlCmdParameters.Count.ToString();
MessageBox.Show(eMsg, "Invalid Parameter Count", MessageBoxButton.OK, MessageBoxImage.Error);
}
#endif
return (validCount);
}
}
}
</code></pre>
<p><em>DataTableItemBaseModel.cs</em> </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.Windows;
using MySql.Data.MySqlClient;
using ExperimentSimpleBkLibInvTool.ModelInMVC.DataTableModel;
/*
* There is a tight coupling between each model and the table it belongs to. This
* is due to the models ability to add parameters to the tables call to the stored
* procedure. This is only true when a model can be added to a table.
*
* This class represents a row of data in a data table. Generally it will be used
* to add a row to a database table.
*/
namespace ExperimentSimpleBkLibInvTool.ModelInMVC.ItemBaseModel
{
public abstract class DataTableItemBaseModel
{
/*
* To save memory and correctly change the proper command parameter, only the
* _sqlCmdParameters list contains SqlCmdParameters and the dictionaries provide
* indexes into the command parameters list. To maintain good performance the
* dictionaries are used rather than using a find in the list.
*/
private List<SqlCmdParameter> _sqlCmdParameters;
private Dictionary<string, int> _parameterIndexByPublicName;
private Dictionary<string, int> _parameterIndexByDatabaseTableName;
private Dictionary<string, int> _parameterIndexByParameterName;
public bool IsValid { get { return _dataIsValid(); } }
public uint BookId
{
get { return GetParameterKValue("ID"); }
set { SetParameterValue("ID", value); }
}
public void setBookId(uint BookId)
{
SetParameterValue("ID", BookId);
}
public abstract bool AddToDb();
protected abstract bool _dataIsValid();
protected DataTableItemBaseModel(CDataTableModel DBInterfaceModel)
{
_sqlCmdParameters = new List<SqlCmdParameter>();
List<SqlCmdParameter> sqlCmdParameters = DBInterfaceModel.SQLCommandParameters;
foreach (SqlCmdParameter parameter in sqlCmdParameters)
{
SqlCmdParameter p = new SqlCmdParameter(parameter);
_sqlCmdParameters.Add(p);
}
_parameterIndexByPublicName = new Dictionary<string, int>(DBInterfaceModel.PublicNameParameterIndex);
_parameterIndexByParameterName = new Dictionary<string, int>(DBInterfaceModel.ParametersIndexByStoredProcedureName);
_parameterIndexByDatabaseTableName = new Dictionary<string, int>();
_parameterIndexByDatabaseTableName = new Dictionary<string, int>(DBInterfaceModel.ParametersIndexByDbColumnName);
}
/*
* Sometimes the number of parameters in the stored procedure count doesn't
* match the nummber of columns in the table. This function can be overriden
* in those cases. Two examples of this are the Series and Books.
*/
public bool AddParameterToCommand(MySqlCommand cmd, string ParameterName)
{
bool success = true;
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
MySqlParameterCollection parameters = cmd.Parameters;
success = _sqlCmdParameters[tableIndex].AddParameterToCommand(cmd);
}
else
{
success = false;
}
return success;
}
public string GetParameterValue(string ParameterName)
{
string ParameterValue = "Failure";
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
ParameterValue = _sqlCmdParameters[tableIndex].Value;
}
return ParameterValue;
}
public uint GetParameterKValue(string ParameterName)
{
uint ParameterValue = 0;
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
ParameterValue = _sqlCmdParameters[tableIndex].KeyValue;
}
return ParameterValue;
}
public int GetParameterIValue(string ParameterName)
{
int ParameterValue = -1;
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
ParameterValue = Convert.ToInt32(_sqlCmdParameters[tableIndex].Value);
}
return ParameterValue;
}
protected ParameterDirection GetParameterDirection(string ParameterName)
{
ParameterDirection Direction = ParameterDirection.Input;
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
Direction = _sqlCmdParameters[tableIndex].Direction;
}
return Direction;
}
protected MySqlDbType GetParameterType(string ParameterName)
{
MySqlDbType Type = MySqlDbType.String;
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
Type = _sqlCmdParameters[tableIndex].Type;
}
return Type;
}
protected void SetParameterValue(string ParameterName, string value)
{
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
_sqlCmdParameters[tableIndex].Value = value;
}
}
protected void SetParameterValue(string ParameterName, uint value)
{
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
_sqlCmdParameters[tableIndex].Value = value.ToString();
_sqlCmdParameters[tableIndex].KeyValue = value;
}
}
protected void SetParameterValue(string ParameterName, int value)
{
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
_sqlCmdParameters[tableIndex].Value = value.ToString();
}
}
protected void SetParameterValue(string ParameterName, bool value)
{
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
_sqlCmdParameters[tableIndex].BValue = value;
}
}
protected bool GetParameterBValue(string ParameterName)
{
bool ParameterValue = false;
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
ParameterValue = _sqlCmdParameters[tableIndex].BValue;
}
return ParameterValue;
}
protected uint GetKeyValue()
{
uint KeyValue = 0;
int tableIndex = getParameterIndex("ID");
if (tableIndex >= 0)
{
KeyValue = _sqlCmdParameters[tableIndex].KeyValue;
}
return KeyValue;
}
protected void SetKeyValue(uint KeyValue)
{
int tableIndex = getParameterIndex("ID");
if (tableIndex >= 0)
{
_sqlCmdParameters[tableIndex].KeyValue = KeyValue;
}
}
public bool GetParameterIsValid(string ParameterName)
{
bool ParameterIsValid = false;
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
ParameterIsValid = _sqlCmdParameters[tableIndex].IsValid;
}
return ParameterIsValid;
}
protected bool GetParameterIsRequired(string ParameterName)
{
bool ParameterIsRequired = false;
int tableIndex = getParameterIndex(ParameterName);
if (tableIndex >= 0)
{
ParameterIsRequired = _sqlCmdParameters[tableIndex].IsRequired;
}
return ParameterIsRequired;
}
private int getParameterIndex(string parameterName)
{
int parameterIndex = -1;
int tableIndex;
if (_parameterIndexByParameterName.TryGetValue(parameterName, out tableIndex))
{
parameterIndex = tableIndex;
}
else if (_parameterIndexByPublicName.TryGetValue(parameterName, out tableIndex))
{
parameterIndex = tableIndex;
}
else if (_parameterIndexByDatabaseTableName.TryGetValue(parameterName, out tableIndex))
{
parameterIndex = tableIndex;
}
#if DEBUG
// ASSERT
else
{
string eMsg = "Programmer error in getParameterIndex(): Parameter not found: " + parameterName;
MessageBox.Show(eMsg, "Programmer Error:", MessageBoxButton.OK, MessageBoxImage.Error);
}
#endif
return parameterIndex;
}
protected bool _defaultIsValid()
{
bool isValid = true;
foreach (SqlCmdParameter parameter in _sqlCmdParameters)
{
isValid = parameter.IsValid;
if (parameter.Direction == ParameterDirection.Input && !isValid)
{
return isValid;
}
}
return isValid;
}
}
}
</code></pre>
<p><em>DictionaryTableModel.cs</em> </p>
<pre><code>using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows;
using ExperimentSimpleBkLibInvTool.ModelInMVC.DataTableModel;
using ExperimentSimpleBkLibInvTool.ModelInMVC.ItemBaseModel;
namespace ExperimentSimpleBkLibInvTool.ModelInMVC.DictionaryTabelBaseModel
{
public abstract class DictionaryTableModel : CDataTableModel
{
private Dictionary<uint, string> _keyToTitle;
private Dictionary<string, uint> _titleToKey;
public DictionaryTableModel(string TableName, string GetTableStoredProcedureName, string AddItemToTableStoredProcedureName = null) :
base(TableName, GetTableStoredProcedureName, AddItemToTableStoredProcedureName)
{
_titleToKey = new Dictionary<string, uint>();
_keyToTitle = new Dictionary<uint, string>();
_titleToKey = DataTable.AsEnumerable().ToDictionary(row => row.Field<string>(0), row => row.Field<uint>(1));
_keyToTitle = DataTable.AsEnumerable().ToDictionary(row => row.Field<uint>(1), row => row.Field<string>(0));
}
public List<string> ListBoxSelectionList()
{
List<string> listBoxSelectionValues = _keyToTitle.Values.ToList<string>();
return listBoxSelectionValues;
}
protected string KeyToName(uint Key)
{
return _keyToTitle[Key];
}
protected uint NameToKey(string CategoryTitle)
{
return _titleToKey[CategoryTitle];
}
protected void AddItemToDictionary(DataTableItemBaseModel NewItem)
{
bool AddedSuccessfully = addItem(NewItem);
if (AddedSuccessfully && _newKeyValue > 0)
{
_keyToTitle.Add(_newKeyValue, NewItem.GetParameterValue("Name"));
_titleToKey.Add(NewItem.GetParameterValue("Name"), _newKeyValue);
}
else
{
string errorMsg = "Database Error: Failed to add item";
MessageBox.Show(errorMsg);
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>I won't read this code beginning to end. Some basic advice:</p>\n\n<h2>Namespaces</h2>\n\n<p><code>ExperimentSimpleBkLibInvTool.ModelInMVC.DictionaryTabelBaseModel</code> doesn't follow naming conventions. \nNaming convention is <code>Company.App.Module</code>. \nIt should be something like: <code>Pacmaninbw.PersonalLibrary.Model</code>.</p>\n\n<h2>Naming</h2>\n\n<ol>\n<li><p>Don't tack on crap affixes to the names. </p>\n\n<ul>\n<li><p><code>ExperimentSimple...</code> \nIt's ok to write experimentally low quality code. \nBut stating the experimentality of the code belongs to README.md. \nPutting it in the name makes it even lower quality. \nIf you are worried people will use your code to operate Nuclear Reactors and Airliners put legal discalimers in the LICENCE.txt.</p></li>\n<li><p><code>...Tool</code> \nIt's either a \"library\" or a \"book inventory\", but never a \"book library inventory tool\", much less \"bk lib inv tool\". \nYou can say \"screwdriver\" or \"hammer\", but never \"nail driver hammer tool\".</p></li>\n</ul></li>\n<li><p>Don't repeat pattern artifacts in names (<code>ModelInMVC</code>)</p></li>\n</ol>\n\n<p>If you are following a well-known pattern no need to mangle names to advertise it.\nWhen you are following patterns follow the naming conventions in the examples.\nIf you, for some reason, are writing a singleton, add an <code>Instance</code> property. \nDon't name the property <code>TheSingletonInstance</code>.\nIf you put <code>Models</code>, <code>Views</code>, <code>Controllers</code> folders people will understand you are following a pattern, especially if it is the IDE default. \nIf you are following an obscure pattern, document it with the sources where others can learn about it and the reasons you chose it in the README.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:15:35.270",
"Id": "416829",
"Score": "0",
"body": "I really want a *nail driver hammer tool* now. +1 Good notes on naming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T16:48:04.117",
"Id": "417328",
"Score": "0",
"body": "I have changed all the namespaces to reflect your comment in the repository. Could you point me to online documentation for this naming convention? By default Microsoft Visual Studio uses the project name as the default namespace."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T12:47:46.863",
"Id": "417462",
"Score": "1",
"body": "@pacmaninbw namespace naming convention [straight from the horse's mouth](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-namespaces)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T13:36:08.800",
"Id": "417660",
"Score": "1",
"body": "It would be nice if Visual Studio defaulted to this naming convention based on who the horse is."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T08:50:27.390",
"Id": "215485",
"ParentId": "215431",
"Score": "6"
}
},
{
"body": "<h1>Application Architecture</h1>\n\n<blockquote>\n <p>The architecture of the application is divided into models and views to separate the data and business model \n from the user interface. Within the models there is an additional division, there are models that represent the \n database tables and there are models that represent a row of data within each database table.</p>\n</blockquote>\n\n<p>You missed an opportunity to split view layout from its logic using <a href=\"https://www.markwithall.com/programming/2013/03/01/worlds-simplest-csharp-wpf-mvvm-example.html\" rel=\"noreferrer\">Model-View-ViewModel</a>:</p>\n\n<ul>\n<li><strong>View</strong>: any user or data control represented in xaml</li>\n<li><strong>ViewModel</strong>: the data context a view binds to and provides access to the application layer</li>\n<li><strong>Model</strong>: any services, entities and dependencies used in the application, and accessible to the view models</li>\n</ul>\n\n<p>The classes that reside in the model don't require to be *Model classes or even to be in the same layer. You have distinguished between (1) data table models\nand (2) data record models. It is more common to split these into explicit layers:</p>\n\n<ul>\n<li><strong>Presentation Layer</strong>: the views and view models</li>\n<li><strong>Business Layer</strong>: the classes that represent your business classes (Book, Author, Rating, ..)</li>\n<li><strong>Data-Access Layer</strong>: objects that manage interaction between the database and the business entities (preferably using an <a href=\"https://stackoverflow.com/questions/3187928/best-orm-to-use-with-c-sharp-4-0\">ORM Framework</a>)</li>\n</ul>\n\n<hr>\n\n<h1>Design Metrics</h1>\n\n<blockquote>\n <p>Was inheritance abused or over used?</p>\n</blockquote>\n\n<p>Your models have a depth of 2, max 3 classes in inheritance. \nGiven the fact you have implemented your own base classes to provide custom ORM (as explained by the OP), I find this complexity within reasonal bounds.</p>\n\n<blockquote>\n <p>Is this a SOLID OOP design?</p>\n</blockquote>\n\n<p>It's an attempt at SOLID and OOP design, but with several offenses against these principles.</p>\n\n<h3>Single responsibility principle</h3>\n\n<ul>\n<li>data table models have properties that represent list box values; these properties should be on view models</li>\n<li>data record models serve both as business entities and records with database mapping aware properties; these objects should become business entities (preferrably <a href=\"https://en.wikipedia.org/wiki/Plain_old_CLR_object\" rel=\"noreferrer\">POCO</a>) with the database aware mapping extracted and stored inside the data table models</li>\n<li>views should offset the logic to view-models, who in term use business entities and data layer objects in the backend</li>\n</ul>\n\n<h3>Open/closed principle</h3>\n\n<ul>\n<li>the models are not closed for changes; you provide public accessors to the internal state; instead you should take more care of encapsulation and provide methods to request the models to change data</li>\n</ul>\n\n<h3>Dependency inversion principle</h3>\n\n<ul>\n<li>your application depends your models, there is no easy way to replace any of your layers by another; to allow dependency inversion, you should let layers communicate to each other through interfaces, and use <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"noreferrer\">Dependency Injection</a> to configure the layers at runtime.</li>\n</ul>\n\n<h3>Test-driven design</h3>\n\n<ul>\n<li>it's hard to test the seperate layers, since you don't use interfaces between layers, making it virtually impossible to mock out dependencies</li>\n<li>you have included message box prompts inside model logic, which is a pain to test with a unit tests</li>\n</ul>\n\n<hr>\n\n<h1>Review</h1>\n\n<ul>\n<li>You should read the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions\" rel=\"noreferrer\">C# Naming Conventions</a>. Many of your method and variable names are offenses against conventions.</li>\n<li>Don't use Green and Red for button colors. They make the app look like a color book. It's better to use a set of icons that are universal.</li>\n<li>Don't use center alignment for a list of buttons, instead wrap vertically with the same width.</li>\n</ul>\n\n<h3>CategoryTableModel</h3>\n\n<p>Using magic string literals is a design smell. If you must work with such strings, declare them in a dedicated class <code>DataSchemaConstants</code>.</p>\n\n<blockquote>\n<pre><code>public CategoryTableModel() : base(\"bookcategories\", \"getAllBookCategoriesWithKeys\", \"addCategory\")\n{\n}\n</code></pre>\n</blockquote>\n\n<p>Use the arrow notation when you can.</p>\n\n<pre><code>public string CategoryTitle(uint Key) => KeyToName(Key);\n</code></pre>\n\n<h3>AuthorTableModel</h3>\n\n<p>It is unclear what magic you are performing to get a key in <code>AuthorKey</code> when <code>if (key < 1)</code>. Methods should be self-explaining. But this one needs comments. Why should <code>key < 1</code> be able to get remapped to a valid key? Also, prefer proper <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"noreferrer\">string interpolation</a> over string concatenation.</p>\n\n<blockquote>\n<pre><code>public uint AuthorKey(AuthorModel author)\n{\n uint key = author.AuthorId;\n if (key < 1)\n {\n DataTable dt = AuthorTable;\n string filterString = \"LastName = '\" + author.LastName + // .. removed for brevity\n DataRow[] authors = dt.Select(filterString);\n if (authors.Length > 0)\n {\n if (!uint.TryParse(authors[0][AuthorIDColumnIndex].ToString(), out key))\n {\n key = 0;\n }\n }\n else\n {\n key = 0;\n }\n }\n\n return key;\n}\n</code></pre>\n</blockquote>\n\n<h3>AuthorModel</h3>\n\n<p>Here's a blatant offense against single-responsibility. Don't use representation logic in your models. <code>MessageBox</code> should never be called here. Instead, throw an exception, and catch it at the top most layer, at the view-model. Also think about how to test this code. A unit test with a prompt in it, is not the best idea.</p>\n\n<blockquote>\n<pre><code>private void SetFirstName(string textBoxInput)\n{\n if (string.IsNullOrEmpty(textBoxInput))\n {\n string errorMsg = \"The first name of the author is a required field!\";\n MessageBox.Show(errorMsg);\n errorWasReported = true;\n }\n else\n {\n SetParameterValue(\"First Name\", textBoxInput);\n }\n}\n</code></pre>\n</blockquote>\n\n<h3>Other Classes</h3>\n\n<p>Should be replaced with an ORM Framework.</p>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T15:00:48.660",
"Id": "436357",
"Score": "1",
"body": "Thank you for an in depth review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T15:31:30.170",
"Id": "436363",
"Score": "0",
"body": "Why is string interpolation to be preferred over string concatenation? Not being difficult, there should just be a good reason for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T15:33:19.840",
"Id": "436364",
"Score": "0",
"body": "Based on the AuthorModel part of the review, all data error reporting should be done at the view-model level rather than at the model level?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T15:34:09.147",
"Id": "436365",
"Score": "1",
"body": "about string interpolation vs concatenation: https://stackoverflow.com/questions/42370614/concatenating-using-interpolated-strings-vs-operator-in-c-sharp. also, for readability"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T15:35:20.790",
"Id": "436366",
"Score": "1",
"body": "Yes, reporting should be at top level. Only if you want to intercept errors at the model (to branch to other flow, optionally retthrowing the exception or throwing a new one), should the model handle exceptions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T15:50:16.903",
"Id": "436378",
"Score": "0",
"body": "Since the function `public uint AuthorKey(AuthorModel author)` is never referenced I should delete it. When an author is added using the `Add Author` dialog the instance does not initially have a value for Key. It is only after the author is added to the database that the primary key exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T16:01:04.447",
"Id": "436380",
"Score": "1",
"body": "One reason to keep public methods in an API that you don't use, is to allow for them to be used later. If they make sense, keep them."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T14:39:19.017",
"Id": "224899",
"ParentId": "215431",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "224899",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T16:35:58.343",
"Id": "215431",
"Score": "8",
"Tags": [
"c#",
".net",
"mysql",
"database",
"wpf"
],
"Title": "Non-Entity framework database interaction model"
} | 215431 |
<p>I have this code to get the current Timestamp and compute the last timestamp's difference with the current timestamp in minutes. I'm wondering if this can be optimized further for production.</p>
<pre><code>public static Timestamp getTimestamp() {
java.util.Date date= new java.util.Date();
long time = date.getTime();
java.sql.Timestamp ts = new java.sql.Timestamp(time);
return ts;
}
public static long getLastTimestampElapse(java.sql.Timestamp oldTime){
long milliseconds1 = oldTime.getTime();
long milliseconds2 = getTimestamp().getTime();
long diff = milliseconds2 - milliseconds1;
long diffMinutes = diff / (60 * 1000);
return diffMinutes;
}
</code></pre>
| [] | [
{
"body": "<p>Note that none of these suggestions will have any significant impact on the performance of your application overall. Don't micro-optimize performance until you have known, tested bottlenecks.</p>\n\n<p>The <code>getTimestamp()</code> method is noise. If all you care about is the current timestamp in milliseconds, use <code>System.currentTimeMillis()</code>.</p>\n\n<p>You can use a constant to store the number of milliseconds in a minute, potentially saving the multiplication. Even if the compiler optimizes the math away, it's easier to read.</p>\n\n<p>A <code>java.sql.Timestamp</code> is a kind of <code>java.util.Date</code>, and the <code>getTime()</code> method is defined there. Your method should accept a <code>java.util.Date</code> to support more clients at no cost.</p>\n\n<p>Your method is poorly named. Something like <code>getMinutesSince()</code> would be more readable. Likewise, there are better variable names than what you've selected.</p>\n\n<p>Use <code>final</code> to indicate that variables won't be reassigned. That reduces the cognitive load on the reader.</p>\n\n<p>You don't really need as many variables as you have. You might even be able to get away with none and still have a reasonably clear method.</p>\n\n<p>If you were to use all my suggestions, your code might look more like:</p>\n\n<pre><code>private static final long MILLISECONDS_PER_MINUTE = 60 * 1000;\n\npublic static long getMinutesSince(final java.util.Date startTime) {\n final long millisecondsSinceStart =\n System.currentTimeMillis() - startTime.getTime();\n return millisecondsSinceStart / MILLISECONDS_PER_MINUTE;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T23:51:07.150",
"Id": "416751",
"Score": "1",
"body": "You might want to assign `MILLISECONDS_PER_MINUTE` to something. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T03:33:21.280",
"Id": "416763",
"Score": "1",
"body": "TimeUnit.MILLISECONDS.toMinutes(millisecondsSinceStart) - TimeUnit already has constants for you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:10:34.933",
"Id": "416827",
"Score": "0",
"body": "@AJNeufeld That's what I get for editing directly in the window instead of moving to my editor. Fixed, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:11:05.200",
"Id": "416828",
"Score": "0",
"body": "@AlexeyRagozin That's a good point. I personally find it harder to read in this case, but it's a good option for the OP to be aware of. Thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:31:56.003",
"Id": "215442",
"ParentId": "215432",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T16:36:15.207",
"Id": "215432",
"Score": "2",
"Tags": [
"java",
"performance",
"datetime"
],
"Title": "Getting the current timestamp and compute the timestamp difference in minutes"
} | 215432 |
<p>I am new to Go and wrote program to download and save bulk URLs concurrently. It is working correctly, but I would like to make it more efficient and follow best practices.</p>
<pre><code>package main
import (...)
// Connection String
const connectionString = "connectionString"
// Declare Channels
var wg sync.WaitGroup
var ch = make(chan *item) // For success item(s)
var errItems = make(chan *item) // For error item(s)
type item struct {
id int
url string
path string
content []byte
err error
}
func main() {
start := time.Now()
var basePath = os.Args[1]
var from, to = os.Args[2], os.Args[3]
db, err := sql.Open("sqlserver", connectionString)
if err != nil {
log.Fatal(err.Error())
}
rows, err := db.Query("SELECT [ImageID],[AccommodationlID],[Link],[FileName] FROM [dbo].[AccomodationImage] where AccommodationlID between @from and @to and FileName not like '%NoHotel.png%'", sql.Named("from", from), sql.Named("to", to))
if err != nil {
log.Fatal(err.Error())
}
defer db.Close()
for rows.Next() {
var item = item{}
var accId, name string
_ = rows.Scan(&item.id, &accId, &item.url, &name)
item.path = fmt.Sprintf("%s\\%s\\%s", basePath, accId, name)
wg.Add(1)
go downloadFile(&item)
go func() {
select {
case done := <-ch:
wg.Add(1)
go saveAndUpdateFile(db, done)
case errorItem := <-errItems:
wg.Add(1)
go printResult(errorItem)
}
}()
}
wg.Wait()
fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
}
func downloadFile(item *item) {
defer wg.Done()
resp, err := http.Get(item.url)
if err != nil {
item.content, item.err = nil, err
} else if resp.StatusCode != http.StatusOK {
item.content, item.err = nil, errors.New(resp.Status)
} else {
item.content, item.err = ioutil.ReadAll(resp.Body)
}
if item.err != nil {
errItems <- item
} else {
ch <- item
}
}
func saveAndUpdateFile(db *sql.DB, item *item) {
defer wg.Done()
if item.content == nil {
item.err = errors.New("Content is empty.")
} else {
dir := filepath.Dir(item.path)
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
item.err = err
} else {
item.err = ioutil.WriteFile(item.path, item.content, 0644)
}
}
if item.err == nil {
result, err := db.Exec("UPDATE [dbo].[AccomodationImage] SET IsRead = 1 WHERE ImageID = @id", sql.Named("id", item.id))
if rows, _ := result.RowsAffected(); rows <= 0 || err != nil {
item.err = errors.New("Update status failed.")
}
}
if item.err != nil {
errItems <- item
}
}
func printResult(item *item) {
defer wg.Done()
fmt.Println(item.toString())
}
</code></pre>
<p>I use a <code>select</code> statement to implement event so that when <code>errItems</code> or <code>ch</code> channels receive, save or print items. I also surrounded <code>select</code> statement with goroutine to prevent blocking.</p>
| [] | [
{
"body": "<h2>Full code</h2>\n\n<pre class=\"lang-golang prettyprint-override\"><code>import (...)\n</code></pre>\n\n<p>Please include your full code next time. This should instead be:</p>\n\n<pre><code>import (\n \"database/sql\"\n \"errors\"\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"net/http\"\n \"os\"\n \"path/filepath\"\n \"sync\"\n \"time\"\n)\n</code></pre>\n\n<p>You also have <code>item.toString()</code>, but this is nowhere defined. I changed it to:</p>\n\n<pre><code>fmt.Println(item)\n</code></pre>\n\n<h2>Scope</h2>\n\n<p><code>connectionString</code> doesn't need to be in the global scope, whether it's <code>const</code> or not. The same could be argued about <code>wg</code>, <code>ch</code>, and <code>errItems</code> -- but moving those to a lower scope would involve adding more function arguments, which is a choice you can make.</p>\n\n<p>In terms of security, I recommend against hard-coding the connection string in the source code. Instead, as one of many options, you can have the connection credentials as a separate file that you read.</p>\n\n<h2>Simplify query</h2>\n\n<p>You use named arguments in your query. But here, the query is so short that it's clear from the context. You can split the query across multiple lines to make it easier to read. You also have some keywords in all uppercase and some in all lowercase.</p>\n\n<pre><code>q := `\nSELECT [ImageID],\n [AccommodationlID],\n [Link],\n [FileName]\nFROM [dbo]. [AccomodationImage]\nWHERE AccommodationlID BETWEEN ? AND ?\n AND FileName NOT LIKE '%NoHotel.png%'`\n\nrows, err := db.Query(q, from, to)\n</code></pre>\n\n<p>(Notice that you also have a misspelling in <code>AccomodationImage</code>.)</p>\n\n<p>This kind of formatting for query strings is also how the Go documentation does it.</p>\n\n<h2>Vertical spacing</h2>\n\n<p>All of the code is compressed together and has no room to breathe. I recommend adding the occasional empty lines, such as between <code>if</code>-statements, <code>for</code> loops, goroutines, etc.</p>\n\n<h2>Validate <code>os.Args</code></h2>\n\n<p>Your code assumes the program will always have three arguments. While this makes sense if only you plan to use it, it's generally not good practice.</p>\n\n<p>Without bounds checking, you will get a runtime panic \"index out of range\" -- no a particularly useful message for those running the program.</p>\n\n<pre><code>if len(os.Args) < 4 {\n log.Fatal(\"missing arguments\")\n}\n</code></pre>\n\n<p>You can also use <a href=\"https://golang.org/ref/spec#Short_variable_declarations\" rel=\"nofollow noreferrer\">short variable declaration</a> when declaring <code>basePath</code>, <code>from,</code> and <code>to</code>.</p>\n\n<pre><code>basePath := os.Args[1]\nfrom, to := os.Args[2], os.Args[3]\n</code></pre>\n\n<h2>Default values</h2>\n\n<pre><code>var item = item{}\n</code></pre>\n\n<p>This is redundant. You should be able to simply use <code>var item</code> -- please correct my if I'm wrong here and <code>Rows.Scan()</code> produces an error if <code>item</code> is <code>nil</code>. Since we do not need to initialize <code>item</code>, we can combine our declarations. Notice I rename the variable <code>item</code> to avoid confusion with the type <code>item</code>.</p>\n\n<pre><code>var (\n i item\n accID string\n name string\n)\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>Here's the code I ended up with:</p>\n\n<pre><code>package main\n\nimport (\n \"database/sql\"\n \"errors\"\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"net/http\"\n \"os\"\n \"path/filepath\"\n \"sync\"\n \"time\"\n)\n\ntype item struct {\n id int\n url string\n path string\n content []byte\n err error\n}\n\nvar wg sync.WaitGroup\nvar ch = make(chan *item) // For success items\nvar errItems = make(chan *item) // For error items\n\nfunc main() {\n const connectionString = \"connectionString\"\n\n if len(os.Args) < 4 {\n log.Fatal(\"missing arguments\")\n }\n\n start := time.Now()\n\n basePath := os.Args[1]\n from, to := os.Args[2], os.Args[3]\n\n db, err := sql.Open(\"sqlserver\", connectionString)\n\n if err != nil {\n log.Fatal(err.Error())\n }\n\n q := `\nSELECT [ImageID],\n [AccommodationlID],\n [Link],\n [FileName]\nFROM [dbo]. [AccomodationImage]\nWHERE AccommodationlID BETWEEN ? AND ?\n AND FileName NOT LIKE '%NoHotel.png%'`\n\n rows, err := db.Query(q, from, to)\n\n if err != nil {\n log.Fatal(err.Error())\n }\n\n defer db.Close()\n\n for rows.Next() {\n var (\n i item\n accID string\n name string\n )\n\n _ = rows.Scan(&i.id, &accID, &i.url, &name)\n\n i.path = fmt.Sprintf(\"%s\\\\%s\\\\%s\", basePath, accID, name)\n\n wg.Add(1)\n\n go downloadFile(&i)\n\n go func() {\n select {\n case done := <-ch:\n wg.Add(1)\n go saveAndUpdateFile(db, done)\n case errorItem := <-errItems:\n wg.Add(1)\n go printResult(errorItem)\n }\n }()\n }\n\n wg.Wait()\n\n fmt.Printf(\"%.2fs elapsed\\n\", time.Since(start).Seconds())\n}\n\nfunc downloadFile(i *item) {\n defer wg.Done()\n\n resp, err := http.Get(i.url)\n\n if err != nil {\n i.content, i.err = nil, err\n } else if resp.StatusCode != http.StatusOK {\n i.content, i.err = nil, errors.New(resp.Status)\n } else {\n i.content, i.err = ioutil.ReadAll(resp.Body)\n }\n\n if i.err != nil {\n errItems <- i\n } else {\n ch <- i\n }\n}\n\nfunc saveAndUpdateFile(db *sql.DB, i *item) {\n defer wg.Done()\n\n if i.content == nil {\n i.err = errors.New(\"Content is empty.\")\n } else {\n dir := filepath.Dir(i.path)\n err := os.MkdirAll(dir, os.ModePerm)\n\n if err != nil {\n i.err = err\n } else {\n i.err = ioutil.WriteFile(i.path, i.content, 0644)\n }\n }\n\n q := `\nUPDATE [dbo].[AccomodationImage]\nSET IsRead = 1\nWHERE ImageID = ?`\n\n if i.err == nil {\n result, err := db.Exec(q, i.id)\n\n if rows, _ := result.RowsAffected(); rows <= 0 || err != nil {\n i.err = errors.New(\"Update status failed.\")\n }\n }\n\n if i.err != nil {\n errItems <- i\n }\n}\n\nfunc printResult(i *item) {\n defer wg.Done()\n\n fmt.Println(i)\n}\n</code></pre>\n\n<p>Unfortunately I cannot test this code and suggest algorithmic or more in-depth changes.</p>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T12:55:35.927",
"Id": "416821",
"Score": "0",
"body": "\"Double-spacing\" code so that it can \"breathe\" severely limits readablity. Readability is the paramount concern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:03:18.237",
"Id": "416823",
"Score": "0",
"body": "We don't need the full code for imports. Simply run the `goimports` command."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:40:30.017",
"Id": "416835",
"Score": "0",
"body": "@peterSO And `goimports` is what I ran in this case. It is still invalid Go code nonetheless. In my opinion adding spacing improves readability, but this change is of little consequence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T20:12:05.153",
"Id": "416936",
"Score": "1",
"body": "Thank you very much @esote. your tips are very helpful. i didn't write `imports` because of summarization. generally my emphasis is on concurrent approach and implementing `goroutines` and `select` statement in `for` loop."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T20:09:41.980",
"Id": "215449",
"ParentId": "215433",
"Score": "3"
}
},
{
"body": "<p>A couple of generic good practices are </p>\n\n<ul>\n<li>Try to avoid using global variables(You can pass wg, ch & errItems as arguments to function)</li>\n<li>Single Responsibility function(A function should do only once task. Makes it easy to test.)</li>\n<li>As far as possible pass dependencies as variables or using dependency injection etc.</li>\n</ul>\n\n<p>Specific to this snippet you can:</p>\n\n<ul>\n<li><p>Pass connectionString as either flag variables or args. Usually secrets like (db user, password) etc should not be hardcoded. It also makes it easier to run in multiple environments like test, production etc.</p></li>\n<li><p>Try to break the main function into smaller functions. (like fetchRows, ProcessRows etc) Will make it testing easier and reusable.</p></li>\n<li><p>saveAndUpdateFile can be made more generic. You shouldn't pass *sql.DB instead try passing a io.Reader object or just the data that needs to be written to the file.</p></li>\n<li><p>Add fetchDBAccomodationFunction and updateDBAccomodation function and pass necessary information as arguments to the functions.</p></li>\n<li><p>Check if rows.Next() keeps a connection open to DB. If yes you should first read all the rows, close the connection and then make http calls to download files. It is better not to keep db connections open for a long time. </p></li>\n<li>I'm not sure if you need two separate channels for done & errorItem. Since you are passing error within item you have one channel and based on error make a decision on how to proceed. </li>\n</ul>\n\n<pre><code>\n select {\n case item := <-ch:\n wg.Add(1)\n if item.err != nil {\n go printResult(errorItem)\n }else{\n go saveAndUpdateFile(db, done) \n }\n }\n\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T17:18:45.447",
"Id": "215855",
"ParentId": "215433",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T16:47:12.990",
"Id": "215433",
"Score": "3",
"Tags": [
"beginner",
"sql",
"go",
"concurrency",
"http"
],
"Title": "Download and save bulk URL concurrently"
} | 215433 |
<p>This is my first Array in VBA for Excel, but I need some help to optimize the code and try to reduce the number of <code>If</code> statements.</p>
<p>The long and short of the code is that it checks to see if there is a Customer name in Column B and checks that against Column A; if there is no value in Column A then an input box opens to prompt the user to add the CIF number to the specific named range.</p>
<p>Cells B2 through B9 will always have a value, but not every cell B2 through B9 will be used. Cells A2 through A9 will not always have a value.</p>
<p>Below is the Code:</p>
<pre><code>Sub CheckCIF()
Dim fileArray
Dim finalRow As Long
Dim targetCol As Long
With Sheets("Loan Data")
finalRow = .Range("B" & Rows.Count).End(xlUp).Row
targetCol = .Range("A1").EntireRow.Find("CIF #").Column
fileArray = Array(.Range("B2:B" & finalRow), _
.Range(.Cells(2, targetCol), .Cells(finalRow, targetCol)))
End With
'fileArray(1)(1) Number in first parenthesis is the column and the number in the second parenthesis is the row
If fileArray(1)(1) = vbNullString And fileArray(0)(1) <> vbNullString Then
With Sheets("Loan Data")
.Range("CIF_1") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(1))
End With
End If
If fileArray(1)(2) = vbNullString And fileArray(0)(2) <> vbNullString Then
With Sheets("Loan Data")
.Range("CIF_2") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(2))
End With
End If
If fileArray(1)(3) = vbNullString And fileArray(0)(3) <> vbNullString Then
With Sheets("Loan Data")
.Range("CIF_3") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(3))
End With
End If
If fileArray(1)(4) = vbNullString And fileArray(0)(4) <> vbNullString Then
With Sheets("Loan Data")
.Range("CIF_4") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(4))
End With
End If
If fileArray(1)(5) = vbNullString And fileArray(0)(5) <> vbNullString Then
With Sheets("Loan Data")
.Range("CIF_5") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(5))
End With
End If
If fileArray(1)(6) = vbNullString And fileArray(0)(6) <> vbNullString Then
With Sheets("Loan Data")
.Range("CIF_6") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(6))
End With
End If
If fileArray(1)(7) = vbNullString And fileArray(0)(7) <> vbNullString Then
With Sheets("Loan Data")
.Range("CIF_7") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(7))
End With
End If
If fileArray(1)(8) = vbNullString And fileArray(0)(8) <> vbNullString Then
With Sheets("Loan Data")
.Range("CIF_8") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(8))
End With
End If
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:42:29.677",
"Id": "416686",
"Score": "0",
"body": "Does this code work as expected? Column A appears to be excluded from the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:46:53.653",
"Id": "416687",
"Score": "0",
"body": "Yes the code works as expected. I reference Column A in this line `targetCol = .Range(\"A1\").EntireRow.Find(\"CIF #\").Column` and then in the `fileArray(1)(1)` where the 1 in the first () is column A."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:49:20.370",
"Id": "416688",
"Score": "0",
"body": "But doesn't fileArray start from B?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:51:02.733",
"Id": "416690",
"Score": "0",
"body": "Yes. I know its backwards, but it is my first Array ever and I get the expected result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:56:39.143",
"Id": "416695",
"Score": "0",
"body": "I may be misunderstanding. Does the following do something similar? https://pastebin.com/Hi39squf"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:56:40.297",
"Id": "416696",
"Score": "0",
"body": "I get a subscript out of range on `If fileArray(rowCounter, 2) = vbNullString And fileArray(rowCounter, 1) <> vbNullString Then`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:58:58.463",
"Id": "416698",
"Score": "0",
"body": "Never mind :-( I think you can use the same loop idea though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T19:00:45.977",
"Id": "416699",
"Score": "1",
"body": "I will play around with it and see what I come up with. Thanks for looking at this for me."
}
] | [
{
"body": "<p>The <code>fileArray</code> variable can be replaced with 2 variables. When looking at fileArray in the locals window, from the IDE menu at the top View>Locals Window, you can see that it's it a Variant/Variant(0 to 1). Expanding that by clicking on the + icon to the left of the variable name it it contains two sub arrays. fileArray(0) and fileArray(1) are both of type Variant/Object/Range. These are distinct areas that should be named respectively. <code>customerArea</code> for those in column B and <code>cifArea</code> for those in the same column as <code>targetCol</code> let you refer to these ranges directly.</p>\n\n<p>Because these variables house information stored vertically, that is X rows tall by 1 column wide, you can reference the rows by <code>customerArea(checkRow).Value2</code>. Doing this allows you to write self documenting code. Rather than </p>\n\n<pre><code>If fileArray(1)(1) = vbNullString And fileArray(0)(1) <> vbNullString Then\n</code></pre>\n\n<p>You have </p>\n\n<pre><code>If customerArea(checkRow).Value2 = vbNullString And cifArea(checkRow).Value2 <> vbNullString Then\n</code></pre>\n\n<p>I'm torn between how to go about checking each of the rows. Mulling it over I decided on extracting the check into a Sub. I added a guard clause, <code>endRow > customerArea.Rows.Count Or endRow > cifArea.Rows.Count</code>, that raises an error if the end row exceeds the number of rows in each area that's checked. You <strong>could</strong> also add a guard clauses to ensure that <code>startRow >= 1</code>, or ensure that <code>customerArea.Rows.Count = cifArea.Rows.Count</code> or any others you deem appropriate, but that I'll leave for you.</p>\n\n<p>Instead of checking each row explicitly I condensed that with a <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/fornext-statement\" rel=\"nofollow noreferrer\">For...Next statement</a> and used a descriptive variable <code>checkRow</code> to let you know which row you're checking.</p>\n\n<pre><code>Private Sub CheckForEmptyCellsIn(ByVal customerArea As Range, ByVal cifArea As Range, ByVal startRow As Long, ByVal endRow As Long)\n Const InputMessage As String = \"Please enter the CIF Number for \"\n\n Const InvalidArgument As Long = 5\n If endRow > customerArea.Rows.Count Or endRow > cifArea.Rows.Count Then\n Err.Raise InvalidArgument, \"CheckForEmptyCells Sub\", \"endRow argument exceeded number of rows in\"\n End If\n\n Dim checkRow As Long\n For checkRow = startRow To endRow\n If customerArea(checkRow).Value2 = vbNullString And cifArea(checkRow).Value2 <> vbNullString Then\n customerArea.Parent.Range(\"CIF_\" & checkRow).Value2 = InputBox(InputMessage & vbCrLf & cifArea(1).Value2)\n End If\n Next\nEnd Sub\n</code></pre>\n\n<p>This refactoring leaves you with </p>\n\n<pre><code>Public Sub CodeReview()\n Dim loanData As Worksheet\n Set loanData = Worksheets(\"Loan Data\")\n Dim finalRow As Long\n finalRow = loanData.Range(\"B\" & Rows.Count).End(xlUp).Row\n Dim targetCol As Long\n targetCol = loanData.Range(\"A1\").EntireRow.Find(\"CIF #\").Column\n\n CheckForEmptyCellsIn loanData.Range(\"B2:B\" & finalRow), _\n loanData.Range(loanData.Cells(2, targetCol), loanData.Cells(finalRow, targetCol)), _\n 1, 8\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T13:35:42.013",
"Id": "417299",
"Score": "0",
"body": "Thank you for this. I did make a change so it would reference the Customer Name and not a specific row. Changed `If customerArea(checkRow).Value2 = vbNullString And cifArea(checkRow).Value2 <> vbNullString Then\n customerArea.Parent.Range(\"CIF_\" & checkRow).Value2 = InputBox(InputMessage & vbCrLf & cifArea(1).Value2)\n End If` to this `If customerArea(checkRow).Value <> vbNullString And cifArea(checkRow).Value = vbNullString Then\n cifArea.Parent.Range(\"CIF_\" & checkRow).Value = InputBox(InputMessage & vbCrLf & customerArea(checkRow).Value)\n End If`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T04:28:53.437",
"Id": "215645",
"ParentId": "215436",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215645",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T17:13:53.283",
"Id": "215436",
"Score": "3",
"Tags": [
"array",
"vba",
"excel"
],
"Title": "Array that stores values from two ranges and compares if one cell is blank"
} | 215436 |
<p>I am automating a scenario of flight booking on Cleartrip.com(<a href="https://www.cleartrip.com/flights" rel="nofollow noreferrer">https://www.cleartrip.com/flights</a>) in which I have to enter depart date, 5 days from today and return date, 6 days from today. I have written below code.</p>
<pre><code>Date dt = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.add(Calendar.DATE, 5);
dt = calendar.getTime();
String departdate = new SimpleDateFormat("dd/mm/yyyy").format(dt);
//enter Journy date in the field
WebElement depart = driver.findElement(By.id("DepartDate"));
depart.sendKeys(departdate);
Date dt1 = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt1);
calendar.add(Calendar.DATE, 6);
dt1 = calendar.getTime();
String returndate = new SimpleDateFormat("dd/mm/yyyy").format(dt1);
//enter returndate in the field
WebElement return= driver.findElement(By.id("ReturnDate"));
return.sendKeys(returndate);
</code></pre>
| [] | [
{
"body": "<p>You don't need the Date type. You can do it all with a Calendar instance and a DateFormat instance:</p>\n\n<pre><code> DateFormat dateFormat = new SimpleDateFormat(\"dd/mm/yyyy\");\n Calendar now = Calendar.getInstance(); // gets current date\n now.add(Calendar.DATE, 5); // add five days\n String firstDate = dateFormat.format(now.getTime());\n ...\n now.add(Calendar.DATE, 1); // add one more day\n String secondDate = dateFormat.format(now.getTime());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T20:16:12.540",
"Id": "215450",
"ParentId": "215437",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215450",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T17:32:37.353",
"Id": "215437",
"Score": "1",
"Tags": [
"java",
"datetime",
"selenium"
],
"Title": "Select depart date, 5 days from today and return date, 6 days from today in Selenium"
} | 215437 |
<blockquote>
<p><a href="https://www.hackerearth.com/problem/algorithm/remains/" rel="nofollow noreferrer"><strong>Remains</strong></a></p>
<p>You've recently stumbled upon the remains of a ruined ancient city. Luckily, you've studied enough ancient architecture to know how the buildings were laid out.</p>
<p>The city had <span class="math-container">\$n\$</span> buildings in a row. Unfortunately, all but the first two buildings have deteriorated. All you can see in the city are the heights of the first two buildings. The height of the first building is <span class="math-container">\$x\$</span>, and the height of the second building is <span class="math-container">\$y\$</span>.</p>
<p>Your studies show ancient traditions dictate for any three consecutive buildings, the heights of the two smaller buildings sum up to the height of the largest building within that group of three. This property holds for all consecutive triples of buildings in the city. Of course, all building heights were nonnegative, and it is possible to have a building that has height zero.</p>
<p>You would like to compute the sum of heights of all the buildings in the row before they were ruined. You note there can be multiple possible answers, so you would like to compute the minimum possible sum of heights that is consistent with the information given. It can be proven under given constraints that the answer will fit within a 64-bit integer.</p>
<p><strong>Input Format</strong></p>
<p>The first line of the input will contain an integer <span class="math-container">\$T\$</span>, denoting the number of test cases.</p>
<p>Each test case will be on a single line that contains 3 integers <span class="math-container">\$x, y, n\$</span>.</p>
<p><strong>Output Format</strong></p>
<p>Print a single line per test case, the minimum sum of heights of all buildings consistent with the given information. </p>
<p><strong>Constraints</strong></p>
<p>For all files<br>
<span class="math-container">\$1 ≤ T ≤ 10\,000\$</span><br>
<span class="math-container">\$0 ≤ x, y\$</span><br>
<span class="math-container">\$2 ≤ n\$</span> </p>
<p>File 1 -- 61 pts:<br>
<span class="math-container">\$x, y, n ≤ 10\$</span> </p>
<p>File 2 -- 26 pts:<br>
<span class="math-container">\$x, y, n ≤ 100\$</span> </p>
<p>File 3 -- 13 pts:<br>
<span class="math-container">\$x, y, n ≤ 1\,000\,000\,000\$</span> </p>
<p><strong>Sample Input</strong></p>
<pre><code>3
10 7 5
50 100 50
1000000000 999999999 1000000000
</code></pre>
<p><strong>Sample Output</strong></p>
<pre><code>25
1750
444444445222222222
</code></pre>
<p><strong>Explanation</strong></p>
<p>In the first sample case, the city had 5 buildings, and the first building has height 10 and the second building has height 7. We know the third building either had height 17 or 3. One possible sequence of building heights that minimizes the sum of heights is {10, 7, 3, 4, 1}. The sum of all heights is 10+7+3+4+1 = 25.</p>
<p>In the second sample case, note that it's possible for some buildings to have height zero.</p>
<p><strong>Environment</strong></p>
<p>Time Limit: 5.0 sec(s) for each input file.<br>
Memory Limit: 256 MB<br>
Source Limit: 1024 KB</p>
</blockquote>
<p><strong>TLDR;</strong></p>
<p>Heights of first two buildings and the total number of buildings are given. For any three consecutive buildings, the heights of the two smaller buildings sum up to the height of the largest building within that group of three. This property holds for all consecutive triples of buildings in the city.</p>
<p><strong>Buildings of size 0 are allowed</strong>.</p>
<p>Compute the minimum sum of heights of all the buildings.</p>
<p><em>Runtime Per Input = 5 sec</em></p>
<p><strong>My Code:</strong></p>
<pre><code>#include <iostream>
#include <cmath>
#include <vector>
#include <cstdio>
using namespace std;
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
long long int t; // t = number of test cases
cin >> t;
long long int x, y, n;
//x, y = Height of first & second building. n = number of buildings
long long int sum; //sum of the height of buildings
int arr[3]; //Not required as pointed out by Juno
long long int z; //Temporary variable to store the height of next building
for (long long int foo = 0; foo < t; foo++)
{
cin >> x >> y >> n; //Takes the input
sum = x + y; //Adds to sum the height of the first two buildings
for (long long int i = 2; i < n; i++)
{
z = abs(x - y);
sum += z;
x = y;
y = z;
}
cout << sum << endl;
}
}
</code></pre>
<blockquote>
<p>Input 1: x, y, n ≤ 10</p>
<p>Input 2: 26 pts: x, y, n ≤ 100</p>
<p>Input 3: 13 pts: x, y, n ≤ 1,000,000,000</p>
</blockquote>
<p>My code works for the first two inputs but goes on time limit exceeded on the third input.
<a href="https://i.stack.imgur.com/WYzjw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WYzjw.png" alt="enter image description here"></a></p>
<blockquote>
<p>Can anyone help in thinking a better algorithm for solving this question?</p>
</blockquote>
<p><strong>During the last input, the program's execution was not complete.</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T19:31:52.030",
"Id": "416719",
"Score": "2",
"body": "Honestly, I think the challenge is simply poorly worded. The following is deceiving: \"You would like to compute the sum of heights of all the buildings\" since they really want to know \"the minimum sum of heights of all buildings consistent with the given information\". I'm fairly sure it can be done with less iteration by ignoring the first line and focussing on what they actually want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T04:30:40.393",
"Id": "416767",
"Score": "0",
"body": "@Vogel612 Can you please confirm that the question that I posted is relevant to this site so that I can post more such questions. Also thanks for the link."
}
] | [
{
"body": "<p>This is not going to be the answer you want, but it might help you figure it out on your own. There are (at least) two problems here. The first is in the challenge description, the other one is in your code being a mess.</p>\n\n<ol>\n<li><p>Honestly, I think the challenge is simply poorly worded. The following is deceiving: \"You would like to compute the sum of heights of all the buildings\" since they really want to know \"the minimum sum of heights of all buildings consistent with the given information\". I'm fairly sure it can be done with less iteration by ignoring the first line and focussing on what they actually want.</p></li>\n<li><p>Your code. There's a lot of things in there that don't have to be in there and the naming could be much better. I'm not a star at it myself, but I've taken a shot at cleaning it up.</p></li>\n</ol>\n\n<p>A more readable version:</p>\n\n<pre><code>#include <iostream>\n#include <cmath>\n\nint main(void)\n{\n long long int amount_cases;\n long long int first, second, n;\n long long int sum;\n long long int carry;\n\n std::cin >> amount_cases;\n\n for (long long int i = 0; i < amount_cases; i++)\n {\n std::cin >> first >> second >> n;\n sum = first + second;\n for (long long int j = 2; j < n; j++)\n {\n carry = std::abs(first - second);\n sum += carry;\n first = second;\n second = carry;\n }\n std::cout << sum << std::endl;\n }\n}\n</code></pre>\n\n<p>Your timeout problem is in this part:</p>\n\n<pre><code>for (long long int j = 2; j < n; j++)\n{\n carry = std::abs(first - second);\n sum += carry;\n first = second;\n second = carry;\n}\n</code></pre>\n\n<p>That's not the most optimum method for this problem and the only part of the program you'll have to improve to make it happen fast enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T20:04:23.017",
"Id": "416726",
"Score": "1",
"body": "Two suggestions: first, you don't need to write `int main(void)` (remove void). Second, it's quite C-like to declare variables at the beginning of scope. With C++, I'd stick to declaring them as late as possible (and you can make a good bunch of them const here as well)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T20:07:31.420",
"Id": "416727",
"Score": "0",
"body": "@Juho You are absolutely right. Feel free to write an answer based on mine, improving it even further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T21:50:36.260",
"Id": "416742",
"Score": "1",
"body": "If you're going to use `std::cin >>` like that without checking, make it throw exceptions instead: start with `cin::exceptions(std::ios_base::fail | std::ios_base::eof);` before any reading."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T22:13:17.647",
"Id": "416746",
"Score": "0",
"body": "@TobySpeight Usually, absolutely. Would you still do that for guaranteed to be sanitized input, which is the case here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T08:39:35.333",
"Id": "416783",
"Score": "1",
"body": "@Mast, I probably would, given it's only one line at the beginning - it helps us diagnose any misunderstanding of, or change to, the spec. BTW, giving good names to the variables was my first thought, and the largest single improvement to be made!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T19:50:09.173",
"Id": "215447",
"ParentId": "215443",
"Score": "4"
}
},
{
"body": "<p>There are a few observations we can make about the nature of the problem.</p>\n\n<p>The first and most obvious observation is that the building heights will keep decreasing until the first building hits 0. As soon as that happens, the building heights will follow the form <span class=\"math-container\">\\$h, 0, h, h, 0, \\ldots \\$</span>, repeating the last non-zero height twice before adding in a zero again.<br>\nNote that the same is true for equal building heights (though that much should've been obvious).</p>\n\n<p>The next observation is the following: When the first building is smaller than the second, the output of <code>cumulative_heights(a, b, n)</code> is <code>a + cumulative_heights(b, b - a, n - 1)</code></p>\n\n<p>Now that we handled \"special cases\", we should take a look at the properties of the \"general case\". In the following, <span class=\"math-container\">\\$a > b\\$</span></p>\n\n<p>Now let's examine the behaviour of four simple sequences:</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\n(1) & 20, 5, 15, 10, 5, 5, 0, \\ldots \\\\\n(2) & 20, 9, 11, 2, 9, 7, 2, 5, 3, 2, 1, 1, 0, \\ldots\\\\\n(3) & 20, 4, 16, 12, 4, 8, 4, 4, 0, \\ldots\\\\\n(4) & 20, 6, 14, 8, 6, 2, 4, 2, 2, 0, \\ldots\n\\end{align}\n$$</span></p>\n\n<p>Note how in all of these sequences the smaller building height keeps repeating.</p>\n\n<p>I've chosen these for certain additional properties they exhibit. It's important to understand how the divisibility of the building heights comes into play here. Using <span class=\"math-container\">\\$(\\lfloor \\frac{a}{b} \\rfloor, a \\mod b)\\$</span> to classify these sequences gives us an insight:</p>\n\n<p>The sequences where <span class=\"math-container\">\\$a \\mod b = 0\\$</span> very quickly result in a repeating pattern. Because the repeated subtraction returns 0 at some point, these sequences (namely (1) and (3)) \"end\" the descent of the building heights.</p>\n\n<p>The other two sequences are somewhat more interesting.<br>\nWhen we look at them somewhat differently we get the following picture:</p>\n\n<p><span class=\"math-container\">$$\n20, 9, 11, 2, 9\\\\\n2, 9 \\\\\n9, 7, 2, 5, 3, 2, 1\\\\\n2, 1, 1, 0 \\\\\n... \\\\\n20, 6, 14, 8, 6, 2\\\\\n6, 2, 4, 2, 2, 0\n$$</span></p>\n\n<p>Now when you see this I <em>hope</em> you notice that there's multiple subsequences here. I repeated the \"start\" of each subsequence to make it easier to notice.</p>\n\n<p>The deciding factor about what exactly happens when the first subsequence ends is whether <span class=\"math-container\">\\$\\lfloor \\frac{a}{b} \\rfloor \\$</span> is even or not. If it is, that's equivalent to the first case (sequence (2)). If it isn't we get the somewhat cleaner and easier to reason about result of sequence (4).</p>\n\n<p>Note how upon reaching <span class=\"math-container\">\\$a \\mod b\\$</span> the even case \"adds another <span class=\"math-container\">\\$b\\$</span>\", which will always be larger than <span class=\"math-container\">\\$a \\mod b\\$</span>. The sequence then continues with <span class=\"math-container\">\\$(b, b - (a \\mod b))\\$</span>. </p>\n\n<p>The odd case however just \"starts sooner\" and follows a sequence based on <span class=\"math-container\">\\$(b, a \\mod b)\\$</span>.</p>\n\n<p>The only remaining puzzle piece to turn this into a working analytical (and possibly recursive) solution is to understand how many steps elapse before the \"next subsequence\" begins and to encapsulate this behaviour into a separate function that takes the two starting heights and the number of buildings as arguments.</p>\n\n<p>I leave the hammering out of that detail to you :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T05:29:10.753",
"Id": "416979",
"Score": "0",
"body": "Thanks for the answer. I was thinking that since there is always a 3 integer sequence repeating, I can start out with 6 variables instead. Also I can check for the condition if the first three variable equals to the last three then add their sum (n-current iteration) number of times and exit the loop. I think this should improve the run time drastically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T05:34:45.590",
"Id": "416982",
"Score": "0",
"body": "I would not be able to code for all the special cases because it was just a 30 min contest"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T19:55:29.843",
"Id": "215526",
"ParentId": "215443",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215526",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T18:44:56.753",
"Id": "215443",
"Score": "5",
"Tags": [
"c++",
"time-limit-exceeded",
"c++14"
],
"Title": "Code to find the sums of building heights"
} | 215443 |
<p>I've written the below code to validate user input but I feel it's quite excessive for what seems to be a simple operation. I want to only accept non-negative integers or doubles as an input. This block of code is required three times in my program so I will need to put it into a method or something but in the mean time is there a simpler way to validate user input?</p>
<pre><code> Scanner input = new Scanner(System.in);
boolean validWidth = false;
double width = 0.0;;
do // do while runs until the input is validated
{
System.out.print("Enter width: ");
if (input.hasNextInt()) // we accept an int
{
width = input.nextInt();
if (width > 0) // we accept a non-negative
{
validWidth = true;
}
else // refuse a negative
{
System.out.println("Input error. Try again.");
validWidth = false;
}
}
else if (input.hasNextDouble())// accept a double
{
width = input.nextDouble();
if (width > 0) // we accept a non-negative
{
validWidth = true;
}
else // and refuse a negative
{
System.out.println("Input error. Try again.");
validWidth = false;
}
}
else
{
System.out.println("Input error. Try again.");
validInput = false;
input.next();
}
} while (!(validWidth));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T20:54:38.420",
"Id": "416735",
"Score": "0",
"body": "Welcome to Code Review. Unfortunately, your code is missing some important context, for example `input`'s type, how it's initialized, and the declarations of the other variables. Keep in mind that It's fine to drop a lot of code here, as long as you properly explain it beforehand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T20:59:58.693",
"Id": "416737",
"Score": "0",
"body": "Sorry, I have added those now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T21:01:28.360",
"Id": "416738",
"Score": "0",
"body": "Perfect, thanks. I hope that one of the Java devs will review your code soon."
}
] | [
{
"body": "<p>You are distinguishing between <code>hasNextInt()</code> and <code>hasNextDouble()</code> in the input stream, but treating them identically afterwards. <code>hasNextDouble()</code> will return <code>true</code> if the next token is an integer, because integers can be successfully parsed as a double too.</p>\n\n<p>So your loop could be simplified into:</p>\n\n<pre><code>double width = 0.0;\n\nfor(;;) {\n System.out.print(\"Enter width: \");\n if (input.hasNextDouble()) {\n width = input.nextDouble();\n if (width > 0)\n break;\n }\n System.out.println(\"Input error. Try again.\");\n input.nextLine();\n}\n</code></pre>\n\n<p>A few notes:</p>\n\n<ul>\n<li><p>The unnecessary <code>validWidth</code> variable has been removed. A <code>break</code> statement exits the infinite <code>for(;;)</code> loop, skipping over the \"cleanup, try again\" code.</p></li>\n<li><p><code>.nextLine()</code> is used to cleanup after invalid input. This is important, because if the user enters <code>\"one fish two fish red fish blue fish\"</code> instead of say <code>-12</code>, your current approach will print out <code>\"Input error. Try again\"</code> 8 times. Using <code>.nextLine()</code> discards everything up to and including the new line character. Which brings us to zero and negative numbers. If the user enters a valid integer/double, but not a positive one, your code didn't skip any tokens, where as my code (as mentioned above) will skip the remaining input up to and including the new line character. Assuming the next character was a new line (as in the user entered <code>-12</code> and pressed the return key) the following <code>.hasNextDouble()</code> will skip over the new line (and any other blank space) looking for the next token, so the effect is approximately the same.</p></li>\n<li><p><strong>But</strong> my code performs differently if the user enters <code>red 5</code>. You original code will print <code>\"Invalid input. Try again.\"</code>, and then immediately consume the <code>5</code> as valid input, where as my code will discard the remainder of the line, and wait for the user to enter another line.</p></li>\n</ul>\n\n<p>Since you are using the code multiple places, putting it into a method is prudent. Here is one using a <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/function/DoublePredicate.html\" rel=\"nofollow noreferrer\"><code>DoublePredicate</code></a> functional interface in order to validate the input according to the caller's requirements:</p>\n\n<pre><code>double getDouble(Scanner input, String prompt, DoublePredicate validate) {\n double value = 0.0;\n\n for(;;) {\n System.out.print(prompt);\n if (input.hasNextDouble()) {\n value = input.nextDouble();\n if (validate.test(value))\n return value;\n }\n System.out.println(\"Input error. Try again.\");\n input.nextLine();\n }\n}\n</code></pre>\n\n<p>Which you could use with a lambda function like:</p>\n\n<pre><code> double width = getDouble(input, \"Enter width: \", x -> x > 0);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T05:25:42.710",
"Id": "416772",
"Score": "0",
"body": "Nice explanation Amazing (-_-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T23:11:21.367",
"Id": "215458",
"ParentId": "215452",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215458",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T20:48:09.663",
"Id": "215452",
"Score": "7",
"Tags": [
"java",
"validation"
],
"Title": "Validating user input"
} | 215452 |
<p>Using feedback from my <a href="https://codereview.stackexchange.com/questions/215117/queue-interview-code-basic-methods-made-from-struct-node/215130">previous implementation</a> I'm writing a very simple Queue of struct Nodes with only these methods get_front(), get_back(), pop_front(), push_back(), and a ostream friend method. I want this to be reviewed as production code and is to be treated as code that could be used in an interview. I'm really curious about the approach I've taken here to keep track of the size, empty status, and back and front pointers. I resolved some of the padding issues in my data structures, not sure if that's over kill or would look good to show my C++ proficiency.</p>
<p>I'd like to know also if my member functions for the Queue have any edge cases I am not catching and any improvements I can make to run time efficiency overall. Anyway I can simplify this code further with c++11 features, shorter variable names or smart pointers would be appreciated.</p>
<p>Lastly if you optionally would like to share the memory/space complexity for my code that would be a huge help! I have noted some examples in the member data of my Node struct.</p>
<pre><code>#include <iostream>
#include <string>
class Queue
{
private:
struct Node
{
int data;
char padding[4];
Node* previous;
Node(int data) : data(data), previous(nullptr) { }
};
int _size{0};
char padding[4];
Node* _back{nullptr};
Node* _front{nullptr};
public:
~Queue() {
while(_front) {
auto n = _front;
_front = _front->previous;
delete n;
}
}
void pop_front() {
--_size;
if (!_back) {
throw std::out_of_range{"cannot get data from empty queue"};
}
else if (_front->previous) {
auto danglingptr = _front;
_front = _front->previous;
delete danglingptr;
}
else {
_front = _back = nullptr;
}
}
void push_back(int data) {
auto n = new Node(data);
++_size;
if (!_back) {
_front = _back = n;
}
else {
_back->previous = n;
_back = _back->previous;
}
}
int get_back() { return _back ? _back->data : 0; }
int get_front() { return _front ? _front->data : 0; }
std::size_t get_size() { return _size; }
bool is_empty() { return _size > 0; }
friend std::ostream& operator<<(std::ostream& os, const Queue& queue) {
int size = queue._size;
if (size == 0) {
os << "Queue is empty";
}
else {
for (int i = 1; i < size*2; i++) { os << "_"; }
os << std::endl;
std::string queue_string = "";
auto current = queue._front;
for(; current; current = current->previous) {
queue_string = std::to_string(current->data) + " " + queue_string;
}
os << queue_string << std::endl;
for (int i = 1; i < size*2; i++) { os << "_"; }
}
return os;
}
};
int main()
{
Queue queue;
queue.push_back(9);
queue.push_back(8);
queue.push_back(7);
queue.push_back(6);
queue.push_back(5);
std::cout << queue << std::endl;
std::cout << "back is " << std::to_string(queue.get_back()) << '\n';
std::cout << "front is " << std::to_string(queue.get_front()) << '\n';
std::cout << "size is " << std::to_string(queue.get_size()) << "\n\n";
queue.pop_front();
queue.pop_front();
queue.pop_front();
std::cout << queue << std::endl;
std::cout << "back is " << std::to_string(queue.get_back()) << '\n';
std::cout << "front is " << std::to_string(queue.get_front()) << '\n';
std::cout << "size is " << std::to_string(queue.get_size()) << "\n\n";
queue.pop_front();
queue.pop_front();
std::cout << queue << std::endl;
std::cout << "back is " << std::to_string(queue.get_back()) << '\n';
std::cout << "front is " << std::to_string(queue.get_front()) << '\n';
std::cout << "size is " << std::to_string(queue.get_size()) << "\n\n";
queue.pop_front();
}
</code></pre>
| [] | [
{
"body": "<p>This is going to be somewhat more conversational on things to do or don't looking at it as if you'd shown this in the course of an interview. Any response with respect to an interview example would always take into account the amount of experience that the candidate is claiming to have. Note, I am also writing this in the way I am looking at the code, noticing superficial things first and then looking closer and closer at the implementation.</p>\n\n<p>My first question would be about the padding, and if you wouldn't be able to answer as to why it is important here or why you added it (saying that there was a warning wouldn't be a sufficient answer), what it does, and what the issues are whether this works under 32 and 64 bit architectures, etc... . If you can't answer these questions it would be a bad sign for me. For interviews don't use features in your code that you can't explain. </p>\n\n<p>I'd definitely ask you why you didn't use <code>std::unique_ptr</code> as this would remove large swaths of the code, it's a feature of c++11 in an interview i'd probably expect to see that. I'd probably also ask whether you thought about making the interface closer to the standard library calls e.g. <code>get_back()</code> vs <code>back()</code> or <code>is_empty()</code> vs <code>empty()</code>.</p>\n\n<p>Note that most of these are actually superficial but they are really easy to pick up on a first look, without even having to think about if the code is correct or not (which would be more work on my side) there are already a ton of things to talk about that might let me exclude you as a candidate. The quicker you can be excluded, the less work for everybody. </p>\n\n<p>So on closer look, you'd get dinged for returning a valid piece of data on failure in <code>get_back()</code> and <code>get_front()</code>. Here you are return 0 if there aren't any items, this is really a big issue. This would start a discussion on error handling in general, what could you have done, what <em>did</em> you do just a few lines above that section. </p>\n\n<p>I see a bug in <code>pop_front()</code> first I'd ask you to look at it and we'd try to find it together. You decrease size before the check if the queue is empty, this would make size incorrect. Looking at the bug also made me notice that you never tested popping from the empty list. Now that I have seen the first bug, i'm looking closer and there is another bug that leaks the first nodes memory if its the last item. If we haven't talked about <code>unique_ptr</code> up to this point, I'd ask now. </p>\n\n<p>Depending on how your responses are we might talk about some general points, i'd comment that you're probably putting out too much text on <code><<</code>, i'd ask if the <code>to_string()</code> in the demo code is really necessary. I'd comment on your style for member variables (pet peeve). Leading underscores are iffy at best with regard to their use, the standard reserves names with leading underscores in combination with capital letters and double underscores, so you're just one keystroke away from code that violates that. I'd also remark that the test code could have used some assertions rather than just output, this would have made things much more like a unit test, and if there is time we might talk about what you know about unit testing. </p>\n\n<p>When I interview, i take any issue I see as an opportunity to talk about what caused it, what might remedy it, why the candidate did this. The answers to these questions may matter more than the actual code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T18:58:01.497",
"Id": "416918",
"Score": "0",
"body": "Thanks for all the feedback Harald. For padding I would say I added this to properly align the bits for my data structures in memory. Without padding there would be wasted space (at large scale this a big issue) in the memory addresses where my logic is contained and performance is improved by this as well. I can not answer if this works on different bit architectures, but would like to understand that more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T19:38:14.060",
"Id": "416932",
"Score": "0",
"body": "You wasted the exact same space as the compiler ... http://coliru.stacked-crooked.com/a/beb5efd219f81262"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T19:48:31.757",
"Id": "416933",
"Score": "1",
"body": "The padding is still wasted space, a solution saving space could have been to use a `long` for the node payload that would have in that case used the same 4 byte that you used for padding. Sometimes the answers here are not a good fit for the person asking the question. You don't necessarily want to tell a somebody trying to crawl that they should be running instead, all in good time. But I realize it can be hard to figure that out on the readers side."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T12:31:18.460",
"Id": "417010",
"Score": "0",
"body": "Using `std::unique_ptr`, adding asserts to make things behave more like unit test, and avoiding topics I'm less familiar with like the memory address padding is what I'll do going forward thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T13:03:16.183",
"Id": "417290",
"Score": "1",
"body": "I thought about the purpose of the `-Wpadded` switch. And I would probably use it to check my code to see where padding occurs and then try to rearrange the struct to reduce the amount of padding e.g if you have `int;int*;int` that would be padded but `int;int;int*` wouldn't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T16:14:29.667",
"Id": "417677",
"Score": "0",
"body": "In the case where there's padding like this `int;int*`, would adding a `char padding[4]` (although I think that still wasting space) or changing `int` to `long` or `double` be a better decision? For an interview or production entry level I still do not have a good sense on how important padding is. At massive scale I know there are space complexity implications, but not sure what other key contributions fixing padding makes to my code. Also I am implementing smart pointers in my next post if you'd like to comment at it. You've left some great feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T18:12:38.683",
"Id": "417689",
"Score": "1",
"body": "Unless you have a specific reason to manually introduce the padding, don't. The compiler is already doing it, you are worrying about this too much.Manually padding might be important in applications where you need to be sure about the binary layout of the data that you are producing. Worry about the bugs in your code rather than a warning given by an optional flag."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T14:46:43.007",
"Id": "215511",
"ParentId": "215453",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215511",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T20:56:55.220",
"Id": "215453",
"Score": "2",
"Tags": [
"c++",
"c++11",
"queue",
"pointers"
],
"Title": "Queue Interview Code basic methods made from struct Node optimized"
} | 215453 |
<p>I am looking to simplify my main() function. The nested if statements contain four lines of the same code, and I'm unsure of how to refactor and simplify it. I was attempting to use booleans, which seemed like a safe bet, but the logic gets skewed in the process.</p>
<pre><code>#include <bits/stdc++.h>
#include <iostream>
#include <string>
int bits(unsigned long d) {
int l;
if (d <= 255) {
l = 8;
}
else if (d > 255 && d <= 65535) {
l = 16;
}
else if (d > 65535 && d <= 4294967295U) {
l = 32;
}
else {
std::cout << "32 bits (4294967295) or smaller." << std::endl;
}
std::cout << "Bits..................... " << l << std::endl;
return l;
}
std::string convertToBinary(unsigned long decimal) {
int l = bits(decimal);
int i, r;
std::string str;
// creates array
for (i = 0; i < l; i++) {
r = decimal % 2;
decimal /= 2;
str += std::to_string(r);
}
// reverses array for binary value
reverse(str.begin(), str.end());
std::cout << "Binary Value............. " << str << std::endl;
return str;
}
int main(void) {
std::string input;
std::cout << "------------ Input -----------" << std::endl;
std::cin >> input;
std::cout << "Input: " << input << std::endl;
std::cout << "Length: " << input.length() << std::endl;
int i, count = 0, j = 0;
int length = input.length();
int ascii;
unsigned long nums;
int numbers[33];
std::string binaries;
std::string chars;
for (i = 0; i < length; i++) {
// if next input is digit
if (isdigit(input[i])) {
numbers[j] = input[i];
// place digit in next decimal
count = (numbers[j] - '0') + count * 10;
// if next input is char
if (i == length - 1) {
if (isdigit(input[length - 1])) {
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;
}
}
// next number
j++;
}
// if next input is char
else {
chars[i] = input[i];
ascii = (int) chars[i];
// if next input is digit
if (count != 0) {
nums = count;
std::cout << "------------ " << nums << " ------------" << std::endl;
binaries += convertToBinary(nums) + ' ';
count = 0;
}
// != end of letters
std::cout << "------------ " << chars[i] << " ------------" << std::endl;
std::cout << "ASCII.................... " << ascii << std::endl;
binaries += convertToBinary(ascii) + ' ';
}
}
std::cout << "\n------- Binary Value of " << input << " -------" << std::endl;
std::cout << binaries << std::endl;
return 0;
}
</code></pre>
<p>The program takes an input, then outputs the corresponding number of bits, binary value, and if necessary, an ASCII value. If the user inputs "c357g98", then the program should get ASCII and binary values of "c", then retrieve the binary value of "357" (rather than "3", "5", then "7" individually), so any adjacent digits will be treated as a single int instead of separate integers. Each time I attempt to refactor, the program loses its ability to store the adjacent digits together as a single int.</p>
<p>In the first attempt at refactoring, I tried this, which takes the <code>count</code> and <code>binary</code> parameters:</p>
<pre><code>void getNumbers(int c, std::string b) {
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;
}
</code></pre>
<p>Since the <code>count</code> is never returned, the input "c357g98" is treated as "c357g35798" and the numbers never reset.</p>
<p>So in my second attempt, I return the <code>count</code> variable as an int:</p>
<pre><code>int getNumbers(int c, std::string b) {
std::cout << "------------ " << c << " ------------" << std::endl;
b += convertToBinary(c) + ' ';
c = 0;
return c;
}
</code></pre>
<p>And replace the four lines of code with a reference to the function as:</p>
<pre><code>count = getNumbers(count, binaries);
</code></pre>
<p>This method converts each value correctly, but does not store the final binary values of the digits, only the characters (since the reference to the string <code>binaries</code> was moved and not returned).</p>
<p>I've also done away with the <code>nums</code> variable entirely.</p>
<p>I'm coming to terms with the idea that my entire program may need heavily refactored in order for the logic to be simplified, but I was hoping to start with the messy <code>main()</code> function for now.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T21:25:33.620",
"Id": "416739",
"Score": "0",
"body": "What have you attempted to do to refactor it? Assuming the four lines you are referring to are the ones beginning with `nums = count;`, why can't you put those four lines in a function that accepts references to `nums` and `count`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T21:46:18.667",
"Id": "416741",
"Score": "0",
"body": "@Null I created a function that takes `count` and `binaries`, then returns the `count`. So the four lines are then replaced with `count = getNumbers(count, binaries);` This method will skip the digits entirely, and when the program is due to print all final binary values at the end, only the characters are converted. In my second attempt, I changed the function to `string getNumbers` and had the `binaries` string be returned instead, and the four lines of code in the nested `if`statements were replaced with `binaries += getNumbers(count, binaries);` This method does not reset the counter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T21:56:55.347",
"Id": "416744",
"Score": "0",
"body": "It's hard to follow that in a comment. Please [edit] your question with the attempted refactor code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T22:13:34.450",
"Id": "416747",
"Score": "0",
"body": "@Null I apologize, I was unaware of the correct protocol for editing posts. I've edited the post now to include my attempts."
}
] | [
{
"body": "<p>The first 3 lines in <code>main</code> can be turned into a function:</p>\n<pre><code>std::string getInput()\n{\n std::string input;\n std::cout << "------------ Input -----------" << std::endl;\n std::cin >> input;\n return input;\n}\n\nint main()\n std::string input = getInput();\n</code></pre>\n<p>There are several portions of <code>main</code> that could become functions.</p>\n<h3>Declare Variable when needed</h3>\n<p>In the function <code>convertToBinary</code> the integer variables <code>i</code> and <code>r</code> are declared at the beginning of the function. They are only needed within the <code>for</code> loop.</p>\n<pre><code> for (int i = 0; i < l; i++) {\n int r = decimal % 2;\n decimal /= 2;\n str += std::to_string(r);\n }\n</code></pre>\n<p>This is also true in the <code>main</code> function for <code>i</code> and other variables.</p>\n<p>The contents of the <code>then</code> clause and the <code>else</code> could both be moved into functions.</p>\n<p>Does the inner <code>if</code> statement <code>(if (i == length - 1))</code> need to be within the <code>for</code> loop or could it be executed after the <code>for</code> loop is done? You might want to think about <a href=\"https://en.wikipedia.org/wiki/Loop_invariant\" rel=\"nofollow noreferrer\">loop invariants</a>.</p>\n<h3>Reduce Complexity When You Can</h3>\n<p>In the function <code>bits</code>, checking from the top down might make reading easier because the top limit isn't needed:</p>\n<pre><code> if (d > 65535) {\n l = 32;\n } else if (d > 255) {\n l = 16;\n } else {\n l = 8;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T23:29:31.000",
"Id": "215461",
"ParentId": "215455",
"Score": "4"
}
},
{
"body": "<p>The use of the term <strong>ASCII</strong> is misleading. What's used here is actually the <strong>execution character coding</strong>, which may or may not be ASCII. C++ is intentionally portable enough to work on systems regardless of the encoding they use for characters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T11:33:53.810",
"Id": "215499",
"ParentId": "215455",
"Score": "4"
}
},
{
"body": "<p>It's not only the main function that you should try to improve upon. Rather, when you build your supporting functions in a nice way, a simplified main function follows naturally.</p>\n\n<p>First, as general comments, your program suffers from a bad separation of logic. Your functions are doing too much: they do processing, print output to the user, and return some value. The same problem is echoed in the main: input parsing is tightly knit together with printing and processing.</p>\n\n<ul>\n<li><p>Don't include <code><bits/stdc++.h></code>, it's not portable. Also, see <a href=\"https://stackoverflow.com/q/31816095/551375\">here for more on why not do it</a>.</p></li>\n<li><p>Your program crashes on multiple inputs due to out-of-indexing issues, so avoid C-arrays like <code>int numbers[33]</code>. Also, avoid magic numbers like 33 which makes the reader go \"Huh, what 33?\".</p></li>\n<li><p>As explained in the other review(s), declare variables as late as possible because you write C++ and not C.</p></li>\n<li><p>Standard functions and data structures will simplify your code massively. We can logically think about the following: read the input, split it into sensible parts, and process each part. That's it!</p></li>\n</ul>\n\n<p>So in full, we could write your program also as follows:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <bitset>\n#include <iterator>\n\nconstexpr unsigned long MAX_BITSIZE = 32;\n\nint bits(unsigned long d)\n{\n if (d > 65535) {\n return 32;\n }\n else if (d > 255) {\n return 16;\n }\n else {\n return 8;\n }\n}\n\n// Return a bit string corresponding to the input.\nstd::string to_binary(unsigned long decimal)\n{\n std::bitset<MAX_BITSIZE> bs(decimal);\n return bs.to_string().substr(MAX_BITSIZE - bits(decimal));\n}\n\n// Split the input string into parts, \n// e.g., \"abc123e6g\" is split into (\"abc\", \"123\", \"e\", \"6\", \"g\").\nstd::vector<std::string> get_parts(const std::string& str)\n{\n std::vector<std::string> parts;\n\n for (auto first = str.cbegin(); first != str.cend(); )\n {\n auto change = std::adjacent_find(first, str.cend(),\n [](char a, char b) { return isdigit(a) != isdigit(b); });\n\n if (change != str.cend())\n {\n ++change;\n }\n\n parts.emplace_back(std::string(first, change));\n\n first = change;\n }\n\n return parts;\n}\n\nint main()\n{\n // Reading input could be done a function.\n // We also omit all checks, and just assume it is valid.\n\n std::string input;\n std::cout << \"------------ Input -----------\\n\";\n std::cin >> input;\n\n std::cout << \"Input: \" << input << \"\\n\";\n std::cout << \"Length: \" << input.length() << \"\\n\";\n\n const auto cont = get_parts(input);\n\n std::vector<std::string> binary;\n\n for (const auto& e : cont)\n {\n // Processing an integer\n if (isdigit(e.front()))\n {\n const std::string b = to_binary(stoi(e));\n\n std::cout << \"------------ \" << e << \" ------------\\n\";\n std::cout << \"Bits..................... \" << bits(stoi(e)) << \"\\n\";\n std::cout << \"Binary value............. \" << to_binary(stoi(e)) << \"\\n\";\n\n binary.push_back(b);\n }\n // Processing individual characters\n else\n {\n for (const auto& ch : e)\n {\n const std::string b = to_binary(ch);\n\n std::cout << \"------------ \" << ch << \" ------------\\n\";\n std::cout << \"ASCII.................... \" << int(ch) << \"\\n\";\n std::cout << \"Bits..................... \" << bits(ch) << \"\\n\";\n std::cout << \"Binary value............. \" << to_binary(ch) << \"\\n\";\n\n binary.push_back(b);\n }\n }\n }\n\n std::cout << \"\\n------- Binary value of \" << input << \" -------\\n\";\n std::copy(binary.cbegin(), binary.cend(), std::ostream_iterator<std::string>(std::cout, \" \"));\n}\n</code></pre>\n\n<p>A few comments about the above program:</p>\n\n<ul>\n<li><p>Luckily, <code>std::bitset</code> has methods for printing a binary string that we can use to massively simplify your \"to-binary\" conversion function. Notice that this function does <em>no</em> printing; it's not its job. Remember: <em>one function, one responsibility</em>. Whoever uses this function decides when, how, and what to print (if anything).</p></li>\n<li><p>The function <code>get_parts</code> takes care of all that messy processing of your main function (which is buggy - but don't feel bad, it's hard to get it right when you go so low level). The magic is taken care of <code>std::adjacent_find</code> which is used by a suitable lambda function that checks if the two adjacent indices contain characters of \"different type\" (i.e., a digit and a non-digit). If we wanted to, we could also modify this slightly to further split \"abc\" to \"a\", \"b\", and \"c\".</p></li>\n<li><p>The main function is quite pretty now (and very readable compared to your original): just get the parts and process each. Printing could be further divided into more functions.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:32:41.790",
"Id": "215567",
"ParentId": "215455",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215567",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T21:17:59.603",
"Id": "215455",
"Score": "6",
"Tags": [
"c++",
"c++11",
"number-systems"
],
"Title": "Program that outputs binary values of input"
} | 215455 |
<p>This simple implementation of the HangMan game in Java is a side project, unlike the usual programs I write which are either school assignments or problems on coding websites. </p>
<p>It feels great to have something simple working, but I know for sure this can be improved. This only runs through the command line now, but I'm thinking of adding a lot more to this in the near future.</p>
<pre><code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner userGuess = new Scanner(System.in);
printTitleScreen();
System.out.println("");
String word = getRandomWordFromFile("/Users/kingcold/Desktop/words.txt");
char[] wordCharArray = word.toCharArray();
System.out.println("It's time to guess the word!");
StringBuilder gameWord = new StringBuilder(printBlankSpaces(word));
int successfulAttempts = 0;
int failedAttempts = 0;
int totalAttempts = 0;
do {
System.out.println("Your word looks like this: " + gameWord);
System.out.println("Your guess: ");
String userInput = userGuess.next();
char charUserInput = userInput.charAt(0);
if (isValidInput(userInput)) {
System.out.println("Your guess is: " + userInput);
if (!(containsUserInput(wordCharArray, userInput))) {
letterNotInWordMessage(userInput);
failedAttempts++;
} else if (containsUserInput(wordCharArray, userInput)){
letterInWordMessage(userInput);
gameWord.setCharAt(getMatchingIndex(wordCharArray, userInput), charUserInput);
successfulAttempts++;
}
} else {
System.out.println("Invalid input entered. Try again.");
}
totalAttempts = successfulAttempts + failedAttempts;
} while (!word.equals(gameWord.toString()));
if (word.equals(gameWord.toString())) {
System.out.println("Congratulations, you correctly guessed the word!");
System.out.println("The word is " + word);
System.out.println("You guessed the word in " + totalAttempts + " attempts");
userGuess.close();
}
}
private static void printTitleScreen() {
System.out.println("-------------------");
System.out.println("Welcome to Hangman!");
System.out.println("-------------------");
}
private static String printBlankSpaces(String word) {
return new String(new char[word.length()]).replace('\0', '-');
}
private static void letterNotInWordMessage(String letter) {
System.out.println("The letter " + letter + " is not in the word!");
}
private static void letterInWordMessage(String letter) {
System.out.println("The letter " + letter + " is in the word!");
}
private static int getMatchingIndex(char[] wordArray, String userGuess) {
int index = -1;
for (int i = 0; i < wordArray.length && (index == -1); i++) {
if (String.valueOf(wordArray[i]).equals(userGuess)) {
index = i;
}
}
return index;
}
private static boolean containsUserInput(char[] wordArray, String userGuess) {
for (int i = 0; i < wordArray.length; i++) {
if (wordArray[i] == userGuess.charAt(0)) {
return true;
}
}
return false;
}
private static boolean isValidInput(String userGuess) {
final int VALID_INPUT_LENGTH = 1;
if (userGuess.length() == VALID_INPUT_LENGTH && Character.isLetter(userGuess.charAt(0))) {
return true;
}
return false;
}
private static String getRandomWordFromFile(String fileName) throws FileNotFoundException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
String fileContents = "";
while(fileScanner.hasNextLine()) {
fileContents = fileContents.concat(fileScanner.nextLine() + "\n");
}
fileScanner.close();
String[] fileContentArray = fileContents.split("\n");
return fileContentArray[(int) (Math.random() * fileContentArray.length)];
}
}
</code></pre>
| [] | [
{
"body": "<p>Let’s start with your utility methods.</p>\n\n<hr>\n\n<h3><code>printBlankSpaces(String word)</code></h3>\n\n<p>This method returns a new <code>String</code>; It does not do any printing. It needs a better name...</p>\n\n<hr>\n\n<h3><code>getMatchingIndex(char[] wordArray, String userInput)</code></h3>\n\n<p>You repeatedly turn each character of <code>wordArray[]</code> into a <code>String</code> using <code>String.valueOf(...)</code>. It would be better to turn the <code>userInput</code> into a character before the loop starts (using <code>.charAt(0)</code>), and just do a simple comparison in the loop with that character.</p>\n\n<p>It would be even better to pass in a <code>char userInput</code>, instead of a <code>String</code>.</p>\n\n<p>Instead of <code>&& (index == -1)</code> in your loop condition, just <code>break;</code> out of the loop after you do the assignment <code>index = i;</code>, or even simplier, <code>return i;</code> and you could remove the <code>index</code> variable entirely.</p>\n\n<hr>\n\n<h3><code>containsUserInput(char[] wordArray, String userInput)</code></h3>\n\n<p>Instead of extracting <code>.charAt(0)</code> in every iteration of the loop, do it before the start of the loop and save it in a local variable. Or even better, like above, pass in <code>char userInput</code>.</p>\n\n<p>You aren’t using the loop index other than for retrieving the character <code>wordArray[i]</code>. This is a sign you could use an enhanced for-loop:</p>\n\n<pre><code>char userChar = userInput.charAt(0);\nfor (char letter : wordArray) {\n if (letter == userChar) {\n return true;\n }\n}\nreturn false;\n</code></pre>\n\n<p>Or even simpler, the entire method could be one statement, leveraging the function above:</p>\n\n<pre><code>return getMatchingIndex(wordArray, userInput) >= 0;\n</code></pre>\n\n<hr>\n\n<h3><code>isValidInput(String userGuess)</code></h3>\n\n<p>The construct <code>if (condition) return true; else return false;</code> can be re-written as <code>return condition;</code>. You don’t need the <code>if</code> statement.</p>\n\n<hr>\n\n<h3><code>getRandomWordFromFile(String fileName)</code></h3>\n\n<p>You are doing a lot of work to get a random line from the file. First, you are reading the file, line-by-line. Then, you concatenate all the lines together! Finally you split the concatenation back into the individual lines!</p>\n\n<p>If you simply stored each line as you read it into a <code>List<String></code>, you would be able to skip the concatenation and wouldn’t need to split later.</p>\n\n<p>In fact, reading all the lines of a file into a <code>List<String></code> is such a common operation, there is a standard method for it. <a href=\"https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html#readAllLines(java.nio.file.Path)\" rel=\"nofollow noreferrer\"><code>List<String> Files.readAllLines(Path path)</code></a>.</p>\n\n<p>With that, the function could be reduced to two lines:</p>\n\n<pre><code>List<String> lines = Files.readAllLines(Paths.get(fileName));\nreturn lines[ ThreadLocalRandom.current().nextInt(lines.size()) ];\n</code></pre>\n\n<p>That skips over a lot of fine points. Most important is ensuring all file resources are properly closed, even in the face of exceptions. The “try-with-resources” statement is best used for that:</p>\n\n<pre><code>File file = new File(fileName);\nList<String> lines = new ArrayList<>();\ntry(Scanner scanner = new Scanner(file)) {\n while(scanner.hasNextLine()) {\n lines.add( scanner.nextLine());\n }\n}\n</code></pre>\n\n<p>All that is done for you with the one <code>readAllLines()</code> call.</p>\n\n<hr>\n\n<h3>main</h3>\n\n<p><code>charUserInput</code> is not used. As mentioned above, many of your methods would be easier to write if they were given a single character, instead of a <code>String</code> ... and you have this unused character variable that would be perfect for that...</p>\n\n<p>You tests <code>if (!(containsUserInput(wordArray, userInput))) { ... }</code> followed immediately by <code>else if (containsUserInput(wordArray, userInput)) { ... }</code>. Those tests conditions are - literally - opposites of each other; if one is <code>true</code>, the other must be <code>false</code>, and vis-versa. Instead of repeating the test, both in code and in CPU time, just use an <code>else</code></p>\n\n<pre><code>if (!containsUserInput(wordArray, userInput)) {\n ...\n} else {\n ...\n}\n</code></pre>\n\n<p>I’ve removed the unnecessary ( )’s. You can improve this further by switching the order of the then-else clauses, and removing the <code>!</code> operator.</p>\n\n<pre><code>if (containsUserInput(wordArray, userInput)) {\n ... guess is correct code ...\n} else {\n ... guess is incorrect code ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T05:30:08.843",
"Id": "417086",
"Score": "1",
"body": "Such a good answer, except for the last sentence suggesting `snake_case` for local variables. The naming conventions say these variables are also written in `camelCase`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T16:48:59.820",
"Id": "417133",
"Score": "0",
"body": "Upvoted for all the good advice, but I want to explicitly state that I have the same gripe with this answer as Roland does..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T01:25:04.917",
"Id": "417199",
"Score": "0",
"body": "Ok ... ok ... there is a badge for caving in to peer pressure, right? I’ll remove last sentence."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T03:18:56.130",
"Id": "215545",
"ParentId": "215463",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T23:53:41.593",
"Id": "215463",
"Score": "4",
"Tags": [
"java",
"hangman"
],
"Title": "Simple HangMan game Implemented in Java"
} | 215463 |
<p>I work with YML files that include SIDs and the following structure:</p>
<pre><code> title:
"2": "content a" # key: comment
"3": "content b" # key: comment
"4": "content c" # key: comment
"5": "content d" # key: comment
"6": "content e" # key: comment
</code></pre>
<p>Usually, I have to remove some strings (note I never remove the number 1 or 2) so my new file looks like this:</p>
<pre><code> title:
"2": "content a" # key: comment
"3": "content b" # key: comment
"5": "content d" # key: comment
"6": "content e" # key: comment
</code></pre>
<p>I need to rearrange the SIDs in order to have a sequence without any gap (in this case 2, 3, 4, 5, 6) independently on the content. For that reason I have written the following script. It works properly but I need to bring it into production so I need your help to <strong>reduce its complexity, make it clear and simpler or any advice you may have for a beginner</strong> (in both, Python and Stack Exchange).</p>
<pre><code>import re, os
file=input ('YML file name: ')
#read the file and store its content as a list
os.chdir('/home/balaclava/Desktop/Scripts/YML fixer/')
rdfile= open(file)
cont=rdfile.readlines()
rdfile.close()
#list to store the reviewed strings
newfile=[]
newfile.append(cont[0]+cont[1])
#Get the second string SID as reference
numRegex = re.compile(r'\d+')
act=numRegex.search(cont[1])
global refnum
refnum=int(act.group())
#Loop for each string (-2 due to the two first string are excluded)
for i in range(len(cont)-2):
act=numRegex.search(str(cont[i+2]))
temp=int(act.group())
#If the SID is correct, add item to newlist, else, fix it and add the item to the list.
if temp == (refnum+1):
newfile.append(cont[i+2])
else:
temp= (refnum+1)
change=numRegex.sub(str(temp), cont[i+2])
newfile.append(change)
refnum += 1
#overwrite the file with the newlist content
with open (file,'w') as finalfile:
finalfile.write(''.join(newfile))
finalfile.close()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T04:01:50.463",
"Id": "416766",
"Score": "1",
"body": "Instead of attacking this with regexes, why not just do a `yaml.load` to bring it in, and modify it using regular python operations on the resulting data structure? It would be clear, and there would be no risk of corrupting the format."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T17:52:09.387",
"Id": "417140",
"Score": "0",
"body": "@AustinHastings, yaml.load would not keep the comments."
}
] | [
{
"body": "<p>You could use rumael.yaml, it can preserve comments. <a href=\"https://stackoverflow.com/questions/7255885/save-dump-a-yaml-file-with-comments-in-pyyaml#27103244\">https://stackoverflow.com/questions/7255885/save-dump-a-yaml-file-with-comments-in-pyyaml#27103244</a></p>\n\n<p>Moreover, you want to be a better python developer (or maybe pythonist?) I can give you some tips:</p>\n\n<p><strong>Content duplication</strong>\nYou are storing the file content inside <code>cont</code> and after closing the file you are duplicating that info in a new variable <code>newfile</code> I think that is an unnecessary process in this situation. You could store all the data in <code>cont</code> and just modify the lines needed. You can replace the entire if-else by:</p>\n\n<pre><code> if temp != (refnum+1): \n temp= (refnum+1) \n change=numRegex.sub(str(temp), cont[i])\n cont[i] = change\n</code></pre>\n\n<p><strong>For loop's range</strong>\nChange your range call in the for loop to <code>range(2, len(cont)):</code>\nNow inside the loop you can access the current line with simply <code>cont[i]</code> it's more readable and efficient.</p>\n\n<p>As with <code>i</code>'s range you are accessing refnum always with a +1. By initializing it as <code>refnum=int(act.group()) +1</code> your code saves that operations inside the loop. Another thing that you can do is do the +=1 increment at the beginning of the loop.</p>\n\n<p><strong>File management</strong>\nYou don't need to manually close files when using <code>with</code> statement you can remove <code>finalfile.close()</code>. Another thing, you are using <code>with</code> in the when writing but not when reading, think about always use the same method.</p>\n\n<p>More things can be changed but I think that's enough for now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T11:09:56.503",
"Id": "215990",
"ParentId": "215464",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "215990",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T00:10:34.877",
"Id": "215464",
"Score": "0",
"Tags": [
"python",
"beginner",
"yaml"
],
"Title": "Script that fixes YML SIDs to be simplified for production"
} | 215464 |
<p>I want to group by <code>id</code>, apply a custom function to the data, and create a new column with the results. It seems there must be a faster/more efficient way to do this than to pass the data to the function, make the changes, and return the data. Here is an example.</p>
<p><strong>Example</strong></p>
<pre><code>dat = pd.DataFrame({'id': ['a', 'a', 'a', 'b', 'b', 'b'], 'x': [4, 8, 12, 25, 30, 50]})
def my_func(data):
data['diff'] = (data['x'] - data['x'].shift(1, fill_value=data['x'].iat[0]))
return data
dat.groupby('id').apply(my_func)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>id x diff
0 a 4 0
1 a 8 4
2 a 12 4
3 b 25 0
4 b 30 5
5 b 50 20
</code></pre>
<p>Is there a more efficient way to do this?</p>
| [] | [
{
"body": "<p>I tried a few variations on your code. I was surprised at how performant the groupby approach really was!</p>\n\n<p>I changed your test data to use more values -- this amortizes the overhead a bit more. Surprisingly, the overhead is a lot of the difference. When I pushed the array length too high, the differences got very small for the groupby-based alternatives.</p>\n\n<p>That said, there are some things you can do to speed things up:</p>\n\n<pre><code>original: 18.022180362\norg_prefill: 14.969489811999996\nunique_keys: 23.526526202000007\ngroupby_return: 15.557421341999998\ngroupby_prefill: 15.846651952999991\nshifty: 9.605120361000004\n</code></pre>\n\n<p>I tried moving away from <code>groupby</code> by iterating over the distinct key values, but that didn't pay off: the performance got worse (<code>unique_keys</code>). I tried playing games with the return value from groupby, hoping to eliminate some duplicated effort. I eventually got that in <code>groupby_return</code>. For small sizes, where the overhead is more of a factor, I got a tiny speed boost by pre-filling the result column before running the groupby. That's <code>groupby_prefill</code> and then <code>org_prefill</code> where I back-ported it. You can see that it pays off versus the original code, but not against the <code>groupby_return</code> code. </p>\n\n<p>Finally, I eliminated the groupby entirely, by figuring out how to detect the start of a group using <code>.shift()</code>. Then I computed a shifted-by-one series and did the subtract operation as a single expression. That's <code>shifty</code> and it's the most performant by a bunch. W00t!</p>\n\n<pre><code>import sys\nimport timeit\n\nimport numpy as np\nimport pandas as pd\n\ndef make_df():\n n = 10_000\n df = pd.DataFrame({'id': ['a']*(n//2) + ['b']*(n//2),\n 'x': np.random.randn(n)})\n return df\n\ndef original(df):\n def my_func(group):\n group['diff'] = (group['x'] - group['x'].shift(\n 1, fill_value=group['x'].iat[0]))\n return group\n\n df.groupby('id').apply(my_func)\n\ndef org_prefill(df):\n def my_func(group):\n group['diff'] = (group['x'] - group['x'].shift(\n 1, fill_value=group['x'].iat[0]))\n return group\n\n df['diff'] = df['x']\n df.groupby('id').apply(my_func)\n\ndef unique_keys(df):\n #print(\"DF:\\n\", df)\n df['diff'] = 0\n for key in df.id.unique():\n matches = (df.id == key)\n #df.loc[matches, 'diff'] = df.loc[matches, 'x'] - df.loc[matches, 'x'].shift(1, fill_value=df.loc[matches, 'x'].iat[0])\n df_lmx = df.loc[matches, 'x']\n df.loc[matches, 'diff'] = df_lmx - df_lmx.shift(1, fill_value=df_lmx.iat[0])\n\ndef groupby_iter(df):\n for key, subset in df.groupby('id'):\n subset['diff'] = subset.x - subset.x.shift(1,\n fill_value=subset.x.iat[0])\n\ndef groupby_return(df):\n def my_func2(group):\n gx = group['x']\n result = gx - gx.shift(1, fill_value=gx.iat[0])\n return result\n\n res = df.groupby('id').apply(my_func2)\n df['diff'] = res.values\n\ndef groupby_prefill(df):\n def my_func2(group):\n gx = group['x']\n result = gx - gx.shift(1, fill_value=gx.iat[0])\n return result\n\n df['diff'] = df['x']\n res = df.groupby('id').apply(my_func2)\n df['diff'] = res.values\n\ndef shifty(df):\n shifted = df['x'].shift(fill_value=df['x'].iat[0])\n shifted.loc[(df.id != df.id.shift())] = df['x']\n df['diff'] = df['x'] - shifted\n\nif __name__ == '__main__':\n kwargs = {\n 'globals': globals(),\n 'number': 1000,\n 'setup': 'df = make_df()',\n }\n\n print(\"original:\", timeit.timeit('original(df)', **kwargs))\n print(\"org_prefill:\", timeit.timeit('org_prefill(df)', **kwargs))\n\n print(\"unique_keys:\", timeit.timeit('unique_keys(df)', **kwargs))\n #print(\"groupby_iter:\", timeit.timeit('groupby_iter(df)', **kwargs))\n print(\"groupby_return:\", timeit.timeit('groupby_return(df)', **kwargs))\n print(\"groupby_prefill:\", timeit.timeit('groupby_prefill(df)', **kwargs))\n print(\"shifty:\", timeit.timeit('shifty(df)', **kwargs))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T03:32:14.913",
"Id": "215470",
"ParentId": "215465",
"Score": "2"
}
},
{
"body": "<p>You may wish to try <a href=\"http://numba.pydata.org/\" rel=\"nofollow noreferrer\">numba</a>. Turn the DataFrame columns into Numpy arrays. Although, I couldn't get it working with letters, here it is with number id's. (ran in Jupyter)</p>\n\n<pre><code>import sys\nimport timeit\n\nimport numpy as np\nimport pandas as pd\nfrom numba import jit\n\n\nn = 1000\n\nid_arr = np.concatenate((np.tile(1, n//2), np.tile(2, n//2)), axis=None)\ndf = pd.DataFrame({'id': id_arr,\n 'x': np.random.randn(n)})\n\n@jit(nopython=True)\ndef calculator_nb(id, x):\n res = np.empty(x.shape)\n res[0] = 0\n for i in range(1, res.shape[0]):\n if id[i] == id[i-1]:\n res[i] = x[i] - x[i-1]\n else: \n res[i] = 0\n\n return res\n\n%timeit calculator_nb(*df[['id', 'x']].values.T)\n459 µs ± 1.85 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T12:40:17.830",
"Id": "215564",
"ParentId": "215465",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T00:24:31.533",
"Id": "215465",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "Groupby, apply custom function to data, return results in new columns"
} | 215465 |
<p>I implemented a PhoneBook utilizing a <code>Trie</code> data structure.</p>
<p>Could I ask you to evaluate it?</p>
<p>Did I apply <code>Trie</code> correctly for such case or is it better to store data somehow else?</p>
<p>I'm looking not only for working solution but also for an optimal one in terms of run-time and storage.</p>
<p>From my calculations, it takes NlogT to <code>add()</code> and <code>get()</code> where N is a number of chars and T is a number of children.</p>
<p>Am I right?</p>
<p>Here is the logic</p>
<pre><code>public final class PhoneBook {
private final Node name;
private final Node surname;
private final Comparator<Record> comparator;
public PhoneBook() {
this.name = new Node();
this.surname = new Node();
comparator = (r1, r2) -> {
int result = r1.getName().compareTo(r2.getName());
if (result == 0) {
result = r1.getSurname().compareTo(r2.getSurname());
if (result == 0) {
result = r1.getNumber().compareTo(r2.getNumber());
}
}
return result;
};
}
public void add(final Record record) {
add(record.getName().toLowerCase(), record, name);
add(record.getSurname().toLowerCase(), record, surname);
}
public SortedSet<Record> get(final String prefix) {
final String lc = prefix.toLowerCase();
final List<Record> recordsRetrievedByName = get(lc, name);
final List<Record> recordsRetrievedBySurname = get(lc, surname);
final SortedSet<Record> result = new TreeSet<>(comparator);
result.addAll(recordsRetrievedByName);
result.addAll(recordsRetrievedBySurname);
return result;
}
private List<Record> get(final String prefix, final Node ancestor) {
Node node = ancestor;
for (final char c: prefix.toCharArray()) {
final Node child = node.children.get(c);
if (child == null) {
return Collections.emptyList();
}
node = child;
}
return node.records;
}
private void add(final String str, final Record record, final Node ancestor) {
Node node = ancestor;
for (final char c: str.toCharArray()) {
final Node child;
if (node.children.containsKey(c)) {
child = node.children.get(c);
} else {
child = new Node();
node.children.put(c, child);
}
child.records.add(record);
node = child;
}
}
private static final class Node {
private final Map<Character, Node> children = new TreeMap<>();
private final List<Record> records = new ArrayList<>();
}
}
</code></pre>
<p>And the <code>Record</code> immutable object</p>
<pre><code>public final class Record {
private final String name;
private final String surname;
private final String number;
//constructor, getters, toString
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T05:21:44.237",
"Id": "416771",
"Score": "0",
"body": "It's look fine. I am also a beginner so i don't have very good knowledge about it. So i suggest to you please check this link for more https://www.geeksforgeeks.org/trie-insert-and-search/"
}
] | [
{
"body": "<h2>Naming:</h2>\n\n<p><code>name</code> and <code>surname</code> are somewhat unclear in what they specifically mean. The \"actual\" purpose of these variables is to serve as \"root\" of the trie. Incidentally I'd rename <code>ancestor</code> to <code>root</code>in all the usages in your code, simply because I'm more used to it. YMMV :)<br>\nI'd rename <code>name</code> and <code>surname</code> to <code>nameRoot</code> and <code>surnameRoot</code>.</p>\n\n<h2>Simplifications:</h2>\n\n<ul>\n<li>Initialize private fields that are not dependent on constructor arguments in the field declaration to save on space and complexity.</li>\n<li>Use <code>Comparator.comparing</code> and <code>thenComparing</code> to simplify your comparator.</li>\n</ul>\n\n<p>I personally also prefer to not leave too much space between fields.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private final Node name = new Node();\nprivate final Node surname = new Node();\nprivate static final Comparator<Record> comparator = Comparator.comparing(Record::getName)\n .thenComparing(Record::getSurname).thenComparing(Record::getNumber);\n</code></pre>\n\n<p>Note that I also changed the <code>comparator</code> to be static. It could also do with a better name, but I'm coming up empty right now...</p>\n\n<h2>Possible Trie Optimizations:</h2>\n\n<p>Currently your trie is using a <strong>lot</strong> of memory. It's not quite as bad as it could be, but considering that names are very much non-uniform, you will have a lot of \"degenerated branches\", where the branching factor is very low, if not 1 for \"long\" stretches of the data structure.</p>\n\n<p>These long stretches of basically linked lists can be collapsed by sacrificing a WORD of memory to store how many characters you can skip before the next <em>actual</em> branching.</p>\n\n<p>Currently <code>Node</code> does not support this in any way.</p>\n\n<hr>\n\n<p>The traversal during <code>add</code> can be simplified a bit with <code>computeIfAbsent</code> like so:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (final char c: str.toCharArray()) {\n final Node child = node.children.computeIfAbsent(c, Node::new);\n child.records.add(record);\n node = child;\n}\n</code></pre>\n\n<p>This simplification pretty quickly vanishes when you implement the optimization mentioned above (or rather it becomes somewhat complicated). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T12:57:17.570",
"Id": "417285",
"Score": "0",
"body": "Hi, thank you for such a great response. Could I ask if you can extend a part about Trie memory optimization?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T13:00:38.910",
"Id": "417289",
"Score": "0",
"body": "That kind of goes beyond what I want to put into an answer, but you should be able to find some useful information using the search term \"Patricia-Trie\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T12:18:52.990",
"Id": "215667",
"ParentId": "215468",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T01:43:17.493",
"Id": "215468",
"Score": "6",
"Tags": [
"java",
"algorithm",
"tree",
"complexity",
"trie"
],
"Title": "Phonebook using a trie"
} | 215468 |
<p>Good day, I am a college student and lately we had an assignment where we were tasked to write SQL commands on various questions depending on the information that is needed to be displayed from 3 different tables. Here are the instructions and a sample question with a provided solution:</p>
<p><a href="https://i.stack.imgur.com/Me7AV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Me7AV.png" alt="Assignment Instruction"></a></p>
<p><a href="https://i.stack.imgur.com/CvJDU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CvJDU.png" alt="Table"></a></p>
<p>And below are my answers:</p>
<pre><code>"Question 1: 1. Display information about parts that have their weights greater than the average weight of all parts. "
SELECT pNo, pName
FROM p
WHERE pWeight > (SELECT AVG(pWeight) FROM p);
"Question 2: 2. Find supplier numbers who supply any screws (i.e., such that the part name is ‘screw’). The constraint is that you may not use any join or cross (product). (Hint: Use subquery(ies).)"
SELECT DISTINCT(sNo)
FROM sp
WHERE pNo IN(SELECT pNo FROM p WHERE pName LIKE 'SCREW');
"Question 3: 3. Find supplier numbers of suppliers located in London who supply screws (i.e., such that the part name is ‘screw’) or bolts. The constraint is that you may not use any join or product, but use a subquery(ies). (Hint: Use subquery(ies)."
SELECT DISTINCT(s.sNo)
FROM s, p, sp
WHERE sp.sNo = s.sNo AND sp.pNo = p.pNo AND sCity = 'LONDON' AND pName in('Screw', 'Bolt');
"Question 4: 4. Display the total number of orders (over all parts) and the minimum, average, and maximum quantity of individual orders (each order is a tuple in sp). "
SELECT COUNT(pNo), SUM(qty), MIN(qty), AVG(qty), MAX(qty), (SELECT
AVG(qty) FROM SP) AVGqty
FROM sp;
"Question 5: 5. For each part find the total, minimum, average, and maximum quantity of individual orders (each order is a tuple in p) and the total number of orders. Display the part number and for that part: the number of orders, total, minimum, average, maximum quantity of individual orders for that part and also the average quantity on order over all parts. Furthermore, display information in reverse order by part number. "
SELECT pNo, COUNT(pNo), SUM(qty), MIN(qty), AVG(qty), MAX(qty), (SELECT AVG(qty)
FROM SP) AVGqty
FROM sp
GROUP BY pNo
ORDER BY pNo DESC;
"Question 6: 6. For each part find the total, minimum, average, and maximum quantity of individual orders (each order is a tuple in p) and the total number of orders, but only for those parts for which the average quantity on order is greater than the average quantity on order over all parts. Display the part number and for that part: the number of orders, total, minimum, average, maximum quantity of individual orders for that part and also the average quantity on order over all parts. Furthermore, display information in reverse order by part number. "
SELECT pNo, COUNT(pNo), SUM(qty), MIN(qty), AVG(qty), MAX(qty), (SELECT AVG(qty)
FROM SP) AVGqty
FROM sp
GROUP BY pNo HAVING AVG(qty) > (SELECT AVG(qty) FROM sp)
ORDER BY AVG(qty) DESC;
"Question 7: 7. Find each part for which its largest individual order in terms of quantity is larger than the largest quantity on order for either nut or a cam and the largest quantity for a nut and the largest quantity for a cam. "
SELECT pNo, MAX(qty), (SELECT MAX(qty) FROM sp WHERE pNo IN (SELECT pNo FROM p WHERE pName = 'Nut' OR pName = 'Cam') ) AS MAXcamORnut
FROM sp
GROUP BY pno
HAVING MAX(qty) > ALL (SELECT qty FROM sp WHERE pNo IN(SELECT pNo FROM p
WHERE pName = 'Nut' OR pName = 'Cam'));
</code></pre>
<p>What I would like to know is if there are any more ways to shorten each one of my answers for the 7 questions, preferably the shortest code possible. As a curious person, efficiency matters to me and it is ideal to use much shorter commands.</p>
<p>For example, I am most definitely sure that the code from #7 could be shortened:</p>
<pre><code>SELECT pNo, MAX(qty), (SELECT MAX(qty) FROM sp WHERE pNo IN (SELECT pNo FROM
p WHERE pName = 'Nut' OR pName = 'Cam') ) AS MAXcamORnut
FROM sp
GROUP BY pno
HAVING MAX(qty) > ALL (SELECT qty FROM sp WHERE pNo IN(SELECT pNo FROM p
WHERE pName = 'Nut' OR pName = 'Cam'));
</code></pre>
<p>Thank you guys in advanced. :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T03:41:41.677",
"Id": "416765",
"Score": "3",
"body": "Please post the code to be reviewed as text (as you did for number 7) rather than as screenshots."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T11:31:26.027",
"Id": "416809",
"Score": "0",
"body": "Your image of text [isn't very helpful](//meta.unix.stackexchange.com/q/4086). It can't be read aloud or copied into an editor, and it doesn't index very well. Please [edit] your post to incorporate the relevant text directly (preferably using copy+paste to avoid transcription errors)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T11:49:24.293",
"Id": "416811",
"Score": "0",
"body": "I have made these changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T16:49:46.873",
"Id": "428910",
"Score": "0",
"body": "@XLefora Some of these questions are ambigious. Take the last one, what exactly is asked here? There is a larger than x,y,z of which y and z are subsets of x. These type of questions would make me furious on a test."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T03:23:03.330",
"Id": "215469",
"Score": "1",
"Tags": [
"sql",
"mysql"
],
"Title": "Writing SQL queries to retrieve data from given tables"
} | 215469 |
<p>Come across this problem once again in the book <a href="https://books.google.com/books?id=nl9dDwAAQBAJ&lpg=PP4&dq=modern%20c%2B%2B%20challenge%20epub&pg=PA29#v=onepage&q=modern%20c++%20challenge%20epub&f=false" rel="nofollow noreferrer"><em>The Modern C++ Challenge</em></a>.</p>
<blockquote>
<p><strong>18. Minimum function with any number of arguments</strong></p>
<p>Write a function template that can take any number of arguments and returns the minimum value of them all, using <code>operator <</code> for comparison. Write a variant of this function template that can be parameterized with a binary comparison function to use instead of <code>operator <</code>.</p>
</blockquote>
<p>I wonder how simple and elegant the implementation could be using <a href="/questions/tagged/c%2b%2b17" class="post-tag" title="show questions tagged 'c++17'" rel="tag">c++17</a>. The following is the parameterized version. Ideas?</p>
<pre><code>#include <algorithm>
template <typename Less, typename T, typename... Ts>
constexpr const T& min(Less less, const T& a, const T& b, const Ts&... rems) {
if constexpr (sizeof...(rems)) {
return min(less, std::min(a, b, less), rems...);
}
else {
return std::min(a, b, less);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T05:20:26.437",
"Id": "416770",
"Score": "0",
"body": "Interesting question! Is `Less` supposed to be a comparison object? (Like one that implement \"less than\" for type `T`?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T05:47:13.043",
"Id": "416774",
"Score": "1",
"body": "@user1118321 Yes. `std::less<void>` would also fit :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T19:05:58.490",
"Id": "416920",
"Score": "1",
"body": "While it's exactly the same number of operations, wouldn't pipelining make it worthwhile to divide-and-conquer rather than chain linearly? That way one would effectively run two or three cmp/cmov ops in parallel. So, basically instead of `min(min(min(min(...` it should expand to `min(min(min(...), min(...)), min(min(), min()))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T06:16:05.463",
"Id": "416988",
"Score": "2",
"body": "@Damon I would consider it premature optimization here."
}
] | [
{
"body": "<p>This looks nice! Two issues I see here,</p>\n\n<ol>\n<li><p>When compiling your template with <code>clang</code>, it refuses the <code>if constexpr</code> dispatch for every recursive instantiation with <code>sizeof...(rems) > 1</code>, e.g.</p>\n\n<blockquote>\n <p>error: constexpr if condition evaluates to 2, which cannot be narrowed to type <code>bool</code> [-Wc++11-narrowing]</p>\n</blockquote>\n\n<p><code>gcc</code> seems to accept this, but the fix is quite simple, just be more explicit about it:</p>\n\n<pre><code>if constexpr (sizeof...(rems) > 0)\n</code></pre></li>\n<li><p>Never underestimate the standard library. You are doing more work than necessary, have a look at overload #4 in the <a href=\"https://en.cppreference.com/w/cpp/algorithm/min\" rel=\"noreferrer\"><code>std::min</code></a> signature. You can expand the parameter pack into a <code>std::initializer_list</code> and pass this to <code>std::min</code>, which simplifies your template and avoids its recursive instantiation. Additionally wrapping the arguments into a <code>std::reference_wrapper</code> ships around unnecessary copies.</p>\n\n<pre><code>#include <functional>\n\ntemplate <typename Less, typename... Ts>\nconstexpr decltype(auto) min(Less less, const Ts&... rems) {\n return std::min({std::cref(rems)...}, less).get();\n}\n</code></pre>\n\n<p>The return type of the <code>std::min</code> invocation is a <code>std::reference_wrapper</code>, to get around this, its <code>get()</code> member function is called.</p>\n\n<p>Of course, you will pay for the construction of <code>sizeof...(rems)</code> <code>std::reference_wrapper</code> instances and for the <code>std::initializer_list</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T09:14:34.017",
"Id": "416787",
"Score": "0",
"body": "1) I guess clang is standard-compliant here. 2) Emm... Not sure whether the return type is fine. Maybe have `T` deduced from second argument, and have return type explicitly specified as `const T&`? That is, something like `template <typename Less, typename T, typename... Ts>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T09:23:16.663",
"Id": "416790",
"Score": "1",
"body": "I added `.get()` on the `std::min` return value to dereference the `std::reference_wrapper`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T12:02:24.783",
"Id": "416816",
"Score": "0",
"body": "I think @Snowhawk 's solution beats both of us XD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:03:47.980",
"Id": "416824",
"Score": "2",
"body": "You can [see here](https://gcc.godbolt.org/z/dutPVf) how the compiler can optimize out those things you claim you pay for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:09:11.787",
"Id": "416826",
"Score": "0",
"body": "@chris Nice! Can we assume that the same optimization is applied for large objects?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:17:20.580",
"Id": "416830",
"Score": "1",
"body": "@lubgr, I don't see why not considering that the reference wrapper is essentially a pointer and the initializer list thus essentially contains pointers regardless of the pointed-to type. I don't see lingering wrappers [in here](https://gcc.godbolt.org/z/7DdweM) with `std::string`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T14:38:36.897",
"Id": "416849",
"Score": "0",
"body": "@chris That makes sense. Thanks for the explanation!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T20:36:35.783",
"Id": "416941",
"Score": "1",
"body": "@chris yea, that works as long as the user remembers to pass a comparator that invokes `std::cref<T>::operator T&()`. Passing a comparator defined with generalized auto params results in `std::cref<T>` arguments that need to be unwrapped."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T08:59:10.663",
"Id": "215486",
"ParentId": "215471",
"Score": "12"
}
},
{
"body": "<pre><code>template <typename Less, typename T, typename... Ts>\nconstexpr const T& min(Less less, const T& a, const T& b, const Ts&... rems) {\n</code></pre>\n\n<p>This function requires a minimum of 2 elements. A minimum element will exist if the user provides a single argument variadic list. Consider handling that.</p>\n\n<pre><code>auto& min1 = min(std::less<>{}, 4, 5); // okay!\nauto& min2 = min(std::less<>{}, 4); // candidate function not viable, reqs 3 args, 2 provided\n</code></pre>\n\n<hr>\n\n<pre><code> return min(less, std::min(a, b, less), rems...);\n</code></pre>\n\n<p>Your approach here uses recursion and implementations are permitted to put a recursion depth limit on <code>constexpr</code> calculations. Consider an iterative solution that expands the pack while calculating the minimum.</p>\n\n<pre><code>template <typename Comparator, typename First, typename... Rest>\nconstexpr decltype(auto) variadic_min(Comparator cmp, First const& first, Rest const&... rest) {\n const First* result = std::addressof(first);\n\n // cast each evaluated expr to void in case of overloaded comma operator shenanigans\n ((void)(result = std::addressof(std::min(*result, rest, cmp))), ...);\n\n return *result;\n}\n</code></pre>\n\n<p>An explanation with what is going on with the <a href=\"https://en.cppreference.com/w/cpp/language/fold\" rel=\"noreferrer\">fold expression</a>:</p>\n\n<pre><code>((void)(result = std::addressof(std::min(*result, rest, cmp))), ...);\n ^ ^ ^ ^ \n | | | expand using comma op\n | | safer than built-in, now constexpr in 17\n | evaluate the expression for each pack variable\n cast to void the entire expression to avoid overloaded comma op.\n</code></pre>\n\n<hr>\n\n<p>Just thinking beyond the standard library and reinventing the wheel. This <code>min</code> works fine for homogenous packs. What about heterogenous packs?</p>\n\n<pre><code>auto& min1 = min(std::less<>{}, 4, 5, -1); // min1 = -1\nauto& min2 = min(std::less<>{}, 4, 5, -1.); // candidate template ignored...\n</code></pre>\n\n<p>One of the benefits of the conditional operator (<code>?:</code>) is that if both resulting expressions return lvalues of the same type, then the result will have the same type. If that type is <code>T&</code>, we could assign to that variable. Could we mimic that behavior with <code>min</code> and friends?</p>\n\n<pre><code>auto a = 4;\nauto b = 5;\n((b < a) ? b : a) = 42; // a = 42, b = 5\nmin(std::less<>{}, a, b) = 42; // cannot assign to return value, returns const-qualified type\nstd::min(a, b) = 42; // same with standard library.\nmin(std::less<>{}, 5, 6) = 42 // cannot assign, makes sense!\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T11:52:12.720",
"Id": "416812",
"Score": "0",
"body": "Wow O_O Need some time to digest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T11:54:30.523",
"Id": "416813",
"Score": "3",
"body": "Oh, the fold expression is performed on the comma operator. What a trick, but very nice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T12:00:25.113",
"Id": "416815",
"Score": "0",
"body": "The only disadvantage I can see in your solution is that it cannot be `constexpr`. Or am I wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T12:59:08.980",
"Id": "416822",
"Score": "4",
"body": "@Lingxi, [It's fine with constexpr](https://gcc.godbolt.org/z/cmM8CQ)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:25:24.707",
"Id": "416832",
"Score": "1",
"body": "@chris Oh my. I didn't expect compiler to be that smart, given the address-of operator in action here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:33:54.967",
"Id": "416834",
"Score": "1",
"body": "@Lingxi, Yeah, `constexpr` has come a long way since its introduction. C++20 will include the ability to make `std::vector` constexpr and will actually include a constexprified vector, unless something big changes in the next year."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T10:18:56.967",
"Id": "215493",
"ParentId": "215471",
"Score": "17"
}
},
{
"body": "<p>It works well, according to my simple test program:</p>\n<pre><code>#include <functional>\nint main()\n{\n return min(std::less<int>(), 2, 0, 3);\n}\n</code></pre>\n<p>I suggest that when you present code for review, you include the tests, too - I imagine that your testing is much more thorough than mine, and I'm too lazy to re-create the full suite. It also helps reviewers identify scenarios that are missing from the tests (or, conversely, scenarios that are redundant).</p>\n<hr />\n<p>I recommend using perfect forwarding for the comparator:</p>\n<pre><code>constexpr const T& min(Less&& less,\n// ^^\n</code></pre>\n\n<pre><code> return std::min(a, b, std::forward<Less>(less));\n// ^^^^^^^^^^^^^^^^^^\n</code></pre>\n<p>There's a couple of other uses that need to be forwarded, too.</p>\n<hr />\n<p>As lubgr <a href=\"/a/215486\">mentioned</a>, it's worth using an initializer list. If we want to avoid copying (if the inputs are large, or can't be copied), then we'll want to use a initializer-list of reference wrappers, and use <code>std::min_element()</code> (since the initializer-list <code>std::min()</code> returns a copy. That can be achieved like this:</p>\n<pre><code>#include <algorithm>\n#include <functional>\n\ntemplate<typename Less, typename... T>\nconstexpr auto& min(Less&& less, const T& ...values)\n{\n auto const compare_wrapped =\n [&less](auto const&a, auto const& b) {\n return std::forward<Less>(less)(a.get(), b.get());\n };\n\n auto const list = { std::ref(values)..., };\n auto const smallest =\n std::min_element(list.begin(), list.end(), compare_wrapped);\n return smallest->get();\n}\n</code></pre>\n \n<pre><code>int main()\n{\n auto const a = 3;\n auto const b = 0;\n auto const c = 2;\n\n auto const& lowest = min(std::less<int>(), a, b, c);\n\n return &lowest != &b;\n}\n</code></pre>\n<p>Or, more succinctly:</p>\n<pre><code>template<typename Less, typename... T>\nconstexpr auto& min(Less&& less, const T& ...values)\n{\n return std::min({std::cref(values)...,}, std::forward<Less>(less)).get();\n}\n</code></pre>\n<p>One defect in this implementation is that it will accept xvalues and happily return a (useless) reference in that case. I think it ought to be possible to distinguish that case, and forward the chosen xvalue as result, but I haven't had time to implement that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T11:58:31.727",
"Id": "416814",
"Score": "1",
"body": "I don't think perfect forwarding is necessary here. `std::min` takes `less` by value anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T12:24:28.787",
"Id": "416817",
"Score": "0",
"body": "Fair enough - in which case, you end up with exactly lubgr's suggestion (modulo `auto&` vs `decltye(auto)` - I'm not quite sure which is correct. Possibly the `decltype` version, if it means we get a copy from xvalue arguments but a reference from lvalue arguments; I'd need to check)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T10:42:29.917",
"Id": "215495",
"ParentId": "215471",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "215493",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T03:50:47.597",
"Id": "215471",
"Score": "18",
"Tags": [
"c++",
"library",
"template-meta-programming",
"c++17",
"variadic"
],
"Title": "Min function accepting varying number of arguments in C++17"
} | 215471 |
<p>I'm very much a beginner at programming, and hoping to get some advice!
I'm having some trouble with a tripadvisor scraper being slow, and have identified the part of my code that is taking a while. It's likely because of the long selector, but i'm not sure how to use anything more specific because there are randomly generated strings on the more specific selectors. Below the snippet that is taking a while, and below that is the full code. Would appreciate any feedback!</p>
<p>Sample of the webpages im scraping:</p>
<p><a href="https://www.tripadvisor.com.sg/Hotels-g255100-Melbourne_Victoria-Hotels.html" rel="nofollow noreferrer">https://www.tripadvisor.com.sg/Hotels-g255100-Melbourne_Victoria-Hotels.html</a></p>
<p><a href="https://www.tripadvisor.com.sg/Hotel_Review-g255100-d257433-Reviews-The_Hotel_Windsor-Melbourne_Victoria.html" rel="nofollow noreferrer">https://www.tripadvisor.com.sg/Hotel_Review-g255100-d257433-Reviews-The_Hotel_Windsor-Melbourne_Victoria.html</a></p>
<p>Code giving me problems:</p>
<pre><code> num_rooms = 0
extra_info = soup.select('#taplc_about_addendum_react_0 div div div div')
for data in extra_info:
data = data.text.strip()
if data.isdigit():
num_rooms = int(data)
</code></pre>
<p>Full code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import xlsxwriter
import time
def get_soup(url):
r = requests.get(url)
return BeautifulSoup(r.content, 'html.parser')
def write_xlsx(items, xlsx_write_row):
write_column = 0
for item in items:
worksheet.write(xlsx_write_row, write_column, item)
write_column += 1
workbook = xlsxwriter.Workbook('Results.xlsx')
worksheet = workbook.add_worksheet()
# user variables
while True:
start_url = input('Start url: ')
if 'https://www.tripadvisor.com.sg/Hotels-' not in start_url:
print(
'Please enter a valid url. e.g https://www.tripadvisor.com.sg/Hotels-g255100-Melbourne_Victoria-Hotels.html')
else:
break
print('fetching page...')
soup = get_soup(start_url)
while True:
min_rev_num = input('Min Reviews for property: ')
if min_rev_num.isdigit():
if int(min_rev_num) >= 0:
min_rev_num = int(min_rev_num)
break
print('Please enter a valid number')
while True:
print('Enter max number of low review number properties on a single page, from 0 to 30.')
print('(Program will exit once this condition is fulfilled)')
num_rev_criteria = input('Input: ')
if num_rev_criteria.isdigit():
if 0 <= int(num_rev_criteria) <= 30:
num_rev_criteria = int(num_rev_criteria)
break
print('Please enter a valid number')
while True:
min_star_rating = input('Min star rating for property: ')
if min_star_rating.isdigit():
if 0 <= int(min_star_rating) <= 5:
min_star_rating = float(min_star_rating)
break
print('Please enter a valid number')
while True:
min_room_num = input('Min number of rooms: ')
if min_room_num.isdigit():
if int(min_room_num) >= 0:
min_room_num = int(min_room_num)
break
print('Please enter a valid number')
while True:
max_num_pages = int(soup.select_one('.pageNum.last.taLnk').text.strip())
num_pages = input('Page to search until(1 to {}):'.format(str(max_num_pages)))
if num_pages.isdigit():
if 1 <= int(num_pages) <= max_num_pages:
num_pages = int(num_pages)
break
print('Please enter a valid number')
print('-'*30 + '\n')
check = input("Make sure 'Results.xlsx' is closed and deleted. Once you are ready, press enter")
write_row = 0
write_xlsx(['Property Details', 'Star Rating', 'Number of Rooms'], write_row)
page_url = start_url
rejected_properties = 0
start = time.time()
print('Getting data...')
# get property data
for page_num in range(num_pages):
print('\nOn page {}\n'.format(str(page_num + 1)))
low_review_count = 0
soup = get_soup(page_url)
if page_num != num_pages - 1:
next_page = soup.select_one('.nav.next.taLnk.ui_button.primary')['href']
page_url = 'https://www.tripadvisor.com.sg' + next_page
else:
pass
rows = soup.select('.property_title.prominent')
prop_urls = []
for row in rows:
prop_urls.append('https://www.tripadvisor.com.sg' + row['href'])
for prop in prop_urls:
soup = get_soup(prop)
try:
num_reviews = int(soup.select_one('.reviewCount').text.strip().split(' ')[0].replace(',', ''))
except AttributeError:
num_reviews = 0
try:
property_name = soup.select_one('#HEADING').text.strip()
except AttributeError:
property_name = ' '
if num_reviews >= min_rev_num:
try:
star_rating_class = soup.select_one('.ui_star_rating')['class'][1]
star_rating = float(star_rating_class[5] + '.' + star_rating_class[6])
except TypeError:
star_rating = 0
num_rooms = 0
extra_info = soup.select('#taplc_about_addendum_react_0 div div div div')
for data in extra_info:
data = data.text.strip()
if data.isdigit():
num_rooms = int(data)
try:
address = soup.select_one('.street-address').text.strip() + ', ' + soup.select_one('.locality').text.strip() + soup.select_one('.country-name').text.strip()
except AttributeError:
address = ' '
try:
phone = soup.select_one('.is-hidden-mobile.detail').text.strip()
except AttributeError:
phone = ' '
if star_rating >= min_star_rating or star_rating == 0:
if num_rooms >= min_room_num or num_rooms == 0:
write_row += 1
write_xlsx([property_name + '\n' + address + '\nT: ' + phone, star_rating, num_rooms], write_row)
else:
print("Rejected: '{}'\n".format(property_name) + ' - Not enough rooms:{}'.format(num_rooms))
else:
print("Rejected: '{}'\n".format(property_name)+' - Not high enough star rating:{}'.format(star_rating))
else:
low_review_count += 1
print("Rejected: '{}'\n".format(property_name) + ' - Not enough reviews:{}'.format(num_reviews))
print(' - Low review count: {}/{}'.format(low_review_count, num_rev_criteria))
if low_review_count >= num_rev_criteria:
print('Exiting due to low review count on page')
break
workbook.close()
end = time.time()
print("\nDone! Results can be found in 'Results.xlsx' in the same folder\n")
print('Results can be copied straight onto the shortlist(paste values only), formatting has already been done.')
print('If any results have 0 stars or 0 rooms, Tripadvisor does not have this data')
print('Address and phone numbers are based on Tripadvisor data as well\n')
print('Number of pages searched: {}'.format(str(page_num + 1)))
props_searched = (page_num - 1)*30 + len(prop_urls)
print('Number of properties searched: {}'.format(str(props_searched)))
print('Number of properties accepted: {}'.format(str(write_row - 1)))
print('Number of properties rejected: {}'.format(str(props_searched - write_row + 1)))
print('Time taken: {} minutes'.format(str((end-start)//60)))
while True:
check = input('\nTo exit, press enter')
if True:
break
</code></pre>
| [] | [
{
"body": "<p>At least on the <code>.com</code> version of the site (I can't access the <code>.com.sg</code>) the content your looking for is:</p>\n\n<pre><code><div class=\"hotels-hotel-review-about-addendum-AddendumItem__title--2QuyD\">NUMBER OF ROOMS</div>\n<div class=\"hotels-hotel-review-about-addendum-AddendumItem__content--iVts5\">180</div>\n</code></pre>\n\n<p>This appears to be consistent across pages. So, you could look for a <code>.hotels-hotel-review-about-addendum-AddendumItem__title--2QuyD</code> followed by a <code>.hotels-hotel-review-about-addendum-AddendumItem__content--iVts5</code>. You probably want to check that the text in the first div is <code>NUMBER OF ROOMS</code> in case some pages have more \"addendum items\" with purely numeric content:</p>\n\n<p>When scraping, I like pulling things out into functions to make my intent more clear, to make testing easier, and to make it easier to refactor if (more likely, when the page changes):</p>\n\n<pre><code>def get_addendum_item_titles(page):\n return page.find_all('div', class_='.hotels-hotel-review-about-addendum-AddendumItem__title--2QuyD')\n\ndef get_number_of_rooms_addendum_title(page):\n for title in get_addendum_item_titles(page):\n if title.text.strip().upper() == 'NUMBER OF ROOMS':\n return title\n\n raise ValueError('Number of rooms addendum title not found')\n\ndef get_number_of_rooms(page):\n title = get_number_of_rooms_addendum_title(page)\n content = title.parent.find('div', class_='.hotels-hotel-review-about-addendum-AddendumItem__content--iVts5')\n return int(content.text.strip())\n</code></pre>\n\n<p>You may want to throw those class names in constants.</p>\n\n<p>A prime justification for this approach is immediately obvious. The <code>--2QuyD</code>-like suffixes are almost certainly automatically generated. I suspect the next time tripadvisor modifies any of their CSS these suffixes will change and break your code. But I imagine that the <code>hotels-hotel-review-about-addendum-AddendumItem__title</code> part will rarely change. So you need a way of finding the proper classname with only that prefix. Ideally you create a function like:</p>\n\n<pre><code>def find_class_with_prefix(page, prefix):\n pass\n</code></pre>\n\n<p>I'll leave that as an exercise to you, but once you create it, it will be really cleanly integratable into the above code.</p>\n\n<p>Note there is a <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors#Syntax\" rel=\"nofollow noreferrer\">CSS attribute selector</a> that you can use instead for this: <code>div[class^=hotels-hotel-review-about-addendum-AddendumItem__title]</code>, but I suspect it will have poor performance characteristics because it probably uses a linear scan. You'll want to tap into whatever datastructures beautifulsoup already has built for quickly looking up elements by class (to find the list of class names).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T01:39:55.027",
"Id": "417200",
"Score": "0",
"body": "Thank you for the very detailed response, it was exactly what i was looking for! I was considering even using some string methods to search the raw html out of desperation. Some parts of your answer are still a bit beyond me, but i'll research and make sense of it. At least I have a sense of what to do now. Will look into make the function to find the prefix if it changes as well. Thank you so much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T19:50:34.387",
"Id": "215525",
"ParentId": "215472",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215525",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T04:15:02.137",
"Id": "215472",
"Score": "2",
"Tags": [
"python",
"performance",
"beginner",
"excel",
"web-scraping"
],
"Title": "Python webscraper to get property info from Tripadvisor"
} | 215472 |
<p>I want your suggestions about this shell script. I use it to backup some configurations on my home media server.</p>
<p>What improvements would you do? Keep in mind, I want to optimize space and speed and at the same time, backup the maximum configurations over time.</p>
<p>p.-s. For more informations about the hanoi scheme: <a href="https://en.wikipedia.org/wiki/Backup_rotation_scheme" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Backup_rotation_scheme</a>.</p>
<p><strong>ideas :</strong></p>
<ul>
<li>Only use the hanoi scheme when the limit space is reach by checking the space required by rsync.</li>
</ul>
<pre><code>#!/bin/bash
# ==================================================================================
# Description: BackUp script following a Hanoi scheme using rsync.
# Author: Hugo Lapointe Di Giacomo
# ==================================================================================
set -o errexit
set -o nounset
#set -o xtrace
# ----------------------------------------------------------------------------------
# Options
# ----------------------------------------------------------------------------------
setsMax=16 # ................................ Maximum number of sets bakcup.
cmdPrefix="" # .............................. "echo" if dry-run enable, "" otherwise.
srcDir="/appdata" # ......................... Source directory to backup.
dstDir="/mnt/backup/snapshots" # ............ Destination directory to backup in.
logDir="/mnt/backup/logs" # ................. Logs directory.
# ----------------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------------
SEC_PER_DAY=86400; # ........................ Number of seconds per day.
LATEST_SNAP="$dstDir/latest"; # ............. The "latest" snap.
LATEST_LOG="$logDir/latest"; # .............. The "latest" log.
DATE_FORMAT="%Y-%m-%d"; # ................... The format of a date.
HOUR_FORMAT="%H:%M"; # ...................... The format of a hour.
# ----------------------------------------------------------------------------------
# Show usage of this script.
# ----------------------------------------------------------------------------------
function showUsage() {
echo "Usage: $0 [OPTIONS]..."
echo ""
echo "Options available:"
echo " -h, --help Show usage of the script."
echo " -m, --max Maximum sets of backup."
echo " -s, --src Source directory to backup."
echo " -d. --dst Destination directory to backup in."
echo " -l, --log Log directory."
echo " -r, --dry Enable dry-run."
}
# ----------------------------------------------------------------------------------
# Parse arguments.
# ----------------------------------------------------------------------------------
function parseArgs() {
while [ $# -gt 0 ]; do
case $1 in
-h|--help)
showUsage $@
exit 0
;;
-m|--max)
setsMax=${2:-$setsMax}
shift 2
;;
-s|--src)
if [ -d "$2" ]; then
srcDir="$2"
fi
shift 2
;;
-d|--dst)
if [ -d "$2" ]; then
dstDir="$2"
fi
shift 2
;;
-l|--log)
if [ -d "$2" ]; then
logDir="$2"
fi
shift 2
;;
-r|--dry)
cmdPrefix="echo"
shift 1
;;
*)
echo "Unknown option or value: $1"
showUsage $@
exit 1
;;
esac
done
}
# ----------------------------------------------------------------------------------
# Create a backup with rsync.
# ----------------------------------------------------------------------------------
function createBackUp() {
snapDir="$dstDir/$1" # ................. Name of the snap dir.
logFile="$logDir/$1.log" # ............. Name of the log file.
RSYNC_CMD="rsync " # ................... Rsync Command.
RSYNC_CMD+="--archive " # .............. Enable recursion and preserve infos.
RSYNC_CMD+="--verbose " # .............. Increase amount of infos printed.
RSYNC_CMD+="--human-readable " # ....... Output number in readable format.
RSYNC_CMD+="--progress " # ............. Show progress during transfer.
RSYNC_CMD+="--delete " # ............... Delete files from receiving side.
RSYNC_CMD+="--link-dest=$LATEST_SNAP " # "latest" symbolic link to hardlink.
RSYNC_CMD+="$srcDir " # ................ Source directory to backup.
RSYNC_CMD+="$snapDir " # ............... Destination directory to backup in.
# Create backup and save the output in a log file.
$cmdPrefix $RSYNC_CMD 2>&1 | tee "$logFile"
}
# ----------------------------------------------------------------------------------
# Update the latest links.
# ----------------------------------------------------------------------------------
function updateLatestLinks() {
$cmdPrefix rm -f "$LATEST_SNAP"
$cmdPrefix ln -s "$snapDir" "$LATEST_SNAP"
$cmdPrefix rm -f "$LATEST_LOG"
$cmdPrefix ln -s "$logFile" "$LATEST_LOG"
}
# ----------------------------------------------------------------------------------
# Calculate the previous move in the cycle.
# https://en.wikipedia.org/wiki/Backup_rotation_scheme
# ----------------------------------------------------------------------------------
function calculateDaysFromBackupOfSameSet() {
local todayInSec=$(date +%s)
local todayInDay=$(($todayInSec / $SEC_PER_DAY))
local daysToBackup=$((2 ** ($setsMax - 1)))
local daysElapsed=0
local i=1
while [ $i -lt $(($daysToBackup / 2)) ]; do
local rotation=$(($todayInDay & $i))
if [ $rotation -eq 0 ]; then
daysElapsed=$(($i * 2))
break
fi
daysElapsed=$(($daysToBackup / 2))
i=$((2 * $i))
done
echo $daysElapsed
}
# ----------------------------------------------------------------------------------
# Main function.
# ----------------------------------------------------------------------------------
function main() {
parseArgs $@
local todayDatetime=$(date +$DATE_FORMAT.$HOUR_FORMAT)
if createBackUp $todayDatetime; then
updateLatestLinks
local daysElapsed=$(calculateDaysFromBackupOfSameSet)
local expiredDay=$(date -d "$daysElapsed days ago" +$DATE_FORMAT)
$cmdPrefix rm -frv "$dstDir/$expiredDay."*
fi
}
main $@
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T19:19:25.247",
"Id": "416926",
"Score": "0",
"body": "I have rolled back the last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T19:25:58.847",
"Id": "416929",
"Score": "0",
"body": "@Zeta, understood."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T05:35:17.563",
"Id": "497583",
"Score": "1",
"body": "I have rolled back your latest edits. 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-11-23T05:36:06.390",
"Id": "497584",
"Score": "1",
"body": "You may want to read https://codereview.meta.stackexchange.com/questions/1065/how-to-post-a-follow-up-question as well."
}
] | [
{
"body": "<p><strong>Do not silently ignore invalid arguments</strong></p>\n\n<p>Your script allows to specify the source directory (and other locations). Here is the relevant part in <code>function parseArgs()</code>:</p>\n\n<pre>\n -s|--src)\n if [ -d \"$2\" ]; then\n srcDir=\"$2\"\n fi\n shift 2\n ;;\n</pre>\n\n<p>If <code>--src <sourceDir></code> is specified with an invalid source directory then this argument is (silently) ignored. The consequence is that even a simple typo</p>\n\n<pre>\nbackup --src /my_importatn_data\n</pre>\n\n<p>causes the default directory to be backed up, and not <code>/my_important_data</code>.</p>\n\n<p>Wrong arguments (here: an invalid or not existing directory) should print an error message (to the standard error) and terminate the shell script (with a non-zero exit code). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T06:21:30.967",
"Id": "215476",
"ParentId": "215473",
"Score": "10"
}
},
{
"body": "<h3>Double-quote variables used as command arguments</h3>\n\n<p>Although in many places in the posted code the variables used as command arguments are correctly double-quoted, there are more than a few exceptions, for example <code>parseArgs $@</code>, which should be <code>parseArgs \"$@\"</code> to preserve arguments with spaces. </p>\n\n<p>It's a good habit to <a href=\"https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells\">systematically double-quote variables</a> used as command arguments.</p>\n\n<h3>Collect argument lists in arrays instead of strings</h3>\n\n<p>The <code>createBackUp</code> function collects arguments for the rsync command in a string and executes it. This will not work if some elements (here <code>$srcDir</code>, <code>$snapDir</code>, or <code>$LATEST_SNAP</code>) contain spaces.</p>\n\n<p>You can make it safe by using an array instead:</p>\n\n<pre><code>createBackUp() { \n snapDir=\"$dstDir/$1\" # ................. Name of the snap dir.\n logFile=\"$logDir/$1.log\" # ............. Name of the log file.\n\n RSYNC_CMD=(\"rsync\") # ................... Rsync Command.\n RSYNC_CMD+=(\"--archive\") # .............. Enable recursion and preserve infos.\n RSYNC_CMD+=(\"--verbose\") # .............. Increase amount of infos printed.\n RSYNC_CMD+=(\"--human-readable\") # ....... Output number in readable format.\n RSYNC_CMD+=(\"--progress\") # ............. Show progress during transfer.\n RSYNC_CMD+=(\"--delete\") # ............... Delete files from receiving side.\n RSYNC_CMD+=(\"--link-dest=$LATEST_SNAP\") # \"latest\" symbolic link to hardlink.\n RSYNC_CMD+=(\"$srcDir\") # ................ Source directory to backup.\n RSYNC_CMD+=(\"$snapDir\") # ............... Destination directory to backup in.\n\n # Create backup and save the output in a log file.\n $cmdPrefix \"${RSYNC_CMD[@]}\" 2>&1 | tee \"$logFile\"\n}\n</code></pre>\n\n<p>I also dropped the <code>function</code> keyword which is not recommended in Bash.</p>\n\n<h3>Simplify using arithmetic context</h3>\n\n<p>The <code>calculateDaysFromBackupOfSameSet</code> uses several arithmetic operations and conditions which could be simplified and made more readable using <em>arithmetic context</em>:</p>\n\n<pre><code>calculateDaysFromBackupOfSameSet() {\n local i todayInDay daysToBackup\n local todayInSec=$(date +%s)\n\n ((todayInDay = todayInSec / SEC_PER_DAY))\n ((daysToBackup = 2 ** (setsMax - 2)))\n local daysElapsed=daysToBackup\n\n for ((i = 1; i < daysToBackup; i *= 2)); do\n if ! ((todayInDay & i)); then\n ((daysElapsed = i * 2))\n break\n fi\n done\n\n echo \"$daysElapsed\"\n}\n</code></pre>\n\n<p>I also eliminated some repeated <code>daysToBackup / 2</code>.\nI believe this is equivalent to the original, but I haven't tested it.\nExcuse me if I made an error, the point is more to demonstrate the power of the arithmetic context.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T07:34:46.433",
"Id": "215483",
"ParentId": "215473",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T05:18:57.787",
"Id": "215473",
"Score": "7",
"Tags": [
"bash",
"file-system"
],
"Title": "Backup with Hanoi Strategy"
} | 215473 |
<p>I have module called printer allocator (PrinterAllocator) which will allocate the next available printer to the requester. </p>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
public class PrinterAllocator {
private static final int TOTAL_AVAILABLE_PRINTERS = 25;
private BitSet bitSet = new BitSet( TOTAL_AVAILABLE_PRINTERS );
public PrinterAllocator() {
List<Integer> unassignedPriters = new ArrayList<>( Arrays.asList( 1, 2, 3, 24 ) ); // but this array will be fetched from database
unassignedPriters.forEach( printerId -> bitSet.set( printerId - 1 ) );
}
public int getNextPrinter() {
int index = bitSet.nextClearBit( 0 ) + 1;
bitSet.set( index );
return index + 1;
}
public boolean hasEnoughPrinters(int printersNeeded){
/* point 1*/
return bitSet.cardinality()+printersNeeded<=TOTAL_AVAILABLE_PRINTERS;
}
}
</code></pre>
<p>Point 1: I am unable to replace 'point 1' with following code</p>
<pre><code> return bitSet.cardinality()+printersNeeded<=bitSet.size()
(or)
return bitSet.cardinality()+printersNeeded<=bitSet.length();
</code></pre>
<p>Because bitSet.size() and bitSet.length() has a different meaning that is size() != length() != TOTAL_AVAILABLE_PRINTERS</p>
<p>Any better Idea to implement PrinterAllocator with/without bitset</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:49:49.240",
"Id": "416838",
"Score": "0",
"body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
}
] | [
{
"body": "<p>Why do you use BitSet? You're not saving kilobytes of memory by representing your printers as a set of bits. Go for code clarity and represent each printer with a dedicated instance of Printer class that holds the allocation status of the printer in question. Store them in a List or other data structure that suits your needs. You could even have two LinkedLists for allocated and free printers and just pop the first from the <code>free</code> list and push it to the end of the <code>allocated</code> list. You need to synchronize anyway. No need to count sizes to see if there are available printers. Just check <code>isEmpty()</code>.</p>\n\n<p><code>bitSet</code> is a bad name for printer reservartion status. Java is a strongly typed language so you don't need to repeat the type in the field name. Use <code>printerAllocationStatus</code> if you really need to use a BitSet (see above).</p>\n\n<p>You're stacking on responsibilities by implementing <code>hasEnoughPrinters</code> in your allocator. Instead implement <code>getNumberOfFreePrinters</code> and let the caller decide what to do with the information. The method is of limited use anyway, since printer allocation status might change right after the caller has checked for availability making the data the caller has completely useless.</p>\n\n<p><code>getNextPrinter</code> does not communicate the side effect of changing printer allocation status in it's name. Use <code>allocatePrinter</code> instead.</p>\n\n<p>Use consistent terminology. In a PritnerAllocator a printer is allocated or free, not assigned.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T07:26:34.167",
"Id": "215482",
"ParentId": "215478",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "215482",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T06:47:43.053",
"Id": "215478",
"Score": "0",
"Tags": [
"java",
"bitset"
],
"Title": "Allocate Resource Effectively"
} | 215478 |
<p>The aim of this code, written in <strong>Python3.6</strong>, was to write a function that will non-recursively walk over a N-branching tree structure.</p>
<p>It works by using a list of indices that keep track of visited nodes and by retracing prior steps when a tree branch ends. The function <code>non_recurs</code> visits nodes top down left to right (as far as I can tell). </p>
<p><code>non-recurs</code> allows the caller to provide a function to the <code>func</code> argument which will be applied to to each node. The <code>end_only</code> argument will determine if the supplied function will be applied to all nodes (<code>end_only=False</code>) or only nodes at the end of branches (<code>end_only=True</code>).</p>
<p>1st I would like to know if this attempt is actually capable of walking over N-branching trees and 2nd I would like to know what you think about my implementation. </p>
<hr>
<p><em>NOTE: There are two sections to my code below. The first is to generate N-branching trees and is not the focus of this code review. But is required to generate my demonstrated output</em></p>
<hr>
<p><strong>EDIT</strong></p>
<ol>
<li>I added IndexError to the except of the try block</li>
</ol>
<p><strong>tree generation code</strong></p>
<pre><code>from itertools import product
# CODE to create test tree's for walking
def assign(tree, idx, value):
new_idx = idx[:]
assignment_idx = new_idx.pop()
ref = tree
for i in new_idx:
ref = ref[i]
ref[assignment_idx] = value
return tree
def n_branch_tree(height, branches):
idx = ([i] for i in range(branches))
tree = list(range(branches))
count = 0
node = 0
while count < height:
for i in idx:
# mutates tree
assign(tree, list(i), list(range(node, node+branches)))
node += branches
count += 1
idx = product(range(branches), repeat=count)
return tree
</code></pre>
<hr>
<p><strong>tree walk code</strong></p>
<pre><code># Code to walk over tree
def walk(tree, idx):
"""Return tree node at provided index
args:
tree: tree to index
idx: index of desired node
returns: node
"""
for i in idx:
tree = tree[i]
return tree
def non_recurs(tree, func=print, branches=2, end_only=True, ):
"""Non-recursively walk n-branching tree
args:
tree: n-branching tree
func: function that takes tree node as first argument
branches: The number of branches each node has
end_only: Default is True. When True will only apply func to
end nodes. When False will apply func to all Nodes
"""
branches = branches - 1 # Because index's start at 0
idx = [0]
node = None
while True:
# print(idx)
try:
node = walk(tree, idx)
except (TypeError, IndexError):
# Could not find node at index
try:
# Walk back up tree until a node has not
# been fully explored
while idx[-1] == branches:
idx.pop()
except IndexError:
# Means all nodes in index have been fully explored
break
# Increase index if current index is under node branch limit
if idx[-1] < branches:
idx[-1] += 1
# Apply func to end node
if end_only and node:
func(node)
node = None
else:
idx.append(0)
# Apply func to all nodes
if not end_only:
func(node)
if __name__ == '__main__':
tree = n_branch_tree(height=3, branches=3)
print(tree)
value_store = []
non_recurs(tree, func=value_store.append, branches=3, end_only=True)
print(value_store)
</code></pre>
<hr>
<p><strong>Outputs</strong></p>
<pre><code>[[[18, 19, 20], [21, 22, 23], [24, 25, 26]], [[27, 28, 29], [30, 31, 32], [33, 34, 35]], [[36, 37, 38], [39, 40, 41], [42, 43, 44]]]
[18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44]
</code></pre>
| [] | [
{
"body": "<h2>About your solution</h2>\n\n<p>Your <code>tree generation code</code> is wrong. It doesn't return a tree, it returns a multidimensional list instead. There is a good, detailed article about a <strong>tree data structure</strong>: <a href=\"https://medium.freecodecamp.org/all-you-need-to-know-about-tree-data-structures-bceacb85490c\" rel=\"nofollow noreferrer\">Everything you need to know about tree data structures</a>. </p>\n\n<p>The main idea of tree - the connection of nodes. All begins from the root - the singular node at the first level, that contains references to the all nodes at the next level, which in their turn have references to the next level nodes, so on. Thus, every node should have as minimum as two fields: one for value and one for list of its childs (<a href=\"https://en.wikipedia.org/wiki/Tree_(data_structure)#Terminology_used_in_trees\" rel=\"nofollow noreferrer\">terminology used in trees</a>).</p>\n\n<p><strong>Edit after the comment [start]:</strong></p>\n\n<p>Actually, the <code>tree generation code</code> returned value is resembling the tree, especially taking into account that the Python lists and numbers are objects. It has root object with 3 childs, each child has three childs too, so on. (when <code>height=3, branches=3</code>). At the last level it has objects with a number value.</p>\n\n<p>Thus, it complies the first <strong>tree data structure</strong> requirement: the connection of nodes (from my own definition :)). But not all nodes have value - only the last level's nodes do (the <strong>leaves</strong> in the tree terminology). So, you anyway can't walking through tree, changing or printing all nodes value, because some nodes don't have them:</p>\n\n<pre><code>root[\n 2-nd lvl[ 4-th lvl with values\n 3-rd lvl[18, 19, 20],\n [21, 22, 23],\n [24, 25, 26] \n ], \n [ \n [27, 28, 29],\n [30, 31, 32],\n [33, 34, 35] \n ], \n [ \n [36, 37, 38],\n [39, 40, 41],\n [42, 43, 44] \n ] \n ] \n</code></pre>\n\n<p><strong>Edit after the comment [end]:</strong></p>\n\n<p>I didn't throughout investigation of your <code>tree walk code</code>, but by glance it uses the the wrong tree idea as well as the <code>tree generation code</code> and therefore, can't work correctly.</p>\n\n<h2>My partial solution</h2>\n\n<p>I read your requirements and wrote my own solution, that creates tree, walks through it and applies a passed function to each node. It can't process only end nodes though, but this functionality is easy to add.</p>\n\n<pre><code>class Tree(object):\n\n def __init__(self):\n self.value = None\n self.childs = None\n\n # Build tree recursively\n # All nodes doesn't have values, just child list\n # Values will be set by the passed function\n def grow_tree(self, height, child_num):\n if height < 2:\n return\n\n self.childs = [] \n\n for i in range(child_num):\n child = Tree()\n self.childs.append(child)\n child.grow_tree(height - 1, child_num)\n\n # Walk through tree iteratively\n def walk_tree(self, func):\n\n all_current_level_nodes = [self]\n\n while all_current_level_nodes:\n all_next_level_nodes = []\n\n for node in all_current_level_nodes:\n func(node)\n if node.childs:\n all_next_level_nodes.extend(node.childs) \n\n all_current_level_nodes = all_next_level_nodes\n\n\n### Recursive implementation\n###\n# def walk_tree(self, func):\n# func(self)\n#\n## if isinstance(self.childs, list):\n# if self.childs: \n# for child in self.childs:\n# child.walk_tree(func) \n</code></pre>\n\n<p><strong>Testing</strong></p>\n\n<pre><code>### Functions for passing to the \"walk_tree\" method \ndef set_values(node):\n node.value = set_values.cnt\n set_values.cnt += 1\n\ndef print_values(node):\n print(node.value)\n\ndef print_id(node):\n print(id(node))\n\ndef square_values(node):\n node.value = node.value ** 2\n\ntree = Tree()\n\ntree.grow_tree(2, 3)\n\ntree.walk_tree(print_id)\n\n# Function is an object. Add the \"cnt\" field to this object.\n# It will work as a static variable, preserve counter between calls.\nset_values.cnt = 1\ntree.walk_tree(set_values)\n\ntree.walk_tree(print_values)\n\ntree.walk_tree(square_values)\n\ntree.walk_tree(print_values)\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code># \"print_id\" function was applied on each node while walk_tree\n139632471400688\n139632471400800\n139632471400856\n139632471400912\n# \"set_values\" \n# then \"print_values\" were applied\n1\n2\n3\n4\n# \"square_values\"\n# then \"print_values\" were applied\n1\n4\n9\n16\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T18:28:15.180",
"Id": "417043",
"Score": "1",
"body": "There are many definitions of a [data structure *tree*](https://en.m.wikipedia.org/wiki/Tree_(data_structure)), and even more implementations. I don't follow `[James Schinner's] tree generation code is wrong. It doesn't return [a] tree`: can you be more explicit what makes the value returned *not a tree*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T19:34:49.727",
"Id": "417047",
"Score": "2",
"body": "@greybeard I thought again and understood, that it can be viewed as tree, in which all parent nodes doesn't have a value. They are containing only a list of childs and thus, serving just for grouping the ending nodes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T20:42:03.887",
"Id": "417061",
"Score": "0",
"body": "@greybeard So, it is rather returning of a multidimensional list (which has a recursive structure), than a tree. I added the graphical explanation into my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T22:06:04.373",
"Id": "417067",
"Score": "1",
"body": "(`[the return value of James Schinner's tree generation] can be viewed as [a] tree` yes: it does have a root, every node but the root is the child of exactly *one* node. (Just imagine one of the lists \"with siblings\" shorter: while still looking a multi-dimensional list *from an implementation angle*, it no longer looks a multi-dimensional *array* for inhomogeneous lengths.) `it is rather returning of a multidimensional list (which has a recursive structure), than a tree` [I don't follow](https://en.m.wikipedia.org/wiki/Binary_heap): *tree* is in the interpretation, the operations supported."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T01:40:07.460",
"Id": "417076",
"Score": "0",
"body": "@MiniMax Neat, regardless of specific definition a tree. I do like your solution, it is nice to read and understand."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T17:54:47.010",
"Id": "215576",
"ParentId": "215480",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215576",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T07:23:22.253",
"Id": "215480",
"Score": "4",
"Tags": [
"python",
"tree",
"iteration"
],
"Title": "Walking over a N branching tree"
} | 215480 |
<p>I'm working on an apllication that needs to process a lot of objects in realtime. I've separated the logic from the UI so that it isn't as much of a mess. The basic idea is that every tick I'm trying to populate a list of objects to process and once they are processed I update the UI accordingly.</p>
<p>I've written this collection class for use in the main processing loop. Here is the reasoning behind some of my decisions:</p>
<ul>
<li><p>The objects are processed sequentially in a loop. I only care for fast sequential reading so I've decided to use arrays at the base of it all hoping to get some kind of cache hit benefit.</p></li>
<li><p>The maximum amount of objects is known at compile time so I've tried to avoid rapid heap allocations by pooling my data objects. I allocate a maximum amount but only use the amount that is active.</p></li>
<li><p>I needed a way to correlate the logical objects with the presentation layer, so I've decided to use identifiers. These identifiers allow me to know what actual UI object the data belongs to.</p></li>
</ul>
<p>Through basic stopwatch benchmarking I've arrived to the following solution:</p>
<pre><code>class FixedCapCollectionIntGuids<T> where T : struct
{
public T[] m_array;
Dictionary<int, int> m_guidToIDs;
int[] m_idToGuids;
int m_capacity;
public int Size { get; private set; }
public FixedCapCollectionIntGuids(int capacity)
{
Size = 0;
m_capacity = capacity;
m_array = new T[capacity];
m_guidToIDs = new Dictionary<int, int>(capacity);
m_idToGuids = new int[capacity];
}
public T this[int key]
{
get
{
Debug.Assert(key < Size, "Illegal read");
return m_array[key];
}
}
public void Add(T value, int guid)
{
Debug.Assert(!m_guidToIDs.ContainsKey(guid), "Double insertion");
m_array[Size] = value;
m_guidToIDs[guid] = Size;
m_idToGuids[Size] = guid;
++Size;
}
public void Remove(int guid)
{
Debug.Assert(m_guidToIDs.ContainsKey(guid), "Not found");
int i = m_guidToIDs[guid];
int lasti = Size - 1;
int lastGuid = m_idToGuids[lasti];
m_array[i] = m_array[lasti];
m_guidToIDs.Remove(guid);
m_guidToIDs[lastGuid] = i;
m_idToGuids[i] = lastGuid;
--Size;
}
}
</code></pre>
<p>Please try to ignore the dumb naming, this is WIP so I didn't put much thought into what the best names for variables and classes are at this point. </p>
<p>My benchmarks show that this approach appears to be faster than just having a dictionary for reading(presumably because an array is cache friendlier), but slower for adding\removing(presumably because I'm maintaining 3 separate collections instead of one). I'm somewhat fine with this because addition and removal is going to be less frequent than iteration, but I'm still wondering whether I've solved the problem in a stupid way or not. Can it be done better?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T12:24:32.933",
"Id": "416818",
"Score": "0",
"body": "What do you need the dictionary and the other array for? You're not using them anywhere. All you are doing is assingn values to them but you never read them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T12:37:55.530",
"Id": "416819",
"Score": "0",
"body": "Not quite. Look closer at the code of the Remove function. I get the index of the data array from the specified guid using the dictionary. Without the dictionary I can't identify where the object is in the array. The other array is the reverse of the dictionary - it lets me quickly identify which guid the object at index has. Otherwise I would need to iterate the values of the dictionary which I believe is slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T12:18:35.317",
"Id": "417459",
"Score": "0",
"body": "\"My benchmarks show that this approach appears to be faster than just having a dictionary for reading\" That would probably depend on what kind of data you're storing as well. How did you benchmark, or can you share a representative example of your input?"
}
] | [
{
"body": "<p>This looks like a good (i.e. not stupid) implementation if your main requirements is efficient sequential access to the data. Addition and removal will necessarily be slower than for a Dictionary because you are wrapping a dictionary, but the time complexity is of the other work is constant, so it isn't something I would worry about too much if your goal is fast read/modification.</p>\n\n<h2>Encapsulation</h2>\n\n<p>Generally the encapsulation is fine, but there is one exception: <code>m_array</code> should not be publically settable. It should be <code>readonly</code> or a getter-only <code>{get; }</code> property. Being a reference type, I can't think of any downside to making it a property. Being publically settable means that anyone can change it to <code>null</code> or an array of the wrong size and break the data-structure, which is obviously bad. The other array and dictionary should also be <code>readonly</code>.</p>\n\n<p>I do wonder why you provide an indexer as well as the array, but do not provide a setter for the indexer. The indexer will also create confusion by copying structs you want to mutate. You should probably look at whether you can hide <code>m_array</code> altogether, and do all the work via the indexer: this would produce a much tighter API if you can 'get away' with it. You may be interested to look into <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.arraysegment-1?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>ArraySegment</code></a> as a possible means of facilitating a somewhat tighter API if that indexer is deficient.</p>\n\n<h2>Exception Handling</h2>\n\n<p>I don't know you use-case, but I'd reconsier using <code>Debug.Assert</code> for input sanitisation. It would seem much better would be to exploit the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>TryGetValue</code></a> method of <code>Dictionary'2</code> in <code>Remove</code> and <code>TryAdd</code> in <code>Add</code> to efficiency perform the check and throw under any runtime conditions.</p>\n\n<p>Your exception messages could also be clearer. <code>\"NotFound\"</code>: what is not found? If you throw an exception instead of asserting, you can throw an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.argumentexception?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>ArgumentException</code></a> and make it completely clear what was not found and where the caller went wrong. \"IllegalRead\" means nothing at all. \"Double Insertion\" is pretty cryptic.</p>\n\n<p>You could also do with checking that <code>Size</code> is less than <code>Capacity</code> when adding, as this should also throw an exception, rather than relying on the order of operations to throw with an <code>IndexOutOfRange</code> exception before doing any damanger (if <code>m_guidToIDs[guid]</code> was set first, this would linger despite the operation failing, so the code is extremely brittle).</p>\n\n<p>A check in the constructor that <code>capacity</code> is non-negative would also be nice, just to cover as much of the API surface as possible with clear and useful exceptions (it will still fail if it tries to allocate a negative length array, but an <code>ArgumentOutOfRangeException</code> would be so much nicer.</p>\n\n<h2>Typical C♯</h2>\n\n<p>The code is mostly nice-to-read C#, though there are some bits that could be nicer:</p>\n\n<ul>\n<li><p>The <code>m_</code> member prefix is typical in C++, but much less so in C#. <code>m_array</code> should have a name consistent with being a <code>public</code> member: it should be in <code>ProperCamelCase</code>.</p></li>\n<li><p>Generally it is advised that the accessibility of any member of type is made explicit e.g. <code>public class FixedCapCollectionIntGuids<T></code>, <code>private int m_capactiy</code>). This avoids any confusion (particularly when people are used to using different languagse with different defaults), and makes it completely clear that <em>this is the intention</em> and you didn't just forget to qualify the accessibility.</p></li>\n<li><p>The BCL uses <code>Count</code> rather than <code>Size</code> for everything: it's what people using C# will expect. I'd also argue it is clearer, because <code>Size</code> has can relate to size in memory. Conformity with the BCL also be sensible if you wanted to implement <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>IReadOnlyList<T></code></a> (for which you would need to provide in addition an enumerator but nothing more), which could be useful.</p></li>\n<li><p>It's also typical to have <code>key, value</code> in the BCL add methods, so you might want to consider having the same in <code>Add</code>.</p></li>\n<li><p>Usually we use 4 spaces for indentation.</p></li>\n</ul>\n\n<h2>Other Comments</h2>\n\n<ul>\n<li><p>While I think I see why you would except this to only be used with <code>struct</code>s, I don't see why you need limit this general purpose data structor to only <code>struct</code>s. If you don't have a reason, I would remove the generic constraint (it has no semantic/performance impact for when <code>struct</code>s are used). The only change this would warrant would be clearing removed values (so that you don't hold references to objects that are not in the structure). This is just a suggestion, and 'that would increase the API surface and costs of maintance/testing' would be a good reason to not do this.</p></li>\n<li><p><code>public T this[int key]</code> should have parameter <code>guid</code> for consistency.</p></li>\n<li><p><code>FixedCapCollectionIntGuids</code> is an odd name; I will only say that shorting <code>Cap</code> to <code>Capacity</code> is not a good idea: it only obfuscates the meaning.</p></li>\n<li><p>For a 'tricky' API like this one (where it's very easy to mis-use <code>m_array</code>), you need to provide inline documentation (<code>///</code>) for all <code>public</code> parts of the API. This should detail the usage and assumptions, and explain things like \"this is not thread safe at all\", and that <code>m_array</code> may be larger than <code>Size</code> and you should not access anything beyond index <code>Size - 1</code>. I find that the act of writing documentation makes me aware of the edge cases I need to handle, makes it possible to maintain code without having to guess at the exact intention of a method/class, and gives consumers the information and confidence they need to use your APIs as intended.</p></li>\n<li><p><code>Remove</code> is a bit untidy looking: I would try to break it up a bit with empty lines, to separate the bit where you remove the old values, move the 'last' value into the inner position, and finally resize the structure. There is also a bug in <code>Remove</code>: it will go wrong if you try to remove the last element: writing the code to detect this should automatically force you to organise it so that my previous comment is addressed.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T15:51:32.847",
"Id": "229470",
"ParentId": "215487",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T09:19:43.143",
"Id": "215487",
"Score": "5",
"Tags": [
"c#",
"performance",
"collections",
"cache"
],
"Title": "Data structure that is fast to read and modify"
} | 215487 |
<p>I am writing a noise blur convolution kernel in CUDA</p>
<pre><code>__global__ void noiseReduction(float *im, float *NR, int height, int width)
{
// Definition
int i, j, bi, bj;
// Retrieve global id
i = threadIdx.y + blockDim.y*blockIdx.y + 2;
j = threadIdx.x + blockDim.x*blockIdx.x + 2;
// Retrieve id within block
bi = threadIdx.y + 2;
bj = threadIdx.x + 2;
/* Shared memory preparation */
__shared__ float im_shared[2 + int(BLOCKSIZE) + 2][2 + int(BLOCKSIZE) + 2];
// Load left superior corner
if (2 <= bi && bi < 4 && 2 <= bj && bj < 4){
im_shared[bi-2][bj-2] = im[(i-2)*width + j - 2];
}
// Load left superior corner
if (2 <= bi && bi < 4 && 2 <= bj && bj < 4){
im_shared[bi-2][bj-2] = im[(i-2)*width + j - 2];
}
// Load right superior corner
if (2 <= bi && bi < 4 && BLOCKSIZE <= bj && bj < BLOCKSIZE + 2){
im_shared[bi-2][bj+2] = im[(i-2)*width + j + 2];
}
// Load left inferior corner
if (BLOCKSIZE <= bi && bi <= BLOCKSIZE + 2 && 2 <= bj && bj < 4){
im_shared[bi+2][bj-2] = im[(i+2)*width + j - 2];
}
// Load right inferior corner
if (BLOCKSIZE <= bi && bi <= BLOCKSIZE + 2 && BLOCKSIZE <= bj && bj < BLOCKSIZE + 2){
im_shared[bi+2][bj+2] = im[(i+2)*width + j + 2];
}
// Load superior edge
if (2 <= bi && bi < 4){
im_shared[bi-2][bj] = im[(i-2)*width + j];
}
// Load inferior edge
if (BLOCKSIZE <= bi && bi <= BLOCKSIZE + 2){
im_shared[bi+2][bj] = im[(i+2)*width + j];
}
// Load left edge
if (2 <= bj && bj < 4){
im_shared[bi][bj-2] = im[i*width + j - 2];
}
// Load right edge
if (BLOCKSIZE <= bj && bj < BLOCKSIZE + 2){
im_shared[bi][bj+2] = im[i*width + j + 2];
}
// Load center data
im_shared[bi][bj] = im[i*width + j];
__syncthreads();
// Noise reduction
if (i < height-2 && j < width - 2)
{
NR[i*width+j] =
(2.0*im_shared[bi-2][bj-2] + 4.0*im_shared[bi-2][bj-1] + 5.0*im_shared[bi-2][bj] + 4.0*im_shared[bi-2][bj+1] + 2.0*im_shared[bi-2][bj+2]
+ 4.0*im_shared[bi-1][bj-2] + 9.0*im_shared[bi-1][bj-1] + 12.0*im_shared[bi-1][bj] + 9.0*im_shared[bi-1][bj+1] + 4.0*im_shared[bi-1][bj+2]
+ 5.0*im_shared[bi ][bj-2] + 12.0*im_shared[bi ][bj-1] + 15.0*im_shared[bi ][bj] + 12.0*im_shared[bi ][bj+1] + 5.0*im_shared[bi ][bj+2]
+ 4.0*im_shared[bi+1][bj-2] + 9.0*im_shared[bi+1][bj-1] + 12.0*im_shared[bi+1][bj] + 9.0*im_shared[bi+1][bj+1] + 4.0*im_shared[bi+1][bj+2]
+ 2.0*im_shared[bi+2][bj-2] + 4.0*im_shared[bi+2][bj-1] + 5.0*im_shared[bi+2][bj] + 4.0*im_shared[bi+2][bj+1] + 2.0*im_shared[bi+2][bj+2])
/159.0;
}
}
void blurGPU(float *im, float *image_out,
int height, int width)
{
/* Definitions */
float *im_GPU, *image_out_GPU;
/* Malloc GPU */
cudaMalloc((void **) &im_GPU, height*width*sizeof(float));
cudaMalloc((void **) &image_out_GPU, height*width*sizeof(float));
/* Copy input to GPU */
cudaMemcpy(im_GPU, im, height*width*sizeof(float), cudaMemcpyHostToDevice);
/* Call kernels */
dim3 dimBlock(BLOCKSIZE,BLOCKSIZE,1);
dim3 dimGrid(ceil((width-2) / BLOCKSIZE),ceil((height-2) / BLOCKSIZE),1);
// Noise reduction
noiseReduction<<<dimGrid,dimBlock>>>(im_GPU, image_out_GPU, height, width);
cudaThreadSynchronize();
cudaMemcpy(image_out, image_out_GPU, height*width*sizeof(float), cudaMemcpyDeviceToHost);
/* Free GPU */
cudaFree(im_GPU);
cudaFree(image_out_GPU);
}
</code></pre>
<p>The idea is that each thread loads to shared memory the pixels that correspond to their location, and the threads close to the border of each thread block also take care of loading the neighbouring pixels from other blocks (the "apron" part of the convolution)</p>
<p>It seems to be working, but its hard to tell at glance if there is a subtle mistake.</p>
<p>Plus I wrote a lot of manual code to load the "apron", and I cannot shake the feeling that there should be a more elegant way of writing this.</p>
<p>And of course I could be missing some big things for performance.</p>
<p>Any tips for a CUDA beginner? I am specially interested in testing, improving the code style and improving performance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T13:48:46.737",
"Id": "416837",
"Score": "0",
"body": "This is C++, not C as you labelled it. The cast `int(BLOCKSIZE)` is invalid C code."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T09:29:11.770",
"Id": "215488",
"Score": "2",
"Tags": [
"c",
"signal-processing",
"cuda"
],
"Title": "Convolutions with shared memory in CUDA"
} | 215488 |
<p>My goal in creating this project was to create a password generator that was simple enough to be useful as well as sophisticated enough in its random-number generator so as to not be contrived.</p>
<p>I used Boost Program Options for argument parsing. The interface seems extremely easy to use, and the fact that it's both more readable and allows for writing idiomatic C++ seem pretty good reasons to not use <code>getopt.h</code> in this case. </p>
<p>Using the <code>--passwords</code> or <code>-n</code> flags the user may set the number of passwords to generate. Likewise, the <code>--length</code> or <code>-l</code> flags set the length of the password. I looked around for a standard list of character symbols to use, but I couldn't find anything like a standard, so my default symbol list is <code>"!@#$``~|\\%^&*()[]-_=+{}';:,<.>/?"</code>. (Note: the backtick is repeated so StackOverflow's markdown highlights everything properly.) The user may use the <code>--simple-symbols</code> flag to use only <code>"!@#$&?"</code>.</p>
<p>The actual random number generation was what I wanted to explore with this project. While researching this question I came across some very similar projects like <a href="https://codereview.stackexchange.com/questions/194068/cryptographically-secure-password-generation-in-c">this one</a>, which used <a href="https://download.libsodium.org/doc/" rel="nofollow noreferrer">Sodium</a>, but I'm wondering if the method I'm using here is as good, or at least viable.</p>
<p>I used <a href="https://en.cppreference.com/w/cpp/numeric/random/random_device" rel="nofollow noreferrer">std::random_device</a> to generate my random numbers, along with <a href="https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution" rel="nofollow noreferrer">std::uniform_int_distribution</a>, to ensure as random and uniform an output as possible. I'm looking for a way to check whether std::random_device will work as expected; since it may not be non-deterministic if there is no hardware implementation, I would like to at least warn the user during execution.</p>
<p>Lastly, I wanted to make the alphabets used for password generation as extensible as possible, but after implementing them, it seems a little too much for the benefit gained in return. It theoretically allows a user to not have to use numbers or letters, or whatever, but with the benefit of hindsight this doesn't look like a good feature.</p>
<p>PGEN.hpp</p>
<pre><code>#ifndef PGEN_INCLUDES_PGEN_H_
#define PGEN_INCLUDES_PGEN_H_
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <random>
#include <string>
#include <boost/program_options.hpp>
#endif // PGEN_INCLUDES_PGEN_H_
</code></pre>
<p>main.cpp</p>
<pre><code>#include "PGEN.hpp"
namespace Options = boost::program_options;
int main(int argc, char *argv[])
{
/** Program Defaults
*
*/
const auto DefaultPasswordsToCreate = 1;
const auto DefaultPasswordLength = 16;
const std::string DefaultSymbolList = "!@#$`~|\\%^&*()[]-_=+{}';:,<.>/?";
const std::string SimplerSymbolList = "!@#$&?";
/** Program Options
*
*/
bool verbose = false;
/** Password parameters:
*
*/
int N = DefaultPasswordsToCreate;
int PasswordLength = DefaultPasswordLength;
std::string AlphabetUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string AlphabetLower = "abcdefghijklmnopqrstuvwxyz";
std::string AlphabetNumeric = "0123456789";
std::string AlphabetSymbols = DefaultSymbolList;
Options::options_description OptionsDescription("Program Options");
OptionsDescription.add_options()
("help,h", "Display this help message and exit.")
("version", "Print program version information.")
("passwords,n", Options::value<int>(&N)->default_value(DefaultPasswordsToCreate), "Number of passwords to generate.")
("length,l", Options::value<int>(&PasswordLength)->default_value(DefaultPasswordLength), "Length of passwords to generate.")
("symbols", Options::value<std::string>(&AlphabetSymbols)->default_value(DefaultSymbolList), "Pass in custom legal symbols list.")
("simple-symbols", "Use simpler symbol list.")
("verbose,v", "Log additional info to stdout during execution.")
;
Options::variables_map ArgsInput;
Options::store(Options::parse_command_line(argc, argv, OptionsDescription), ArgsInput);
Options::notify(ArgsInput);
if (ArgsInput.count("help"))
{
std::cout << OptionsDescription << std::endl;
return EXIT_SUCCESS;
}
if (ArgsInput.count("version"))
{
std::cout << "[Program Version Information...]" << std::endl;
return EXIT_SUCCESS;
}
if (ArgsInput.count("verbose"))
{
verbose = true;
}
if (ArgsInput.count("symbols"))
{
// TODO: Validate symbol list input.
if (verbose) {
std::cout << "Legal Symbols: " << AlphabetSymbols << std::endl;
}
}
if (ArgsInput.count("simple-symbols"))
{
AlphabetSymbols = SimplerSymbolList;
if (verbose) {
std::cout << "Legal Symbols: " << AlphabetSymbols << std::endl;
}
}
// TODO: Refactor to idiomatic C++.
const auto AlphabetSize = 62 + strlen(AlphabetSymbols.c_str());
char* Alphabet = static_cast<char *>(malloc(sizeof(char) * AlphabetSize));
sprintf(Alphabet, "%s%s%s%s", AlphabetUpper.c_str(), AlphabetLower.c_str(), AlphabetNumeric.c_str(), AlphabetSymbols.c_str());
std::random_device rd;
std::uniform_int_distribution<int> dist(0, AlphabetSize);
for (auto i = 0; i < N; ++i) {
for (auto n = 0; n < PasswordLength; ++n) {
const auto r = dist(rd);
std::cout << Alphabet[r];
}
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
</code></pre>
<p>Directory Structure</p>
<pre><code>PGEN
|-- Makefile
|
|-- src
| |_ main.cpp
|
|__ include
|_ PGEN.hpp
</code></pre>
<p>Makefile</p>
<pre><code>SHELL = /bin/sh
.SUFFIXES:
.SUFFIXES: .cpp .hpp
vpath %.cpp src
vpath %.hpp include
PROGRAM = pgen
all: $(PROGRAM)
$(PROGRAM): main.o
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $^ -lboost_program_options
main.o: main.cpp
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -I include $(TARGET_ARCH) -c -o $@ $^
.PHONY: clean
clean:
rm -rf *.o $(PROGRAM)
</code></pre>
<p>To build I usually used the following:</p>
<pre><code>make CXX=g++ CXXFLAGS="-std=c++17 -Wall -Wextra -pedantic"
</code></pre>
<p>Example:</p>
<pre><code>$ ./pgen
i=2TBdeDK8E8L%xk
$ ./pgen -n 10 -l 24
zE'S9l(6C3r_F8!V6)[Q!ZiW
-2iJVbW3(4@556vL-@v&naM
96T`-Bl3;MkVmAVHogx]|}X
F~~UJ$tpmrZ2Phf2/WEzlY>$
QLfD5m}29%o#E;\-}MM.QiGb
V'Rwv^\)Rw~5zL5X6a'9{;MJ
RO,m`-K&^G=f/^7IK+@>4@7b
F?fdM6)+.Qcmd<&II;R}1ao
xI6-VCv'ct\g2Da;OfhN^-td
Ayai>)'PQ=T,=zyoEg[Fod`G
$ ./pgen -n -10 -l 24 --simple-symbols
z@?IquGoOw8IhqBJCoat4YM0
qjOXC!1o0ZjfHQezxfHyYe2
4#uyBN5oGoWqbmw!eYTNwW@e
I65bEWLHHg8&3WXhtUXIxX6W
i95SuYP0Ab#d0FUUmpIbGGzk
gOF!EHe1!LeaiP#I?UoD$84v
jPLzBFv2IIqp7iQ$z4@ORW$&
d4eM#NeCaxNf?hGroLBgp&E
QPNZ849rKJnDO$rVhFGkfWWZ
0Ch&IzAQN8PjfUFCMBtVwaVC
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T18:43:48.700",
"Id": "416908",
"Score": "1",
"body": "[This](http://www.pcg-random.org/) might be of help to you."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T09:59:03.727",
"Id": "215490",
"Score": "2",
"Tags": [
"c++",
"random"
],
"Title": "Password Generation Using Cryptographically Strong Random Number Generation"
} | 215490 |
<p>Am I doing this right? I do not know how to properly connect functions with pagination. To make everything work, I have to duplicate this variables. When I add variables to the function and to the index, then everything works.</p>
<pre><code>$rowperpage = 10;
$page = $_GET['page'] ?? 1;
$page = $page - 1;
$p = $page * $rowperpage;
</code></pre>
<p><strong>Function</strong></p>
<pre><code>function find_all_products_by_cat_id2($cat_id, $options=[]) {
global $db;
$visible = $options['visible'] ?? false;
$rowperpage = 10;
$page = $_GET['page'] ?? 1;
$page = $page - 1;
$p = $page * $rowperpage;
$sql = "SELECT * FROM products ";
$sql .= "WHERE cat_id='" . db_escape($db, $cat_id) . "' ";
if($visible) {
$sql .= "AND visible = true ";
}
$sql .= "ORDER BY prod_name ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage." ";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;
</code></pre>
<p><strong>index.php</strong></p>
<pre><code><?php
$rowperpage = 10;
$page = $_GET['page'] ?? 1;
$page = $page - 1;
$p = $page * $rowperpage;
$category_id = $_GET['id'] ?? 1;
$products_count = count_products_by_cat_id($category_id, ['visible' => true]);
if(isset($_GET['id'])) {
$category_id = $_GET['id'];
$product_set = find_all_products_by_cat_id2($category_id, ['visible' => true]);
if(!$product_set) {
redirect_to(url_for('/index.php'));
}
$product_count = mysqli_num_rows($product_set);
if($product_count == 0) {
echo "<h1>No more products</h1>";
}
?>
</code></pre>
<p>I think I found a solution. </p>
<p><strong>Update 1</strong><br>
<strong>Function</strong></p>
<pre><code> function find_by_sql($sql) {
global $db;
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;
}
</code></pre>
<p><strong>index.php</strong></p>
<pre><code>$visible = $options['visible'] ?? false;
$sql = "SELECT * FROM products ";
$sql .= "WHERE cat_id='" . db_escape($db, $category_id) . "' ";
if($visible) {
$sql .= "AND visible = true ";
}
$sql .= "ORDER BY prod_name ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage." ";
$product_set = find_by_sql($sql, ['visible' => true]);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T11:07:13.820",
"Id": "416804",
"Score": "0",
"body": "\"Am I doing this right?\" Most importantly, does it work? You say it works when you add variables to the function and the index, does that suffice for your application? Sure, you're looking for something better, but the current code does at least the bare minimum of what is required?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T11:23:58.673",
"Id": "416808",
"Score": "0",
"body": "Its work, I think I found a solution. Check please Update1"
}
] | [
{
"body": "<p>Assuming you have a BOOL/BOOLEAN column called <code>visible</code>, you might consider using a more recognized syntax like <code>visible <> 0</code> or <code>visible = 0</code> as advised here: <a href=\"https://stackoverflow.com/a/24801220/2943403\">MySQL: “= true” vs “is true” on BOOLEAN. When is it advisable to use which one? And Which one is vendor independent?</a> After all, <a href=\"https://dev.mysql.com/doc/refman/5.6/en/numeric-type-overview.html\" rel=\"nofollow noreferrer\">BOOLEAN columns are really just TINYINT columns</a>.</p>\n\n<p>I have to assume that <code>confirm_result_set($result);</code> is fetching the rows and preparing them in some manner. Perhaps you'd like to adjust the variable name to be more intuitive/descriptive.</p>\n\n<p>Some developers, myself included, do not recommend the use of <code>global</code> as a means of transferring variables into a function's scope. IMO, it is cleaner to pass the connection variable as a parameter in the function call (like you do with <code>$sql</code>).</p>\n\n<p>I don't know what <code>db_escape()</code> is doing, but the surest advice is to urge you to use prepared statements with placeholders. As a less classy alternative, so long as <code>$category_id</code> is an integer, you can cast it as an integer (<code>(int)$category_id</code>) before using it in your query. Joomla, for instance, doesn't offer prepared statements yet (available in the next major version) so they use integer/float casting for security on numeric values. Also, numeric values do not need to be quoted in queries.</p>\n\n<p><code>ASC</code> is not necessary in your query, it is the default sorting direction and can be omitted.</p>\n\n<p>The LIMIT clause string can be written without concatenation: <code>$sql .= \"LIMIT $p, $rowperpage\";</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T08:49:15.200",
"Id": "419961",
"Score": "0",
"body": "`function db_escape($connection, $string) {\n return mysqli_real_escape_string($connection, $string);\n }`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T04:30:03.313",
"Id": "215721",
"ParentId": "215492",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215721",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T10:13:38.260",
"Id": "215492",
"Score": "1",
"Tags": [
"php"
],
"Title": "Php how to properly connect functions with pagination"
} | 215492 |
<h2>Introduction</h2>
<p>This is my first attempt to mess with memory allocation using C and create something close to a python dictionary. Coming from a high level programming language like Python or Java, I am not really used to correctly handling low level code. I tried to follow C conventions/style but I can tell I already failed that since I lack the discipline required.</p>
<h2>About the Implementation</h2>
<p>This is a fixed sized hash-table combined with a linked list. So in case of a collision I just try to append a node at the same index. The methods implemented are :</p>
<ul>
<li><strong><code>hset</code></strong>: sets key + value</li>
<li><strong><code>hget</code></strong>: gets value based on key</li>
<li><strong><code>hdel</code></strong>: deletes key + value based on key</li>
<li><strong><code>display</code></strong>: displays the whole table (mostly for debugging)</li>
</ul>
<h2>Code</h2>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASH_TABLE_SIZE 255
#define DEBUG_HASH_INDEX 0 // for debugging with predictable indexes
typedef struct HashItem HashItem;
struct HashItem {
char * key;
char * value;
HashItem * tail;
};
void freeNode(struct HashItem * node);
void initialize_hash_table(HashItem * hash_table[]) {
for (int i=0; i<HASH_TABLE_SIZE; i++) {
hash_table[i] = NULL;
}
}
unsigned long get_hash_index(char *str) {
if (DEBUG_HASH_INDEX) return 4; // https://xkcd.com/221/
// http://www.cse.yorku.ca/~oz/hash.html
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash % HASH_TABLE_SIZE;
}
char * hget(HashItem * hash_table[], char * key) {
unsigned long idx = get_hash_index(key);
struct HashItem * node = hash_table[idx];
while (node != NULL) {
if (strcmp(key, node->key) == 0){
// if it has the same key we update the value
return node->value;
}
node = node->tail;
}
return NULL;
}
void Hdel(HashItem * hash_table[], char * key) {
unsigned long idx = get_hash_index(key);
struct HashItem * head = hash_table[idx];
if (strcmp(key, head->key) == 0){
// if it has the same key we update the value
if (head->tail != NULL){
hash_table[idx] = head->tail;
} else {
hash_table[idx] = NULL;
}
freeNode(head);
return;
}
}
void hset(HashItem * hash_table[], char * key, char * value) {
unsigned long idx = get_hash_index(key);
if (hash_table[idx] == NULL) {
// idx is empty
struct HashItem * new_pair = (struct HashItem*) malloc(sizeof(HashItem));
new_pair->key = key;
new_pair->value = value;
new_pair->tail = NULL;
hash_table[idx] = new_pair;
} else {
// idx is not empty
if (strcmp(key, hash_table[idx]->key) == 0){
// if it has the same key we update the value
hash_table[idx]->value = value;
} else {
// we insert it in the tail
struct HashItem * node = hash_table[idx];
while (1) {
if (node->tail == NULL) {
struct HashItem * new_pair = (struct HashItem*) malloc(sizeof(HashItem));
new_pair->key = key;
new_pair->value = value;
new_pair->tail = NULL;
node->tail = new_pair;
break;
}
if (strcmp(key, node->tail->key) == 0) {
node->tail->value = value;
break;
}
node = node->tail;
} // end while
} // end else
}
}
void display(HashItem * hash_table[]) {
// displays the key/values alongside their idx
struct HashItem * node;
int inner;
for (int idx = 0; idx < HASH_TABLE_SIZE; idx++) {
if (hash_table[idx] != NULL) {
printf("DISP idx: %d/0 | key: %s | value: %s\n", idx, hash_table[idx]->key, hash_table[idx]->value);
node = hash_table[idx]->tail;
inner = 1;
while (node != NULL) {
printf("DISP idx: %d/%d | key: %s | value: %s\n", idx, inner, node->key, node->value);
inner++;
node = node->tail;
}
}
}
}
void freeNode(struct HashItem * node) {
free(node->key);
free(node->value);
free(node);
node = NULL;
}
void freeInnerNodes(struct HashItem * node) {
if (node == NULL) return;
if (node->tail != NULL) freeInnerNodes(node->tail);
printf("FREE | key: %s | value: %s\n", node->key, node->value);
freeNode(node);
}
void freeHashTable(HashItem * hash_table[]) {
for (int idx = 0; idx < HASH_TABLE_SIZE; idx++) {
if (hash_table[idx] != NULL) {
freeInnerNodes(hash_table[idx]);
}
}
}
static char *rand_string(char *str, size_t size) {
const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJK...";
if (size) {
--size;
for (size_t n = 0; n < size; n++) {
int key = rand() % (int) (sizeof charset - 1);
str[n] = charset[key];
}
str[size] = '\0';
}
return str;
}
char* rand_string_alloc(size_t size) {
char *s = malloc(size + 1);
if (s) {
rand_string(s, size);
}
return s;
}
int main() {
struct HashItem* HASH_TABLE[HASH_TABLE_SIZE];
char * randkey = rand_string_alloc(12);
initialize_hash_table(HASH_TABLE);
hset(HASH_TABLE, randkey, rand_string_alloc(12));
for (int i = 0; i < 5; i++) {
hset(HASH_TABLE, rand_string_alloc(12), rand_string_alloc(12));
}
display(HASH_TABLE);
Hdel(HASH_TABLE, randkey);
display(HASH_TABLE);
freeHashTable(HASH_TABLE);
return 0;
}
</code></pre>
| [] | [
{
"body": "<h1>General</h1>\n<p>Good work for a C newcomer! Welcome to the club!</p>\n<p>Thank you for providing a good test program, and for the macro to exercise the list code - that really helps give confidence in the implementation. The tests do have some limitations, since they only test inserting elements and freeing the entire table; there's no tests of lookup, updating values or removing single entries, for example. Tests of removal should remove elements from beginning, end and interior of lists, and of singleton lists.</p>\n<p>The code compiles almost cleanly (just a single warning) and appears not to leak, double-free, or access inaccessible memory:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -std=c17 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion 215494.c -o 215494\n215494.c: In function ‘get_hash_index’:\n215494.c:34:35: warning: conversion to ‘long unsigned int’ from ‘int’ may change the sign of the result [-Wsign-conversion]\n hash = ((hash << 5) + hash) + c; /* hash * 33 + c */\n ^\nmake TOOL='valgrind --leak-check=full' 215494.run\nmake[1]: Entering directory '/home/tms/stackexchange/review'\nulimit -v 1048576 -t 60; exec \\\nvalgrind --leak-check=full ./215494 \n==17736== Memcheck, a memory error detector\n==17736== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.\n==17736== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info\n==17736== Command: ./215494\n==17736== \nDISP idx: 11/0 | key: sDhHqlcDnv. | value: hDwkwdBpjcw\nDISP idx: 69/0 | key: HwkKbzfehqz | value: yr.eJkngluK\nDISP idx: 88/0 | key: xgrJHpAmjvc | value: BktdguAmqli\nDISP idx: 108/0 | key: jF.rlbJDhhq | value: mKvagbzjeta\nDISP idx: 149/0 | key: tJkIsBbrw.m | value: I.muKitmAAo\nDISP idx: 235/0 | key: edEhiKsCydl | value: gjHrepwzohI\nDISP idx: 11/0 | key: sDhHqlcDnv. | value: hDwkwdBpjcw\nDISP idx: 69/0 | key: HwkKbzfehqz | value: yr.eJkngluK\nDISP idx: 108/0 | key: jF.rlbJDhhq | value: mKvagbzjeta\nDISP idx: 149/0 | key: tJkIsBbrw.m | value: I.muKitmAAo\nDISP idx: 235/0 | key: edEhiKsCydl | value: gjHrepwzohI\nFREE | key: sDhHqlcDnv. | value: hDwkwdBpjcw\nFREE | key: HwkKbzfehqz | value: yr.eJkngluK\nFREE | key: jF.rlbJDhhq | value: mKvagbzjeta\nFREE | key: tJkIsBbrw.m | value: I.muKitmAAo\nFREE | key: edEhiKsCydl | value: gjHrepwzohI\n==17736== \n==17736== HEAP SUMMARY:\n==17736== in use at exit: 0 bytes in 0 blocks\n==17736== total heap usage: 19 allocs, 19 frees, 1,324 bytes allocated\n==17736== \n==17736== All heap blocks were freed -- no leaks are possible\n==17736== \n==17736== For counts of detected and suppressed errors, rerun with: -v\n==17736== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)\n</code></pre>\n<p>Let's fix the warning:</p>\n<pre><code> hash = hash * 33 + (unsigned)c;\n</code></pre>\n<p>Note that I've eliminated the need for the comment: multiplying by a constant is an operation that compilers are very good at optimising, and you should expect to see the same object code from both versions. It doesn't help performance to write it less clearly.</p>\n<h1>Private helpers</h1>\n<p>We should use <code>static</code> for the internal functions that are not part of the public interface. This will be important when we compile the implementation separately so that we can link with other code.</p>\n<h1>Const correctness</h1>\n<p>Consider which pointer arguments point to data that should not be modified, and add <code>const</code> where appropriate:</p>\n<pre><code>static unsigned long get_hash_index(char const *str) {\n</code></pre>\n<p>(or <code>const char *</code>; the order of the keywords doesn't matter, but the position relative to <code>*</code> does matter).</p>\n<h1>Allocations</h1>\n<p>We correctly test the result of <code>malloc()</code> here:</p>\n<blockquote>\n<pre><code> char *s = malloc(size + 1);\n if (s) {\n rand_string(s, size);\n }\n return s;\n</code></pre>\n</blockquote>\n<p>But we use it without checking in other locations, such as:</p>\n<blockquote>\n<pre><code>struct HashItem * new_pair = (struct HashItem*) malloc(sizeof(HashItem));\nnew_pair->key = key;\nnew_pair->value = value;\n</code></pre>\n</blockquote>\n<p>That's Undefined behaviour waiting to bite. When we fix that, we'll need to change the function interface so that we can report the failure to the calling code.</p>\n<p>BTW, there's no need to cast the result of <code>malloc()</code> like that; pointers to <code>void</code> can be assigned to variables of any pointer type.</p>\n<p>I'd recommend re-writing that as</p>\n<pre><code>struct HashItem *new_pair = malloc(sizeof *new_pair);\nif (!new_pair) {\n return ERROR_VALUE; /* use your preferred error type/value here */\n}\nnew_pair->key = key;\nnew_pair->value = value;\n</code></pre>\n<h1>Avoid <code>while (1)</code></h1>\n<p>I think we can refactor <code>hset()</code> to replace the indefinite loop with a definite one, by reversing the sense of the <code>if</code> test:</p>\n<pre><code>bool hset(HashItem *hash_table[], char const *key, char const *value)\n{\n unsigned long idx = get_hash_index(key);\n\n /* search the list for matching key */\n for (struct HashItem *node = hash_table[idx]; node; node = node->tail) {\n if (strcmp(key, node->key) == 0) {\n node->value = value;\n return true; /* success */\n }\n }\n\n /* not found - insert at head */\n struct HashItem *new_pair = malloc(sizeof *new_pair);\n if (!new_pair) {\n return false; /* failed! */\n }\n\n new_pair->key = key;\n new_pair->value = value;\n new_pair->tail = hash_table[idx];\n hash_table[idx] = new_pair;\n return true;\n}\n</code></pre>\n<p>Inserting at the head also eliminates the special case of the empty list - the <code>for</code> loop is empty in that case and we just drop through to the insertion code.</p>\n<h1>Prefer iteration to recursion</h1>\n<p><code>freeInnerNodes()</code> will recurse as deeply as the list is long. We can easily avoid that, by iterating through the list instead:</p>\n<pre><code>void freeInnerNodes(struct HashItem * node)\n{\n while (node) {\n struct HashItem *next = node->tail;\n freeNode(node);\n node = next;\n }\n}\n</code></pre>\n<h1>Don't assign to variables going out of scope</h1>\n<p>Very minor, but the last line of this function is completely pointless:</p>\n<blockquote>\n<pre><code>void freeNode(struct HashItem * node) {\n free(node->key);\n free(node->value);\n free(node);\n node = NULL;\n}\n</code></pre>\n</blockquote>\n<p>No other code can access the variable <code>node</code>, so the assignment achieves nothing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T18:58:59.617",
"Id": "416919",
"Score": "0",
"body": "1) The difference in the allocations part is that the first piece of code, I copied it of stack overflow, while the second one I wrote it myself :D\n\n2) in order for me to iterate when freeing memory instead of using recursion, I would have to know where the tail starts for each table, so I would have to iterate to get there, then \"reverse\" iterate to free each node. Wouldn't that be inefficient ? \n\n3) I see you are using gcc with a bunch of flags then ulimit ? and at the end valgrind. I just used gcc hash_table.c . Where can I find information about your way of compiling ?\n\nThanks you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T08:52:59.993",
"Id": "417227",
"Score": "1",
"body": "I've edited to show how to iterate over the nodes, deleting as we go (the trick is to store the `tail` pointer before removing the node). The GCC flags are mostly to enable plenty of warnings; they are explained very well in the manual (`-g` includes debug symbols, so we get line numbers in any backtraces; `-fPIC` is probably not required). The `ulimit` is just [my standard way](q/165861) of running code from Stack Exchange (it helps prevent out-of-control test programs getting obstructing $DAY_JOB by competing for resources)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T14:32:46.253",
"Id": "215509",
"ParentId": "215494",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "215509",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T10:36:16.113",
"Id": "215494",
"Score": "9",
"Tags": [
"algorithm",
"c",
"reinventing-the-wheel",
"hash-map"
],
"Title": "HashTable using C"
} | 215494 |
<p>I want to add custom punctuations in a given string.</p>
<p>eg:</p>
<pre><code>US 8012999 B2 --> US 8,012,999 B2
US 20170107206 A1 --> US 20170107206 A1
EP 2795605 B1 --> EP 2 795 605 B1
US 09700674 --> US 09/700,674
</code></pre>
<p>This is what I wrote</p>
<pre><code>def punctuate(text, punctuations):
"""Given text and list of tuple(index, puncuation)
returns punctuated text"""
char_list = list(text)
k = 0
for i, char in punctuations:
char_list.insert(i + k, char)
k += 1
return "".join(char_list)
In [53]: punctuate('US 8012999 B2', [(4, ','), (7, ',')])
Out[53]: 'US 8,012,999 B2'
In [54]: punctuate('US 20170107206 A1', [(7, '/')])
Out[54]: 'US 2017/0107206 A1'
In [55]: punctuate('US 09700674', [(5, '/'), (8, ',')])
Out[55]: 'US 09/700,674'
In [56]: punctuate('EP 2795605 B1', [(4, ' '), (7, ' ')])
Out[56]: 'EP 2 795 605 B1'
</code></pre>
<p>This works fine. Is this the best way to do it?
The punctuations list will always be sorted one starting from lower to higher index.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T15:29:04.417",
"Id": "416863",
"Score": "0",
"body": "Yeah, always. For now. I also thought of sorting it first regardless but it will again unnecessarily complicate thing here by creating x,y problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:24:32.493",
"Id": "416871",
"Score": "0",
"body": "Added. Thanks.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:30:05.490",
"Id": "416872",
"Score": "2",
"body": "What is the reason for this code? what is the business requirement? Why do you need to add punctuations like this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T17:31:28.380",
"Id": "416893",
"Score": "0",
"body": "These are the punctuations used by USPTO and EPO."
}
] | [
{
"body": "<p>Knowing the context of a task is needed to determine whether this is the best way. At least, you would do refactoring of the existing solution.</p>\n\n<pre><code>def punctuate(text, punctuations):\n if not punctuations:\n return text\n i, char = punctuations.pop()\n return punctuate(text[:i], punctuations) + char + text[i:]\n</code></pre>\n\n<p>Less code and better performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T15:15:34.760",
"Id": "416857",
"Score": "0",
"body": "I actually can't easily guess what's going on while looking at recursive solution. I have to see it on pythontutor. This is excellent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T15:25:43.627",
"Id": "416860",
"Score": "4",
"body": "Welcome to CR numrut. Could you please specify why the recursive solution is better? I don't think mutating punctuations and recusing for this is a good idea."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T14:43:05.897",
"Id": "215510",
"ParentId": "215501",
"Score": "0"
}
},
{
"body": "<p>Here is a solution using a generator, which gives you linear time. Your current solution is not linear, because <code>list.insert</code> is already <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>.</p>\n\n<pre><code>def interweave(x, y):\n \"\"\"\n Given an iterable `x` and an iterable `y` of indices and items, \n yield from `x`, but interweave the items from `y` at the given indices.\n \"\"\"\n y = iter(y)\n next_i, next_y = next(y, (-1, \"\"))\n for i, next_x in enumerate(x):\n if i == next_i:\n yield next_y\n next_i, next_y = next(y, (-1, \"\")) # default value for when y is exhausted\n yield next_x\n\ndef punctuate(text, punctuations):\n return \"\".join(interweave(text, punctuations))\n</code></pre>\n\n<p>It passes all the given testcases:</p>\n\n<pre><code>In [98]: punctuate('US 8012999 B2', [(4, ','), (7, ',')])\nOut[98]: 'US 8,012,999 B2'\n\nIn [99]: punctuate('US 20170107206 A1', [(7, '/')])\nOut[99]: 'US 2017/0107206 A1'\n\nIn [100]: punctuate('US 09700674', [(5, '/'), (8, ',')])\nOut[100]: 'US 09/700,674'\n\nIn [101]: punctuate('EP 2795605 B1', [(4, ' '), (7, ' ')])\nOut[101]: 'EP 2 795 605 B1'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T03:56:39.957",
"Id": "416972",
"Score": "0",
"body": "Thanks. It took time for me to fully understand it. This is amazing and also fast. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:39:45.937",
"Id": "215517",
"ParentId": "215501",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215517",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T12:25:13.907",
"Id": "215501",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"formatting"
],
"Title": "Adding punctuation to US and European patent numbers"
} | 215501 |
<h2>Problem</h2>
<blockquote>
<p>Given an array and a number <span class="math-container">\$t\$</span>, write a function that determines if there exists a contiguous sub-array whose sum is <span class="math-container">\$t\$</span>.</p>
</blockquote>
<p><a href="https://brilliant.org/practice/arrays-intermediate/?p=3" rel="nofollow noreferrer">Source</a> (Note that the URL may not link to the exact problem as it's from a quiz site, and questions seem to be randomly generated).</p>
<p>I was able to come up with a <span class="math-container">\$O(n^2)\$</span> solution, and further thinking hasn't improved upon it:</p>
<pre class="lang-py prettyprint-override"><code>def substring_sum(lst, target):
sums = []
for val in lst:
if val == target:
return True
for idx, _ in enumerate(sums):
sums[idx] += val
if sums[idx] == target:
return True
sums.append(val)
return False
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T15:17:00.783",
"Id": "416858",
"Score": "4",
"body": "Hey Tobi, if you're not sure the URL doesn't link to the right problem, don't put it in your post. It would be better to give some examples of the problem."
}
] | [
{
"body": "<p>You are currently calculating the sum of all possible subarrays. A different approach is to imagine a sliding window on the array. If the sum of the elements in this window is smaller than the target sum, you extend the window by one element, if the sum is larger, you start the window one element later. Obviously, if the sum of the elements within the window is the target, we are done.</p>\n\n<p>This algorithm only works if the array contains only non-negative numbers (as seems to be the case here when looking at the possible answers).</p>\n\n<p>Here is an example implementation:</p>\n\n<pre><code>def contiguous_sum(a, target):\n start, end = 0, 1\n sum_ = sum(a[start:end])\n # print(start, end, sum_)\n while sum_ != target and start < end < len(a):\n if sum_ < t:\n end += 1\n else:\n start += 1\n if start == end:\n end += 1\n sum_ = sum(a[start:end])\n # print(start, end, sum_)\n return sum_ == target\n</code></pre>\n\n<p>This algorithm can be further improved by only keeping a running total, from which you add or subtract:</p>\n\n<pre><code>def contiguous_sum2(a, t):\n start, end = 0, 1\n sum_ = a[0]\n #print(start, end, sum_)\n while sum_ != t and start < end < len(a):\n if sum_ < t:\n sum_ += a[end]\n end += 1\n else:\n sum_ -= a[start]\n start += 1\n if start == end:\n sum_ += a[end]\n end += 1\n #print(start, end, sum_)\n return sum_ == t\n</code></pre>\n\n<p>The implementation can be streamlined further by using a <code>for</code> loop, since we actually only loop once over the input array, as <a href=\"https://codereview.stackexchange.com/questions/215505/brilliant-org-arrays-intermediate-3-contiguous-knapsack/215516?noredirect=1#comment416876_215516\">recommended in the comments</a> by <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">@Peilonrayz</a>:</p>\n\n<pre><code>def contiguous_sum_for(numbers, target):\n end = 0\n total = 0\n for value in numbers:\n total += value\n if total == target:\n return True\n while total > target:\n total -= numbers[end]\n end += 1\n return False\n</code></pre>\n\n<p>All three functions are faster than your algorithm for random arrays of all lengths (containing values from 0 to 1000 and the target always being 100):</p>\n\n<p><a href=\"https://i.stack.imgur.com/aXSyt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aXSyt.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:05:05.143",
"Id": "416868",
"Score": "0",
"body": "You don't need the deque. Just keep the running sum, and subtract items as you remove them from the tail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:07:05.313",
"Id": "416869",
"Score": "0",
"body": "@AustinHastings: True, you know the index of the item to subtract..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:23:35.083",
"Id": "416870",
"Score": "1",
"body": "@AustinHastings: Added a version without summing the slice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:48:34.693",
"Id": "416876",
"Score": "2",
"body": "Unless I'm missing something [using a for loop would read better imo](https://gist.github.com/Peilonrayz/7796a1e96818779693436bfb1de64f7f)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:49:31.227",
"Id": "416877",
"Score": "0",
"body": "@Peilonrayz: True. Do you want to add it as your own answer, don't have time for it right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:50:44.307",
"Id": "416878",
"Score": "0",
"body": "@Graipher I've not tested it, and don't want to write my own answer. Add it to yours if/when you want :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T07:32:12.787",
"Id": "416994",
"Score": "0",
"body": "How did you do the time graph? That sounds like a very handy utility to have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T08:26:49.217",
"Id": "417223",
"Score": "0",
"body": "@TobiAlafin: It is using the code in [my question here](https://codereview.stackexchange.com/questions/165245/plot-timings-for-a-range-of-inputs) (and it's answers)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:01:27.710",
"Id": "215516",
"ParentId": "215505",
"Score": "7"
}
},
{
"body": "<p>It is possible to do better than the <span class=\"math-container\">\\$O(n^2)\\$</span> of my original solution and solve it in linear time by using a set to store the sums at each point and comparing if the sum at this point minus the target is in the set. However this solution uses <span class=\"math-container\">\\$O(n)\\$</span> space: </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def substring_sum(lst, target):\n sm = 0\n sums = {sm}\n for val in lst:\n sm += val\n if sm - target in sums:\n return True\n sums.add(sm)\n return False \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T07:38:44.290",
"Id": "215559",
"ParentId": "215505",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "215516",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T14:12:22.940",
"Id": "215505",
"Score": "1",
"Tags": [
"python",
"performance",
"beginner",
"algorithm",
"programming-challenge"
],
"Title": "(Brilliant.org) Arrays Intermediate 3: Contiguous Knapsack"
} | 215505 |
<p>I needed to substitute variables of the syntax <code>{FIRST_NAME}</code> in a HTML template. The problem is that the template comes from a WYSIWYG system, and so the placeholders may be intermixed with HTML tags. For example in the following input, the <code>{SECOND_NAME}</code> placeholder should also be substituted, and the formatting tags in-between should be retained.</p>
<pre><code>{FIRST_NAME}
<style>
span.second-name {
color: #f00;
}
</style>
{</span><span style="style01">SECOND_NAME}
</code></pre>
<p>I chose to implement a state machine that scans the template character-by-character, differentiating between text content, tag code and quoted attribute value, and used that to move the HTML tags before the variable value. The transform retains placeholders with unknown variables.</p>
<p>For the example above, the result will be</p>
<pre><code>John
<style>
span.second-name {
color: #f00;
}
</style>
</span><span style="style01">Doe
^ notice the HTML tag lands before the value
</code></pre>
<p>assuming <code>FIRST_NAME</code> is <code>John</code> and <code>SECOND_NAME</code> is <code>Doe</code>.</p>
<p><strong>The code</strong></p>
<pre><code>using System.Collections.Generic;
using System.Text;
namespace Foo
{
// Scans for variables in the {FIRST_NAME} syntax while taking care of HTML tags. For example,
// if FIRST_NAME is “Jan”, then {</span><span>FIRST_NAME} gets translated to </span><span>Jan.
// HTML tags are moved to the beginning of the placeholder. The scanner probably does not handle
// exotic HTML syntax, but idc.
//
// This class is not multithreading safe, and an instance should not be shared between threads.
//
// Usage: var output = new HtmlScanner().Walk(input, new Dictionary<string, string> { ... });
// Remember to encode your variables!
internal sealed class HtmlVariableParser
{
// The scanner basically works like a state machine. For each input character, the
// machine can change to a different state, or change the current state unchanged.
// There are three possible states: TEXT, TAG and QUOTE. TEXT is usual text content,
// TAG is inside an attribute and QUOTE is inside a quoted attribute value.
private enum HtmlScannerState
{
Text,
Tag,
Quote,
}
// Are we inside braces?
private bool fInsideBraces;
// The output string.
private StringBuilder fResult = new StringBuilder();
// While scanning characters inside { }, we separate input fragments that are HTML tags
// from fragments that are normal text. The former is stored in fTagsCollector and the
// latter is stored inside fVariableKey.
private string fTagsCollector = "";
private string fVariableKey = "";
// The original string between { and }, with order retained.
private string fOriginalBraceString = "";
// User-provided variables.
private IDictionary<string, string> fVariables;
private char fLastQuoteChar;
public string Substitute(string html, IDictionary<string, string> variables)
{
fResult = new StringBuilder();
fOriginalBraceString = fVariableKey = fTagsCollector = "";
fVariables = variables;
var state = HtmlScannerState.Text;
for (var cursor = 0; cursor < html.Length; cursor++)
{
var c = html[cursor];
var previous = state;
state = Transition(state, c);
Step(previous, state, c);
}
return fResult.ToString();
}
private void Step(HtmlScannerState previous, HtmlScannerState state, char c)
{
var wasInsideBraces = fInsideBraces;
RecheckInsideBraces(state, c);
if (fInsideBraces && wasInsideBraces)
{
AppendToBuffer(state, c);
}
// We are at the end of a placeholder.
else if (wasInsideBraces && !fInsideBraces)
{
Commit();
}
else if (!fInsideBraces)
{
fResult.Append(c);
}
}
// If the variable is found, the substitute it; otherwise insert back the braces and the
// text between them.
private void Commit()
{
bool variableExists = fVariables.ContainsKey(fVariableKey);
if (variableExists)
{
// Insert the collected tag fragments before the variable value.
fResult.Append(fTagsCollector);
fResult.Append(fVariables[fVariableKey]);
}
else
{
// If the variable was not found, do not replace anything. This is the desired
// behavior, because braces frequently occur in <style> or <script> tags, and
// we should not touch them.
fResult.Append("{" + fOriginalBraceString + "}");
}
Reset();
}
private void Reset()
{
fTagsCollector = "";
fVariableKey = "";
fOriginalBraceString = "";
}
private void AppendToBuffer(HtmlScannerState state, char c)
{
// Is the current char a part of a tag?
var partOfTag =
state == HtmlScannerState.Tag
|| state == HtmlScannerState.Quote
|| state == HtmlScannerState.Text && c == '>';
if (partOfTag && fInsideBraces)
{
fTagsCollector += c;
}
else
{
fVariableKey += c;
}
fOriginalBraceString += c;
}
private void RecheckInsideBraces(HtmlScannerState state, char c)
{
// Update fInsideBraces.
if (state == HtmlScannerState.Text && c == '{')
{
fInsideBraces = true;
}
if (state == HtmlScannerState.Text && c == '}')
{
fInsideBraces = false;
}
}
private HtmlScannerState Transition(HtmlScannerState state, char c)
{
switch (state)
{
// If we are in the TEXT state, and the character is a left angle bracket, then
// we're at the beginning of a tag, and transition to the TAG state.
case HtmlScannerState.Text:
if (c == '<') state = HtmlScannerState.Tag;
break;
// If we are inside a TAG and encounter a right angle bracket, this means the tag
// is being closed.
case HtmlScannerState.Tag:
if (c == '>') state = HtmlScannerState.Text;
if (c == '"' || c == '\'')
{
// Save the kind of quote we encountered, so that <img title="Kant Can't">
// doesn't blow up the scanner, and transition to QUOTE.
fLastQuoteChar = c;
state = HtmlScannerState.Quote;
}
break;
case HtmlScannerState.Quote:
// A quoting character ends the string, but only if it is the same as
if (c == fLastQuoteChar) state = HtmlScannerState.Tag;
break;
}
return state;
}
}
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T14:23:29.507",
"Id": "416845",
"Score": "0",
"body": "What is the `f` prefix for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T14:28:29.053",
"Id": "416846",
"Score": "0",
"body": "Fields. I see `_` is more popular, but it doesn't work too good with my fingers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:59:02.470",
"Id": "422999",
"Score": "0",
"body": "It's hard to imagine that any WYSYWIG is creating code like this `{</span><span style=\"style01\">SECOND_NAME}` the opening `{` is completely off. Shouldn't it be `<span style=\"style01\">{SECOND_NAME}</span>` - it otherwise doesn't make any sense to use the `{}` for enclosing parameter names as their position seem to be pretty random :-\\"
}
] | [
{
"body": "<p>Seems like a lot of work. Can you do something more simple like finding the position of the placeholder in the text, and just removing the nearest 2 brackets?</p>\n\n<pre><code>public string ReplaceToken(string inputText, string token, string value)\n{\n var tokenIndex = inputText.IndexOf(token);\n int? openingIndex = null, closingIndex = null;\n\n for (int i = 0, o = tokenIndex - 1, c = tokenIndex + 1; i < 500; i++, o--, c++)\n { \n if (!openingIndex.HasValue && inputText[o] == '{')\n openingIndex = o;\n\n if (!closingIndex.HasValue && inputText[c] == '}')\n closingIndex = c;\n\n if (openingIndex.HasValue && closingIndex.HasValue)\n break;\n }\n\n return new StringBuilder(inputText)\n .Remove(closingIndex.Value, 1)\n .Remove(tokenIndex, token.Length)\n .Insert(tokenIndex, value)\n .Remove(openingIndex.Value, 1)\n .ToString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T23:41:01.907",
"Id": "215888",
"ParentId": "215507",
"Score": "2"
}
},
{
"body": "<p>I agree with @Matt-Cole here. This seems pretty complicated to solve a WYSIWYG output problem. I would make sure this is the right solution to the problem and the one that adds the least amount of complexity to your system.</p>\n\n<p>I don't know which WYSIWYG editor/system is being used. But, if you have access to it you might want to look into solving it there. This posts has <a href=\"https://ux.stackexchange.com/questions/53904/whats-the-best-way-to-present-variables-in-a-wysiwyg-editor\"> variable representation suggestions for WYSIWYG editors</a>. Most common seems to be to using double brackets like <code>[[FIRST_NAME]]</code> or <code>{{FIRST_NAME}}</code>.</p>\n\n<p>If you absolutely must solve the problem by modifying the string then use @Matt-Cole's code to write your solution. Though I don't feel comfortable to set max iteration to 500 not knowing the bounds of the string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T21:57:02.337",
"Id": "421432",
"Score": "1",
"body": "Welcome to Code Review and thank you for contributing! A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](https://meta.stackexchange.com/a/8259/341145) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-21T00:26:20.973",
"Id": "421439",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I added a bit more clarity. Is the answer now useful without the link? I up voted a previous answer because I think that solves complexity withing the solution. But, I wanted to point out that using this approach to solve what interpret as the problem may not be the best solution. If I'm missing the mark, do you have a suggestion on how I can communicate that better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:47:08.977",
"Id": "440638",
"Score": "0",
"body": "That WYSIWYG system is MS Word. Support for Word documents is required by the business."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T18:46:37.730",
"Id": "217790",
"ParentId": "215507",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T14:21:05.083",
"Id": "215507",
"Score": "1",
"Tags": [
"c#",
"parsing"
],
"Title": "Substituting variable placeholders that may be intermixed with HTML tags"
} | 215507 |
<p>I have been trying to implement good 'OOP' and coding standards, but I always end up with bloated controllers. How could I clean this controller method?</p>
<pre><code>public function updatePositions(Request $request)
{
MenuItem::setNewOrder($request->positions);
$item = MenuItem::findOrFail($request->itemId);
if (!is_array($request->path)) {
return response()->json('Invalid data', 400);
}
if (count($request->path) === 1) {
if ($item->parent()->exists()) {
$item->parent()->dissociate();
$item->save();
}
} else {
$potentialParent = $item->sort_order - last($request->path) - 1;
$previousRecord = MenuItem::where('sort_order', $potentialParent)->first();
$item->parent()->associate($previousRecord);
$item->save();
}
}
</code></pre>
<ul>
<li><p>it sets a completely new order for the MenuItem at hand, which I think in itself my be a method?</p></li>
<li><p>it checks if the $request->path is an array and returns a formatted json response, <strong>should this throw an exception?</strong></p></li>
<li><p>It then checks the length of $request->path and disassociates a relation model or if the length is greater then 1, it associates a relationship object after finding that.</p></li>
</ul>
<p>Any advice in the good direction is welcome here.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:53:33.817",
"Id": "416879",
"Score": "0",
"body": "More context would be useful. Could you clarify what exactly is a `Request` and a `MenuItem`? What class does this method appear in, and what else is in the class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T21:32:27.893",
"Id": "416955",
"Score": "1",
"body": "How many times do you check this `return response()->json('Invalid data', 400);` - I am **not a Laravel** user, but I am a PHP user for many years... It may be possible to put it in the constructor, that's why I ask. But I don't know the best way to get `$request` that seems like something very important to a controller. \nI was just thinking - _\"I wonder if they check that in every/many method(s)\"_ etc.\nIn any case you should do a bit sooner so do your `$item=MenuItem::findOrFail($request->itemId);` after this then you don't waste that ORM call if that return is triggered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T21:37:38.387",
"Id": "416956",
"Score": "1",
"body": "`MenuItem::setNewOrder($request->positions);` like I said above this one looks like its setting something, so you may not want to do that if `!is_array($request->path)`. But I don't know, maybe you do. It just seemed suspect to this non **Laravel** user. For example why would you save that if you issue this `'Invalid data', 400` in your JSON response. But it may not even be percipient, so it's just a wasted call. . If you follow."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T15:01:33.927",
"Id": "215513",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"laravel",
"controller"
],
"Title": "updatePositions() Laravel controller method"
} | 215513 |
<p>I have been given an extremely loose design to follow: a page must show people's photos and name in a text overlay over the image, and when clicked a bio shows below. </p>
<h3>Must Haves</h3>
<p>Photo, text overlay with white background that you can still see part of the image. On click show the bio information, must have a connecting arrow to the image to show show who it relates to. </p>
<p>First row must have three images, all other rows there after must have four. </p>
<p>The working fiddle is at <a href="http://jsfiddle.net/SimonPrice/5kmfq7L3/122/" rel="nofollow noreferrer">http://jsfiddle.net/SimonPrice/5kmfq7L3/122/</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){
$(".imagebox").on('click', function(){
var obj = $(this);
var bio = $(obj).siblings().find('.bio');
var dataTarget = $(obj).data("target")
var parent= $("#" + dataTarget).parents('.bio-text')
var target = $("#" + dataTarget)
var parentId = parent.id;
console.log(parent.is(':visible'))
if ( parent.is(':visible') && target.is(':visible')){
$('.bio').hide('slow');
$('.bio-text').hide('slow');
$('.bio-text-value').hide('slow');
}
else{
$('.bio').hide();
$('.bio-text').hide();
$('.bio-text-value').hide();
console.log(parent)
target.fadeIn('fast')
bio.fadeIn('slow');
target.fadeIn('slow');
parent.fadeIn('slow')
}
})
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bio {
margin-left: 15px;
background: #FFFFFF;
/*border: 1px solid #CAD5E0;
*/
border-radius: 8px;
position: absolute;
z-index: 9
}
.bio-text {
margin-top:4px;
width: 97%;
background: #FFFFFF;
border: 1px solid #CAD5E0;
border-radius: 8px;
min-height: 300px
}
.bio:after {
content: '';
display: block;
position: absolute;
top: -11px;
width: 30px;
height: 30px;
background: #FFFFFF;
border-right:1px solid #CAD5E0;
border-top:1px solid #CAD5E0;
-moz-transform:rotate(-45deg);
-webkit-transform:rotate(-45deg);
}
.first, .second, .third, .fourth, .bio-text, .bio-text-value{
display: none;
}
.imagebox {
padding: 0px;
position: relative;
text-align: center;
width: 100%;
}
.imagebox img {
opacity: 1;
transition: 0.5s opacity;
border-radius: 8px
}
.imagebox .imagebox-desc {
background-color: #ffffff;
bottom: 0px;
color: #000000;
font-size: 1.2em;
left: 0px;
padding: 10px 15px;
position: absolute;
transition: 0.5s padding;
text-align: center;
width: 100%;
opacity: 0.5;
}
.imagebox:hover img {
opacity: 0.9;
}
.imagebox:hover .imagebox-desc {
padding-bottom: 10%;
opacity: 0.9;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="imagebox" data-target="simon">
<a href="#hola">
<img src="//placeimg.com/400/400/animals" class="category-banner img-fluid">
<span class="imagebox-desc">Lorem ipsum dolor sit amet!</span>
</a>
</div>
<div class="comments">
</div>
<div class="offset-md-5 offset-sm-4 offset-5 bio-container">
<div class="bio first">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="imagebox" data-target="vinnie">
<a href="#hola">
<img src="//placeimg.com/400/400/animals" class="category-banner img-fluid">
<span class="imagebox-desc">Lorem ipsum dolor sit amet!</span>
</a>
</div>
<div class="comments">
</div>
<div class="offset-md-5 offset-sm-4 offset-5">
<div class="bio second">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="imagebox" data-target="stuart">
<a href="#hola">
<img src="//placeimg.com/400/400/animals" class="category-banner img-fluid">
<span class="imagebox-desc">Lorem ipsum dolor sit amet!</span>
</a>
</div>
<div class="comments">
</div>
<div class="offset-md-5 offset-sm-4 offset-5">
<div class="bio third">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-sm-12 col-12">
<div class="bio-text">
<div class="col-md-12 col-sm-12 col-12">
<div class="bio-text-value" id="simon">
<p>
Pickle Rick
</p>
</div>
<div class="bio-text-value" id="vinnie">
<p>
batman
</p>
</div>
<div class="bio-text-value" id="stuart">
<p>
lego batman
</p>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-3">
<div class="imagebox" data-target="simon-p">
<a href="#hola">
<img src="//placeimg.com/400/400/animals" class="category-banner img-fluid">
<span class="imagebox-desc">Lorem ipsum dolor sit amet!</span>
</a>
</div>
<div class="comments">
</div>
<div class="offset-md-5 offset-sm-4 offset-5 bio-container">
<div class="bio first">
</div>
</div>
</div>
<div class="col-sm-3">
<div class="imagebox" data-target="vinnie-l">
<a href="#hola">
<img src="//placeimg.com/400/400/animals" class="category-banner img-fluid">
<span class="imagebox-desc">Lorem ipsum dolor sit amet!</span>
</a>
</div>
<div class="comments">
</div>
<div class="offset-md-5 offset-sm-4 offset-5">
<div class="bio second">
</div>
</div>
</div>
<div class="col-sm-3">
<div class="imagebox" data-target="stuart-w">
<a href="#hola">
<img src="//placeimg.com/400/400/animals" class="category-banner img-fluid">
<span class="imagebox-desc">Lorem ipsum dolor sit amet!</span>
</a>
</div>
<div class="comments">
</div>
<div class="offset-md-5 offset-sm-4 offset-5">
<div class="bio third">
</div>
</div>
</div>
<div class="col-sm-3">
<div class="imagebox" data-target="david-h">
<a href="#hola">
<img src="//placeimg.com/400/400/animals" class="category-banner img-fluid">
<span class="imagebox-desc">Lorem ipsum dolor sit amet!</span>
</a>
</div>
<div class="comments">
</div>
<div class="offset-md-5 offset-sm-4 offset-5">
<div class="bio third">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-sm-12 col-12">
<div class="bio-text">
<div class="col-md-12 col-sm-12 col-12">
<div class="bio-text-value" id="simon-p">
<p>
Pickle Rick - 1
</p>
</div>
<div class="bio-text-value" id="vinnie-l">
<p>
batman - 1
</p>
</div>
<div class="bio-text-value" id="stuart-w">
<p>
lego batman - 1
</p>
</div>
<div class="bio-text-value" id="david-h">
<p>
lego batman - 2
</p>
</div>
</div>
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T06:15:00.033",
"Id": "465683",
"Score": "0",
"body": "is there any particular arrow image that you want to show on mouseover of the image?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-19T14:01:32.720",
"Id": "465877",
"Score": "0",
"body": "this is an old ticket now and in production in an old company that i was working for. what you thinking?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T15:36:18.097",
"Id": "215515",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Showing and hiding information with photos"
} | 215515 |
<p>I have a <code>deviceList of more than 10k items</code> and want to send data by calling another method.</p>
<p>I tried to use Parallel.Foreach but I'm not sure is this the correct way to do it.</p>
<p>I have published this webapp on azure,
I have tested this for 100 it works fine but for 10k it got timeout issue.</p>
<blockquote>
<p>This is working code , I need a improvement here :)</p>
</blockquote>
<pre><code>private List<Task> taskEventList = new List<Task>();
public async Task ProcessStart()
{
string messageData = "{\"name\":\"DemoData\",\"no\":\"111\"}";
RegistryManager registryManager;
Parallel.ForEach(deviceList, async (device) =>
{
// get details for each device and use key to send message
device = await registryManager.GetDeviceAsync(device.DeviceId);
SendMessages(device.DeviceId, device.Key, messageData);
});
if (taskEventList.Count > 0)
{
await Task.WhenAll(taskEventList);
}
}
private void SendMessages(string deviceId, string Key, string messageData)
{
DeviceClient deviceClient = DeviceClient.Create(hostName, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), Microsoft.Azure.Devices.Client.TransportType.Mqtt);
//created separate Task
var taskEvents = Task.Run(() => ProcessMessages(deviceId, string messageData));
taskEventList.Add(taskEvents);
}
private async Task ProcessMessages(string deviceId, string messageData)
{
var startTime = DateTime.UtcNow;
while (DateTime.UtcNow - startTime < TimeSpan.FromMinutes(15))
{
await deviceClient.SendEventAsync(messageData);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T17:34:03.217",
"Id": "416894",
"Score": "2",
"body": "You are probably getting into a thread starvation as you just scheduling tasks and also borrowing threads from the thread pool. You need some kind of batching or throttling, as the thread pool is limited ( a thread has 2 MB, imagine 10k requests for threads)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T17:40:42.480",
"Id": "416897",
"Score": "1",
"body": "Also if DeviceClient.Create creates and *disposes* a new HttpClient everytime, then you'll get out of available sockets"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T18:47:16.450",
"Id": "416911",
"Score": "3",
"body": "Hey @AdrianIftode that seems to be the beginnings of an answer. Are you sure you don't want to write one, now that the post has been reopened?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T20:40:53.237",
"Id": "416942",
"Score": "0",
"body": "Thanks, I would like also to know about DeviceClient.Create, possible @Neo ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T21:07:41.427",
"Id": "416949",
"Score": "0",
"body": "@Neo, are you sure everything is ok with this check: *while (DateTime.UtcNow - startTime < TimeSpan.FromMinutes(15))* ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T07:30:45.427",
"Id": "417091",
"Score": "0",
"body": "nope getting timeout if count is more :( how to tackle that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T16:11:45.057",
"Id": "417129",
"Score": "0",
"body": "Is start time ever going to be set with a different value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T16:16:05.590",
"Id": "417130",
"Score": "0",
"body": "nope it will always be DateTime.Now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T17:55:43.377",
"Id": "417520",
"Score": "0",
"body": "Then that loop will never end"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T08:15:24.367",
"Id": "417602",
"Score": "0",
"body": "it is ending after 15 minutes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T06:42:57.153",
"Id": "417760",
"Score": "0",
"body": "Indeed, sorry about that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T17:17:01.843",
"Id": "441995",
"Score": "0",
"body": "You create a local variable _deviceClient_ in _SendMessages_ which you use in _ProcessMessages_, how?? And what about that magic variable _hostName_, where does that come from? I don't think this code compiles."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T16:58:22.420",
"Id": "215518",
"Score": "1",
"Tags": [
"c#",
"multithreading",
"time-limit-exceeded",
"task-parallel-library",
"azure"
],
"Title": "Sending device data of 10k items with Parallel.ForEach"
} | 215518 |
<p>I am working on a pseudo graphical interface for a <a href="https://gitlab.com/tsoj/Googleplex_Starthinker" rel="nofollow noreferrer">Chess engine</a> I wrote. I want to draw a colored Chess board with <a href="https://gitlab.com/tsoj/chessinterface/blob/f9361406014533fa167870943b34671ca5d96950/UI.txt" rel="nofollow noreferrer">ASCII pieces</a>. To abstract the pure <code>std::cout << std::endl;</code> I wrote this little class to organize an ASCII-character "framebuffer":</p>
<pre><code>#include <iostream>
#include <sys/ioctl.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <cassert>
#include <chrono>
#include <thread>
struct Color
{
unsigned char r;
unsigned char g;
unsigned char b;
};
class Framebuffer
{
std::vector<char> charBuffer;
std::vector<Color> textColorBuffer;
std::vector<Color> backgroundColorBuffer;
static const int frametime = 33;
public:
const size_t width;
const size_t height;
Framebuffer() :
width([](){
winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
return w.ws_col;
}()),
height([](){
winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
return w.ws_row;
}())
{
charBuffer = std::vector<char>(height*width);
textColorBuffer = std::vector<Color>(height*width);
backgroundColorBuffer = std::vector<Color>(height*width);
clear();
}
void clear()
{
for(auto& i : charBuffer)
{
i = ' ';
}
for(auto& i : textColorBuffer)
{
i = {255,255,255};
}
for(auto& i : backgroundColorBuffer)
{
i = {0,0,0};
}
}
void setChar(size_t col,size_t row, char c)
{
assert(row < height && col < width && row >= 0 && col >= 0);
charBuffer.at(row*width + col) = c;
}
void setChar(size_t col, size_t row, std::vector<std::string> box)
{
assert(row < height && col < width && row >= 0 && col >= 0);
for(size_t rowOffset = 0; rowOffset<box.size(); rowOffset++)
{
for(size_t colOffset = 0; colOffset<box[rowOffset].size(); colOffset++)
{
setChar(col+colOffset, row+rowOffset, box[rowOffset][colOffset]);
}
}
}
void setTextColor(size_t col,size_t row, Color color)
{
assert(row < height && col < width && row >= 0 && col >= 0);
textColorBuffer.at(row*width + col) = color;
}
void setTextColor(size_t col, size_t row, std::vector<std::vector<Color>> box)
{
assert(row < height && col < width && row >= 0 && col >= 0);
for(size_t rowOffset = 0; rowOffset<box.size(); rowOffset++)
{
for(size_t colOffset = 0; colOffset<box[rowOffset].size(); colOffset++)
{
setTextColor(col+colOffset, row+rowOffset, box[rowOffset][colOffset]);
}
}
}
void setBackgroundColor(size_t col,size_t row, Color color)
{
assert(row < height && col < width && row >= 0 && col >= 0);
backgroundColorBuffer.at(row*width + col) = color;
}
void setBackgroundColor(size_t col, size_t row, std::vector<std::vector<Color>> box)
{
assert(row < height && col < width && row >= 0 && col >= 0);
for(size_t rowOffset = 0; rowOffset<box.size(); rowOffset++)
{
for(size_t colOffset = 0; colOffset<box[rowOffset].size(); colOffset++)
{
setBackgroundColor(col+colOffset, row+rowOffset, box[rowOffset][colOffset]);
}
}
}
char getChar(size_t col, size_t row)
{
assert(row < height && col < width && row >= 0 && col >= 0);
return charBuffer.at(row*width + col);
}
Color getTextColor(size_t col, size_t row)
{
assert(row < height && col < width && row >= 0 && col >= 0);
return textColorBuffer.at(row*width + col);
}
Color getBackgroundColor(size_t col, size_t row)
{
assert(row < height && col < width && row >= 0 && col >= 0);
return backgroundColorBuffer.at(row*width + col);
}
void print()
{
static std::thread printerThread;
if(printerThread.joinable())
{
printerThread.join();
}
auto printer = [this]()
{
std::string output = "";
for(size_t row = 0; row<height; row++)
{
for(size_t col = 0; col<width; col++)
{
Color textColor = getTextColor(col, row);
Color backgroundColor = getBackgroundColor(col, row);
output += "\033[38;2;";
output += std::to_string((int)textColor.r) + ";";
output += std::to_string((int)textColor.g) + ";";
output += std::to_string((int)textColor.b) + "m";
output += "\033[48;2;";
output += std::to_string((int)backgroundColor.r) + ";";
output += std::to_string((int)backgroundColor.g) + ";";
output += std::to_string((int)backgroundColor.b) + "m";
output += getChar(col, row);
}
if(row != height - 1)
{
output += "\n";
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(frametime));
std::system("clear");
std::cout << output << std::flush;
};
printerThread = std::thread(printer);
}
};
</code></pre>
<p>There is a bug: when destructing a <code>Framebuffer</code> it can happen that the <code>static std::thread printerThread</code> never gets joined or otherwise terminated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T06:09:50.283",
"Id": "416987",
"Score": "2",
"body": "ncurses. Perhaps you've heard of it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:54:34.667",
"Id": "417016",
"Score": "0",
"body": "In `setBackgroundColor`, take `std::vector<std::vector<Color>>` by const-ref instead since you don't modify the object. The copy is unnecessary."
}
] | [
{
"body": "<ul>\n<li>Order your includes at least by portable / non-portable.</li>\n<li>Not a huge fan of omitting <code>private</code> and putting all the private members up top. IMO a class interface should go from <code>public</code> to <code>private</code> which makes for easier reading as a user.</li>\n<li>The whole thing is a bit hard to read. Some linebreaks and maybe even spaces would make this easier on the eyes.</li>\n<li>Is there a reason not to use <code>memset</code> in your clear function?</li>\n<li>Pedantic people might complain about the missing header for <code>size_t</code> and the missing <code>std::</code> qualifier.</li>\n<li><code>std::string output = \"\";</code> initializing strings this way always looks weird to me. <code>std::string s;</code> should suffice but to declare intent more clearly you can do <code>std::string{\"\"};</code>. Purely subjective though.</li>\n<li>Always a good idea to get into the habit of <a href=\"https://softwareengineering.stackexchange.com/questions/59880/avoid-postfix-increment-operator\">using prefix operator over postfix</a> operator.</li>\n<li>I do like that you signal intent with <code>flush</code> as opposed to relying on <code>endl</code></li>\n<li>Not sure if you use <code>Color</code> elsewhere but it could probably be an implementation detail instead of being free.</li>\n<li>You explicitly state this is for linux so you probably know that <code>system(\"clear\")</code> is non-portable and are okay with it.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T19:08:49.247",
"Id": "416923",
"Score": "0",
"body": "`#include <sys/ioctl.h>`\n`#include <unistd.h>` are the non-portables, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T20:03:46.433",
"Id": "416935",
"Score": "0",
"body": "@DariusDuesentrieb As far as I can tell, yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T10:32:12.820",
"Id": "417254",
"Score": "0",
"body": "Interesting that you point out `std::system(\"clear\")` as non-portable, when it's much *more* portable than `\\033[m`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T17:43:15.497",
"Id": "417341",
"Score": "0",
"body": "@TobySpeight A fair point. Seems like my subconsciousness shielded me from even noticing those."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T18:32:20.957",
"Id": "215520",
"ParentId": "215519",
"Score": "3"
}
},
{
"body": "<h1>Framebuffer()</h1>\n\n<p>Could end with</p>\n\n<pre><code> charBuffer = std::vector<char>(height * width, ' ');\n textColorBuffer = std::vector<Color>(height * width, {255u, 255u, 255u});\n backgroundColorBuffer = std::vector<Color>(height * width);\n</code></pre>\n\n<p>instead of calling clear.</p>\n\n<h1>void clear()</h1>\n\n<p>Alternative implementation and let container implementation decide what is most effective.</p>\n\n<pre><code> charBuffer.assign(charBuffer.size(), ' ');\n textColorBuffer.assign(textColorBuffer.size(), {255u, 255u, 255u});\n backgroundColorBuffer.assign(backgroundColorBuffer.size(), {});\n</code></pre>\n\n<h1>void setChar()</h1>\n\n<p>Don't copy the box in the interface, use a const reference. And don't call <code>size()</code> more than necessary.</p>\n\n<pre><code>void setChar(size_t col, size_t row, const std::vector<std::string>& box) {\n assert(row < height && col < width && row >= 0 && col >= 0);\n for (size_t rowOffset = 0u, boxSize = box.size(); rowOffset < boxSize; rowOffset++) {\n for (size_t colOffset = 0, rowSize = box[rowOffset].size(); colOffset < rowSize; colOffset++) {\n setChar(col + colOffset, row + rowOffset, box[rowOffset][colOffset]);\n }\n }\n}\n</code></pre>\n\n<h1>void setTextColor()</h1>\n\n<p>Again, don't copy the box on each call. And another use of references inside the loops.</p>\n\n<pre><code>void setTextColor(size_t col, size_t row, const std::vector<std::vector<Color>>& box) {\n assert(row < height && col < width && row >= 0 && col >= 0);\n for (size_t rowOffset = 0, boxSize = box.size(); rowOffset < boxSize; rowOffset++) {\n auto & line = box[rowOffset];\n for (size_t colOffset = 0, line_sz = line.size(); colOffset < line_sz; colOffset++) {\n setTextColor(col + colOffset, row + rowOffset, line[colOffset]);\n }\n }\n}\n</code></pre>\n\n<h1>void setBackgroundColor()</h1>\n\n<p>Similar comments regarding <code>setBackgroundColor</code>.</p>\n\n<h1>void print()</h1>\n\n<p>Alternative lambda with <code>std::stringstream</code>.</p>\n\n<pre><code> auto printer = [this]() {\n std::stringstream output;\n for (size_t row = 0; row < height; row++) {\n for (size_t col = 0; col < width; col++) {\n Color textColor = getTextColor(col, row);\n Color backgroundColor = getBackgroundColor(col, row);\n output << \"\\033[38;2;\"\n << static_cast<int>(textColor.r) << ';'\n << static_cast<int>(textColor.g) << ';'\n << static_cast<int>(textColor.b) << \"m\"\n \"\\033[48;2;\"\n << static_cast<int>(backgroundColor.r) << ';'\n << static_cast<int>(backgroundColor.g) << ';'\n << static_cast<int>(backgroundColor.b) << 'm'\n << getChar(col, row);\n }\n if (row != height - 1) {\n output << '\\n';\n }\n }\n std::this_thread::sleep_for(std::chrono::milliseconds(frametime));\n std::system(\"clear\");\n std::cout << output.rdbuf() << std::flush;\n };\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T09:47:17.670",
"Id": "215562",
"ParentId": "215519",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T17:31:50.373",
"Id": "215519",
"Score": "7",
"Tags": [
"c++",
"console",
"linux",
"ascii-art"
],
"Title": "Color ASCII drawing class"
} | 215519 |
<p>I have googled and read many tutorials about fetching data and posting data to Rest API. But i have never seen a tutorial with how to handle the getting of new data after a POST or an PUT in a best practice way. So i experimented a bit and codes this. It is working but I don't know if it is the correct way of doing this.</p>
<p>In <code>customerservice</code> I have a subject that components can subscribe to. When I'm getting customers from the API I'm publishing the result into the subject. And in the component I'm subscribing to a customer subject.</p>
<p>In a POST to the API I'm triggering a <code>GetCustomer()</code> to fetch all customers again.</p>
<p>CustomerService</p>
<pre><code>import { Injectable } from '@angular/core';
import { LoggerService } from 'src/app/core/services/logger.service';
import { Observable, Subject } from 'rxjs';
import { Customer } from 'src/app/shared/models/customer.model';
import { HttpClient } from '@angular/common/http';
import { tap, map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class CustomersService {
customers = new Subject<Customer[]>();
constructor(private http: HttpClient, private logger: LoggerService) { }
getCustomers(): void {
this.http.get<Customer[]>('/subscribers/customers').pipe(map(res => {
this.logger.info('Getting customers', res);
this.customers.next(res);
})).subscribe();
}
addCustomer(customer: Customer): void {
this.http.post<Customer[]>('/subscribers/customers', customer).pipe(map(res => {
this.logger.info('Adding new customer', res);
this.getCustomers();
})).subscribe();
}
}
</code></pre>
<p>CustomerComponent</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { CustomerDialogComponent } from '../../components/customer-dialog/customer-dialog.component';
import { CustomersService } from '../../services/customers.service';
import { Observable } from 'rxjs';
import { Customer } from 'src/app/shared/models/customer.model';
import { LoadingWrapper } from 'src/app/shared/helpers/LoadingWrapper';
@Component({
selector: 'app-customers',
templateUrl: './customers.component.html',
styleUrls: ['./customers.component.scss']
})
export class CustomersComponent implements OnInit {
bsModalRef: BsModalRef;
customers: LoadingWrapper<Customer[]>;
constructor(private modalService: BsModalService, private customersService: CustomersService) { }
ngOnInit() {
this.customers = new LoadingWrapper(this.customersService.customers);
this.customersService.getCustomers();
}
open(): void {
this.bsModalRef = this.modalService.show(CustomerDialogComponent, { backdrop: false, class: 'right-modal' });
}
}
</code></pre>
<p>And finally my modals that's POST a new customer:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { FormGroup, Validators } from '@angular/forms';
import { FormInputBase } from 'src/app/shared/models/form-input-base.model';
import { LoggerService } from 'src/app/core/services/logger.service';
import { FormInputText } from 'src/app/shared/models/form-input-text.model';
import { FormService } from 'src/app/core/services/form.service';
import { BsModalService } from 'ngx-bootstrap';
import { CustomersService } from '../../services/customers.service';
@Component({
selector: 'app-add-customer',
templateUrl: './add-customer.component.html',
styleUrls: ['./add-customer.component.scss']
})
export class AddCustomerComponent implements OnInit {
addCustomerForm: FormGroup;
addCustomerInputs: FormInputBase<any>[];
constructor(private logger: LoggerService, private formService: FormService,
private modalService: BsModalService, private customerService: CustomersService) { }
ngOnInit() {
this.addCustomerInputs = this.getCustomerInputs();
this.addCustomerForm = this.formService.toFormGroup(this.addCustomerInputs);
}
getCustomerInputs(): FormInputBase<any>[] {
const inputs: FormInputBase<any>[] = [
new FormInputText({
key: 'name',
label: 'Name',
placeholder: 'Customer name',
order: 1,
validation: [Validators.required, Validators.maxLength(200)]
}),
new FormInputText({
key: 'ref',
label: 'Ref',
placeholder: 'External reference',
order: 2
})
];
return inputs.sort((a, b) => a.order - b.order);
}
add(): void {
this.customerService.addCustomer(this.addCustomerForm.value);
}
close(): void {
this.modalService.hide(1);
}
}
</code></pre>
<p>EDIT:
LoadingWrapper</p>
<pre><code>import { Subject, Observable, of } from 'rxjs';
import { shareReplay, catchError } from 'rxjs/operators';
import { LoggerService } from 'src/app/core/services/logger.service';
export class LoadingWrapper<T> {
private readonly _errorLoading$ = new Subject<boolean>();
readonly errorLoading$: Observable<boolean> = this._errorLoading$.pipe(
shareReplay(1)
);
readonly data$: Observable<{} | T>;
constructor(data: Observable<T>) {
this.data$ = data.pipe(
shareReplay(1),
catchError(error => {
this._errorLoading$.next(true);
return of();
})
);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T20:37:41.070",
"Id": "417157",
"Score": "0",
"body": "What is `LoadingWrapper`? The way you're using observables in your service seems like an antipattern, but without seeing `LoadingWrapper` I can't tell what exactly is happening."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T20:52:55.050",
"Id": "417162",
"Score": "0",
"body": "@elclanrs Loading wrapper is just a generic way to handle errors and showing the loading text."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T21:10:24.653",
"Id": "215533",
"Score": "1",
"Tags": [
"javascript",
"angular-2+",
"angular-bootstrap"
],
"Title": "Angular 7 HttpClient POST and GET"
} | 215533 |
<h3>Problem</h3>
<p>I've written a timer module in C for an SDL game. I'd like to get some eyeballs on. I wrote this for 2 requirements: I needed a timer that would signal on an elapsed interval, AND that was pausable and restartable. The timers in SDL signal a callback on a set interval, but they aren't pausable. I've seen other pausable timer implementations for SDL, but they've all required a query for a tick count.</p>
<p>I realized that since I already had an infinite loop using the SDL engine, I could leverage that to drive a pausable timer. I've included a small test program that you can use to evaluate the timer module if you want.</p>
<p>BE ADVISED: <em>If you are sensitive to flashing visual stimuli, you shouldn't run the test program.</em></p>
<p>Also, the test program is NOT the code that I need reviewed.</p>
<p>The timer module works well, and the caveats I'm aware of already are:</p>
<ul>
<li>The more simultaneous timers you use, the greater the likelihood that you will run into timer lag.</li>
<li>The work done in timer callbacks should be short and sweet, and callbacks should return as fast as possible. On the upside, with this implementation, there are no threading issues with timer callbacks.</li>
</ul>
<p>If anyone can spot any gotchas that I'm not aware of, especially as they relate to using the SDL library, I would really appreciate it. </p>
<h3>Timer header file:</h3>
<pre><code>#ifndef TIMER_H
#define TIMER_H
typedef struct Timer Timer;
typedef void(*TimerCallback)(void *data);
/*
Initializes the timer mechanism, and allocates resources for 'nTimers'
number of simultaneous timers.
Returns non-zero on failure.
*/
int timer_InitTimers(int nTimers);
/*
Add this to the main game loop, either before or after the loop that
polls events. If timing is very critical, add it both before and after.
*/
void timer_PollTimers(void);
/*
Creates an idle timer that has to be started with a call to 'timer_Start()'.
Returns NULL on failure. Will fail if 'timer_InitTimers()' has not already
been called.
*/
Timer *timer_Create(Uint32 interval, TimerCallback fCallback, void *data);
/*
Pauses a timer. If the timer is already paused, this is a no-op.
Fails with non-zero if 'timer' is NULL or not a valid timer.
*/
int timer_Pause(Timer *timer);
/*
Starts a timer. If the timer is already running, this function resets the
delta time for the timer back to zero.
Fails with non-zero if 'timer' is NULL or not a valid timer.
*/
int timer_Start(Timer *timer);
/*
Cancels an existing timer. If 'timer' is NULL, this is a no-op.
*/
void timer_Cancel(Timer *timer);
/*
Releases the resources allocated for the timer mechanism. Call at program
shutdown, along with 'SDL_Quit()'.
*/
void timer_Quit(void);
/*
Returns true if the timer is running, or false if the timer is paused or
is NULL.
*/
int timer_IsRunning(Timer *timer);
#endif
</code></pre>
<h3>Timer source file:</h3>
<pre><code>#include <SDL.h>
#include "timer.h"
static Timer *Chunk; /* BLOB of timers to use */
static int ChunkCount;
static Timer *Timers; /* Linked list of active timers */
static Uint64 TicksPerMillisecond;
static Uint64 Tolerance; /* Fire the timer if it's this close */
struct Timer {
int active;
int running;
TimerCallback callback;
void *user;
Timer *next;
Uint64 span;
Uint64 last;
};
static void addTimer(Timer *t) {
Timer *n = NULL;
if (Timers == NULL) {
Timers = t;
}
else {
n = Timers;
while (n->next != NULL) {
n = n->next;
}
n->next = t;
}
}
static void removeTimer(Timer *t) {
Timer *n = NULL;
Timer *p = NULL;
if (t == Timers) {
Timers = Timers->next;
}
else {
p = Timers;
n = Timers->next;
while (n != NULL) {
if (n == t) {
p->next = t->next;
SDL_memset(n, 0, sizeof(*n));
break;
}
p = n;
n = n->next;
}
}
}
int timer_InitTimers(int n) {
TicksPerMillisecond = SDL_GetPerformanceFrequency() / 1000;
Tolerance = TicksPerMillisecond / 2; /* 0.5 ms tolerance */
Chunk = calloc(n, sizeof(Timer));
if (Chunk == NULL) {
//LOG_ERROR(Err_MallocFail);
return 1;
}
ChunkCount = n;
return 0;
}
Timer *timer_Create(Uint32 interval, TimerCallback fCallback, void *data) {
Timer *t = Chunk;
int i = 0;
while (i < ChunkCount) {
if (!t->active) {
t->span = TicksPerMillisecond * interval - Tolerance;
t->callback = fCallback;
t->user = data;
t->active = 1;
addTimer(t);
return t;
}
i++;
t++;
}
return NULL;
}
void timer_PollTimers(void) {
Timer *t = Timers;
Uint64 ticks = SDL_GetPerformanceCounter();
while (t) {
/* if a timer is not 'active', it shouldn't be 'running' */
SDL_assert(t->active);
if (t->running && ticks - t->last >= t->span) {
t->callback(t->user);
t->last = ticks;
}
t = t->next;
}
}
int timer_Pause(Timer* t) {
if (t && t->active) {
t->running = 0;
t->last = 0;
return 0;
}
return 1;
}
int timer_Start(Timer *t) {
if (t && t->active) {
t->running = 1;
t->last = SDL_GetPerformanceCounter();
return 0;
}
return 1;
}
void timer_Cancel(Timer *t) {
if (t) removeTimer(t);
}
void timer_Quit(void) {
Timers = NULL;
free(Chunk);
}
int timer_IsRunning(Timer *t) {
if (t) {
return t->running;
}
return 0;
}
</code></pre>
<h3>Test program:</h3>
<pre><code>#include <stdio.h>
#include <SDL.h>
#include "timer.h"
Uint32 EVENT_TYPE_TIMER_RED;
Uint32 EVENT_TYPE_TIMER_BLUE;
Uint32 EVENT_TYPE_TIMER_GREEN;
Uint32 EVENT_TYPE_TIMER_YELLOW;
Uint32 colorRed;
Uint32 colorBlue;
Uint32 colorGreen;
Uint32 colorYellow;
SDL_Rect rectRed;
SDL_Rect rectBlue;
SDL_Rect rectGreen;
SDL_Rect rectYellow;
Timer* timerRed;
Timer* timerBlue;
Timer *timerGreen;
Timer *timerYellow;
int isRed;
int isBlue;
int isGreen;
int isYellow;
static void handleTimerRed(void*);
static void handleTimerBlue(void*);
static void handleTimerGreen(void*);
static void handleTimerYellow(void*);
SDL_Event QuitEvent = { SDL_QUIT };
SDL_Renderer *render;
SDL_Window *window;
SDL_Surface *surface;
static void initGlobals(void) {
rectRed = (SDL_Rect){ 0, 0, 128, 128 };
rectBlue = (SDL_Rect){ 640 - 128, 0, 128, 128 };
rectGreen = (SDL_Rect){ 0, 480 - 128, 128, 128 };
rectYellow = (SDL_Rect){ 640 - 128, 480 - 128, 128, 128 };
EVENT_TYPE_TIMER_RED = SDL_RegisterEvents(4);
EVENT_TYPE_TIMER_BLUE = EVENT_TYPE_TIMER_RED + 1;
EVENT_TYPE_TIMER_GREEN = EVENT_TYPE_TIMER_RED + 2;
EVENT_TYPE_TIMER_YELLOW = EVENT_TYPE_TIMER_RED + 3;
timerRed = timer_Create(250, handleTimerRed, NULL);
timerBlue = timer_Create(500, handleTimerBlue, NULL);
timerGreen = timer_Create(750, handleTimerGreen, NULL);
timerYellow = timer_Create(1000, handleTimerYellow, NULL);
colorRed = SDL_MapRGB(surface->format, 170, 0, 0);
colorBlue = SDL_MapRGB(surface->format, 0, 0, 170);
colorGreen = SDL_MapRGB(surface->format, 0, 170, 0);
colorYellow = SDL_MapRGB(surface->format, 255, 255, 0);
SDL_FillRect(surface, NULL, 0);
SDL_FillRect(surface, &rectRed, colorRed);
SDL_FillRect(surface, &rectBlue, colorBlue);
SDL_FillRect(surface, &rectGreen, colorGreen);
SDL_FillRect(surface, &rectYellow, colorYellow);
isRed = isBlue = isGreen = isYellow = 1;
}
static void handleEvent(SDL_Event *evt) {
SDL_Texture *tex;
if (evt->type == SDL_KEYDOWN) {
if (evt->key.keysym.sym == SDLK_ESCAPE) {
SDL_PushEvent(&QuitEvent);
}
else if (evt->key.keysym.sym == SDLK_r) {
if (timer_IsRunning(timerRed)) {
timer_Pause(timerRed);
}
else {
timer_Start(timerRed);
}
}
else if (evt->key.keysym.sym == SDLK_b) {
if (timer_IsRunning(timerBlue)) {
timer_Pause(timerBlue);
}
else {
timer_Start(timerBlue);
}
}
else if (evt->key.keysym.sym == SDLK_g) {
if (timer_IsRunning(timerGreen)) {
timer_Pause(timerGreen);
}
else {
timer_Start(timerGreen);
}
}
else if (evt->key.keysym.sym == SDLK_y) {
if (timer_IsRunning(timerYellow)) {
timer_Pause(timerYellow);
}
else {
timer_Start(timerYellow);
}
}
}
else if (evt->type == EVENT_TYPE_TIMER_RED) {
if (isRed) {
SDL_FillRect(surface, &rectRed, 0);
isRed = 0;
}
else {
SDL_FillRect(surface, &rectRed, colorRed);
isRed = 1;
}
tex = SDL_CreateTextureFromSurface(render, surface);
SDL_RenderCopy(render, tex, NULL, NULL);
SDL_RenderPresent(render);
SDL_DestroyTexture(tex);
}
else if (evt->type == EVENT_TYPE_TIMER_BLUE) {
if (isBlue) {
SDL_FillRect(surface, &rectBlue, 0);
isBlue = 0;
}
else {
SDL_FillRect(surface, &rectBlue, colorBlue);
isBlue = 1;
}
tex = SDL_CreateTextureFromSurface(render, surface);
SDL_RenderCopy(render, tex, NULL, NULL);
SDL_RenderPresent(render);
SDL_DestroyTexture(tex);
}
else if (evt->type == EVENT_TYPE_TIMER_GREEN) {
if (isGreen) {
SDL_FillRect(surface, &rectGreen, 0);
isGreen = 0;
}
else {
SDL_FillRect(surface, &rectGreen, colorGreen);
isGreen = 1;
}
tex = SDL_CreateTextureFromSurface(render, surface);
SDL_RenderCopy(render, tex, NULL, NULL);
SDL_RenderPresent(render);
SDL_DestroyTexture(tex);
}
else if (evt->type == EVENT_TYPE_TIMER_YELLOW) {
if (isYellow) {
SDL_FillRect(surface, &rectYellow, 0);
isYellow = 0;
}
else {
SDL_FillRect(surface, &rectYellow, colorYellow);
isYellow = 1;
}
tex = SDL_CreateTextureFromSurface(render, surface);
SDL_RenderCopy(render, tex, NULL, NULL);
SDL_RenderPresent(render);
SDL_DestroyTexture(tex);
}
}
int main(int argc, char* args[])
{
(void)(argc);
(void)(args);
SDL_Event event = { 0 };
int run = 0;
SDL_Texture *texture = NULL;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
printf("Failed to init SDL library.");
return 1;
}
if (SDL_CreateWindowAndRenderer(640,
480,
SDL_WINDOW_RESIZABLE,
&window,
&render))
{
printf("Could not create main window and renderer.");
return 1;
}
if (SDL_RenderSetLogicalSize(render, 640, 480)) {
printf("Could not set logical window size.");
return 1;
}
if (timer_InitTimers(4)) {
printf("Could not init timers.");
return 1;
}
surface = SDL_GetWindowSurface(window);
initGlobals();
texture = SDL_CreateTextureFromSurface(render, surface);
SDL_RenderCopy(render, texture, NULL, NULL);
SDL_RenderPresent(render);
SDL_DestroyTexture(texture);
run = 1;
while (run) {
timer_PollTimers();
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
run = 0;
break;
}
handleEvent(&event);
}
/* or here timer_PollTimers(); */
}
SDL_Quit();
timer_Quit();
return 0;
}
static void handleTimerRed(void *ignored) {
SDL_Event event;
(void)(ignored);
event.type = EVENT_TYPE_TIMER_RED;
SDL_PushEvent(&event);
}
static void handleTimerBlue(void *ignored) {
SDL_Event event;
(void)(ignored);
event.type = EVENT_TYPE_TIMER_BLUE;
SDL_PushEvent(&event);
}
static void handleTimerGreen(void *ignored) {
SDL_Event event;
(void)(ignored);
event.type = EVENT_TYPE_TIMER_GREEN;
SDL_PushEvent(&event);
}
static void handleTimerYellow(void *ignored) {
SDL_Event event;
(void)(ignored);
event.type = EVENT_TYPE_TIMER_YELLOW;
SDL_PushEvent(&event);
}
</code></pre>
| [] | [
{
"body": "<p>I don't see too much that I feel like complaining about.</p>\n\n<h2>Standard Types</h2>\n\n<p>In timer.h, you use <code>Uint32</code>. This is not a standard type. It comes from SDL, which in turn comes from <code>stdint.h</code>:</p>\n\n<p><a href=\"https://github.com/spurious/SDL-mirror/blob/17af4584cb28cdb3c2feba17e7d989a806007d9f/include/SDL_stdinc.h#L203\" rel=\"noreferrer\">https://github.com/spurious/SDL-mirror/blob/17af4584cb28cdb3c2feba17e7d989a806007d9f/include/SDL_stdinc.h#L203</a></p>\n\n<pre><code>typedef uint32_t Uint32;\n</code></pre>\n\n<p>Headers should be include-order-agnostic; that is, your header should work even if it's included first (which currently it won't). One solution is to <code>#include <stdint.h></code> in your header, and use its types rather than the SDL types.</p>\n\n<h2>For is your friend</h2>\n\n<p>This:</p>\n\n<pre><code>int i = 0;\nwhile (i < ChunkCount) {\n ...\n i++;\n</code></pre>\n\n<p>is more simply expressed as</p>\n\n<pre><code>for (int i = 0; i < ChunkCount; i++) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T06:24:01.713",
"Id": "416989",
"Score": "0",
"body": "I agree with your points in general, but SDL takes no dependency on the C runtime, and those types, along with `SDL_memset` and `SDL_assert`, lets me avoid that as well. Usually I prefer a simple for loop over a while loop also, but in this case I would have to use `Chunk[i].member`, instead of just `t->member`. And besides, I have to return a pointer anyway, so I might as well use a pointer as I go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T17:38:31.970",
"Id": "417138",
"Score": "0",
"body": "You can use a `for` and still use `t`. `t` is maintained separately from `i`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T06:03:37.520",
"Id": "215555",
"ParentId": "215537",
"Score": "6"
}
},
{
"body": "<h3>Update</h3>\n\n<p>After further usage, I did discover one issue with regard to usability. Once a <code>Timer</code> instance has been cancelled, it is no longer valid and should not be used. So, if the pointer variable is going to hang around, it should be set to <code>NULL</code>.</p>\n\n<p>The game I'm working on has several reentrant state machines, some of which contain <code>Timer</code> variables. So, everywhere I cancelled a timer, I had to be sure to set the variable to <code>NULL</code>, so that if the state machine is entered again, I could check it. I decided to enforce this by refactoring the <code>timer_Cancel()</code> function to accept the address of a <code>Timer</code> instance, and set it to <code>NULL</code> before returning from that function.</p>\n\n<p>Here is the revised code, along with @Reinderien 's suggestions for improvement. Instead of including <code>stdint.h</code>, I moved the <code>#include <SDL.h></code> line to the timer header file to eliminate the header dependency. That way, I avoid including any headers from the standard libraries, which means I don't have to take a dependency on the C runtime. I also refactored the while loop, which looks a <em>little</em> cleaner, but still sorta sets off some bells, because the first thing I look at when reviewing a <code>for</code> loop is how the iterator variable is used. I tend to get suspicious if it isn't used at all. Probably a question of <em>style</em> more than anything, I guess. The test program code is unchanged, so I didn't include it here.</p>\n\n<h3>Timer.h</h3>\n\n<pre><code>#ifndef TIMER_H\n#define TIMER_H\n\n#include <SDL.h>\n\ntypedef struct Timer Timer;\ntypedef void(*TimerCallback)(void *data);\n\n/*\n Initializes the timer mechanism, and allocates resources for 'nTimers'\n number of simultaneous timers.\n\n Returns non-zero on failure.\n*/\nint timer_InitTimers(int nTimers);\n\n/*\n Add this to the main game loop, either before or after the loop that\n polls events. If timing is very critical, add it both before and after.\n*/\nvoid timer_PollTimers(void);\n\n/*\n Creates an idle timer that has to be started with a call to 'timer_Start()'.\n\n Returns NULL on failure. Will fail if 'timer_InitTimers()' has not already\n been called.\n*/\nTimer *timer_Create(Uint32 interval, TimerCallback fCallback, void *data);\n\n/*\n Pauses a timer. If the timer is already paused, this is a no-op.\n\n Fails with non-zero if 'timer' is NULL or not a valid timer.\n*/\nint timer_Pause(Timer *timer);\n\n/*\n Starts a timer. If the timer is already running, this function resets the\n delta time for the timer back to zero.\n\n Fails with non-zero if 'timer' is NULL or not a valid timer.\n*/\nint timer_Start(Timer *timer);\n\n/*\n Cancels an existing timer. If the timer is NULL, this is a no-op.\n\n Accepts the address of a 'Timer' pointer, and sets that pointer to\n NULL before returning.\n*/\nvoid timer_Cancel(Timer **timer);\n\n/*\n Releases the resources allocated for the timer mechanism. Call at program\n shutdown, along with 'SDL_Quit()'.\n*/\nvoid timer_Quit(void);\n\n/*\n Returns true if the timer is running, or false if the timer is paused or\n is NULL.\n*/\nint timer_IsRunning(Timer *timer);\n\n#endif\n</code></pre>\n\n<h3>Timer.c</h3>\n\n<pre><code>#include \"timer.h\"\n\nstatic Timer *Chunk; /* BLOB of timers to use */\nstatic int ChunkCount;\nstatic Timer *Timers; /* Linked list of active timers */\nstatic Uint64 TicksPerMillisecond;\nstatic Uint64 Tolerance; /* Fire the timer if it's this close */\n\nstruct Timer {\n int active;\n int running;\n TimerCallback callback;\n void *user;\n Timer *next;\n Uint64 span;\n Uint64 last;\n};\n\nstatic void addTimer(Timer *t) {\n Timer *n = NULL;\n\n if (Timers == NULL) {\n Timers = t;\n }\n else {\n n = Timers;\n while (n->next != NULL) {\n n = n->next;\n }\n n->next = t;\n }\n}\n\nstatic void removeTimer(Timer *t) {\n Timer *n = NULL;\n Timer *p = NULL;\n\n if (t == Timers) {\n Timers = Timers->next;\n }\n else {\n p = Timers;\n n = Timers->next;\n while (n != NULL) {\n if (n == t) {\n p->next = t->next;\n SDL_memset(n, 0, sizeof(*n));\n break;\n }\n p = n;\n n = n->next;\n }\n }\n}\n\nint timer_InitTimers(int n) {\n TicksPerMillisecond = SDL_GetPerformanceFrequency() / 1000;\n Tolerance = TicksPerMillisecond / 2; /* 0.5 ms tolerance */\n Chunk = calloc(n, sizeof(Timer));\n if (Chunk == NULL) {\n //LOG_ERROR(Err_MallocFail);\n return 1;\n }\n ChunkCount = n;\n return 0;\n}\n\nTimer *timer_Create(Uint32 interval, TimerCallback fCallback, void *data) {\n Timer *t = Chunk;\n\n for (int i = 0; i < ChunkCount; i++) {\n if (!t->active) {\n t->span = TicksPerMillisecond * interval - Tolerance;\n t->callback = fCallback;\n t->user = data;\n t->active = 1;\n addTimer(t);\n return t;\n }\n t++;\n }\n return NULL;\n}\n\nvoid timer_PollTimers(void) {\n Timer *t = Timers;\n Uint64 ticks = SDL_GetPerformanceCounter();\n\n while (t) {\n /* if a timer is not 'active', it shouldn't be 'running' */\n SDL_assert(t->active);\n\n if (t->running && ticks - t->last >= t->span) {\n t->callback(t->user);\n t->last = ticks;\n }\n t = t->next;\n }\n}\n\nint timer_Pause(Timer* t) {\n if (t && t->active) {\n t->running = 0;\n t->last = 0;\n return 0;\n }\n return 1;\n}\n\nint timer_Start(Timer *t) {\n if (t && t->active) {\n t->running = 1;\n t->last = SDL_GetPerformanceCounter();\n return 0;\n }\n return 1;\n}\n\nvoid timer_Cancel(Timer **t) {\n if (*t) {\n removeTimer(*t);\n *t = NULL;\n }\n}\n\nvoid timer_Quit(void) {\n Timers = NULL;\n free(Chunk);\n}\n\nint timer_IsRunning(Timer *t) {\n if (t) {\n return t->running;\n }\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T17:24:47.687",
"Id": "417516",
"Score": "0",
"body": "If you want that reviewed and the change was major you should post it as a new question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T00:08:39.913",
"Id": "417563",
"Score": "0",
"body": "@HaraldScheirich: Sorry, no I don't need that reviewed. I've asked on Meta whether I should just delete this answer or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T02:09:59.830",
"Id": "417568",
"Score": "1",
"body": "@HaraldScheirich [Here is a link to the meta post](https://codereview.meta.stackexchange.com/q/9122)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T16:55:49.163",
"Id": "215770",
"ParentId": "215537",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "215555",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T00:08:32.913",
"Id": "215537",
"Score": "8",
"Tags": [
"c",
"timer",
"sdl"
],
"Title": "Pausable Timer Implementation for SDL in C"
} | 215537 |
<p>Class <code>SectorController</code> calculates weight coefficients for sector performances in equity exchange markets using minute data from an API (for instance, if a group of equities are up in the past 5 minutes, then coefficient is positive, if not, is negative, ranging from -1 to +1). Most of calculations are based on other scripts, which is not necessary for this review. </p>
<p>Would you be so kind and review this class and help me to make it faster, if possible?</p>
<h3>Script</h3>
<pre><code>class SectorController
{
/**
*
* @var a string of iextrading base URL
*/
const BASE_URL = "https://api.iextrading.com/1.0/";
/**
*
* @var a string of target path and query
*/
const TARGET_QUERY = "stock/market/batch?symbols=";
/**
*
* @var a string for backend path for every sector
*/
const EACH_SECTOR_DIR_PREFIX = "/../../dir/dir/dir/dir-";
/**
*
* @var a string for backend path for index sector
*/
const INDEX_SECTOR_DIR_PREFIX = "/../../dir/dir/dir/dir/";
/**
*
* @var a string for live data path
*/
const LIVE_DATA_DIR = "/../../../public_html/dir/dir/";
function __construct()
{
echo "YAAAY! " . __METHOD__ . " success \n";
return true;
}
public static function getSectors(){
$baseUrl=self::BASE_URL.self::TARGET_QUERY;
$currentTime = date("Y-m-d-H-i-s");
$permission = 0755;
$indexData = array( "Overall" => array("sector_weight" => 1, "sector_coefficient" => 5,
$sectorInfos=SectorController::iexSectorParams();
foreach ($sectorInfos as $a => $sectorInfo) {
$sectorUrl = $baseUrl . implode(",", array_keys($sectorInfo["selected_tickers"])) . "&types=quote&range=1m";
$rawSectorJson = file_get_contents($sectorUrl);
$rawSectorArray = json_decode($rawSectorJson, true);
// Write the raw file
$rawSectorDir = __DIR__ . self::EACH_SECTOR_DIR_PREFIX . $sectorInfo["directory"];
if (!is_dir($rawSectorDir)) {
mkdir($rawSectorDir, $permission, true);
}
$rawSectorFile = $rawSectorDir . "/" . $currentTime . ".json";
$fp = fopen($rawSectorFile, "a+");
fwrite($fp, $rawSectorJson);
fclose($fp);
// Calculate the real-time index
$indexValue = 0;
foreach ($rawSectorArray as $ticker => $tickerStats) {
if (isset($sectorInfo["selected_tickers"][$ticker], $tickerStats["quote"], $tickerStats["quote"]["extendedChangePercent"], $tickerStats["quote"]["changePercent"], $tickerStats["quote"]["ytdChange"])) {
$changeAmount = ($tickerStats["quote"]["extendedChangePercent"] + $tickerStats["quote"]["changePercent"] + $tickerStats["quote"]["ytdChange"])/200;
$indexValue += $sectorInfo["sector_weight"] * $sectorInfo["selected_tickers"][$ticker] * $changeAmount;
}
}
$indexData[$sectorInfo["sector"]] = array("sector_weight" => $sectorInfo["sector_weight"], "sector_coefficient" => 5,
$indexData["Overall"]["sector_value"] += $indexData[$sectorInfo["sector"]]["sector_value"];
}
// Calculate the index factor for better visibility between -1 and +1
$frontIndexData = array();
foreach ($indexData as $sectorName => $sectorIndexData) {
$indexSign = $sectorIndexData["sector_value"];
if ($indexSign < 0) {
$indexSign = - $indexSign;
}
$indexFactor = 1;
for ($i=0; $i <= 10; $i++) {
$indexFactor = pow(10, $i);
if (($indexFactor * $indexSign) > 1) {
$indexFactor = pow(10, $i - 1);
break;
}
}
$frontIndexData[$sectorName] = $sectorIndexData["sector_weight"] * $sectorIndexData["sector_coefficient"] * $sectorIndexData["sector_value"] * $indexFactor;
}
// Write the index file
$indexSectorDir = __DIR__ . self::INDEX_SECTOR_DIR_PREFIX;
if (!is_dir($indexSectorDir)) {mkdir($indexSectorDir, $permission, true);}
$indexSectorFile = $indexSectorDir . $currentTime . ".json";
$indexSectorJson = json_encode($frontIndexData, JSON_FORCE_OBJECT);
$fp = fopen($indexSectorFile, "a+");
fwrite($fp, $indexSectorJson);
fclose($fp);
$sectorDir = __DIR__ . self::LIVE_DATA_DIR;
if (!is_dir($sectorDir)) {mkdir($sectorDir, $permission, true);} // if data directory did not exist
// if text file did not exist
if (!file_exists($sectorDir . "text.txt")){
$handle=fopen($sectorDir . "text.txt", "wb");
fwrite($handle, "d");
fclose($handle);
}
$sectorCoefFile = $sectorDir . "text.txt";
copy($indexSectorFile, $sectorCoefFile);
echo "YAAAY! " . __METHOD__ . " updated sector coefficients successfully !\n";
return $frontIndexData;
}
public static function iexSectorParams(){
$sectorInfos = array(
array(
"sector" => "IT",
"directory" => "information-technology",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"AAPL" => 0.05,
"AMZN" => 0.05,
"GOOGL" => 0.05,
"IBM" => 0.05,
"MSFT" => 0.05,
)
),
array(
"sector" => "Telecommunication",
"directory" => "telecommunication-services",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"VZ" => 0.05,
"CSCO" => 0.05,
"CMCSA" => 0.05,
"T" => 0.05,
"CTL" => 0.05,
)
),
array(
"sector" => "Finance",
"directory" => "financial-services",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"JPM" => 0.05,
"GS" => 0.05,
"V" => 0.05,
"BAC" => 0.05,
"AXP" => 0.05,
)
),
array(
"sector" => "Energy",
"directory" => "energy",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"CVX" => 0.05,
"XOM" => 0.05,
"APA" => 0.05,
"COP" => 0.05,
)
),
array(
"sector" => "Industrials",
"directory" => "industrials",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"CAT" => 0.05,
"FLR" => 0.05,
"GE" => 0.05,
"JEC" => 0.05,
)
),
array(
"sector" => "Materials and Chemicals",
"directory" => "materials-and-chemicals",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"DWDP" => 0.05,
"APD" => 0.05,
"EMN" => 0.05,
"ECL" => 0.05,
"FMC" => 0.05,
)
),
array(
"sector" => "Utilities",
"directory" => "utilities",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"PPL" => 0.05,
"PCG" => 0.05,
"SO" => 0.05,
"WEC" => 0.05,
)
),
array(
"sector" => "Consumer Discretionary",
"directory" => "consumer-discretionary",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"DIS" => 0.05,
"HD" => 0.05,
"BBY" => 0.05,
"CBS" => 0.05,
"CMG" => 0.05,
)
),
array(
"sector" => "Consumer Staples",
"directory" => "consumer-staples",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"PEP" => 0.05,
"PM" => 0.05,
"PG" => 0.05,
"MNST" => 0.05,
"TSN" => 0.05,
)
),
array(
"sector" => "Defense",
"directory" => "defense-and-aerospace",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"BA" => 0.05,
"LMT" => 0.05,
"UTX" => 0.05,
"NOC" => 0.05,
"HON" => 0.05,
)
),
array(
"sector" => "Health",
"directory" => "health-care-and-pharmaceuticals",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"UNH" => 0.05,
"JNJ" => 0.05,
"PFE" => 0.05,
"UHS" => 0.05,
"AET" => 0.05,
"RMD" => 0.05,
)
),
array(
"sector" => "Real Estate",
"directory" => "real-estate",
"sector_weight" => 0.05,
"sector_coefficient" => 5,
"selected_tickers" => array(
"CCI" => 0.05,
"AMT" => 0.05,
"AVB" => 0.05,
"HCP" => 0.05,
"RCL" => 0.05,
"HST" => 0.05,
)
)
);
return $sectorInfos;
}
function __destruct()
{
echo "YAAAY! " . __METHOD__ . " success! \n";
return true;
}
}
</code></pre>
<h3>Output (text.txt)</h3>
<blockquote>
<p>{"Overall":0.05,"IT":0.05,"Telecommunication":0.05,"Finance":0.05,"Energy":0.05,"Industrials":0.05,"Materials
and Chemicals":0.05,"Utilities":0.05,"Consumer
Discretionary":0.05,"Consumer
Staples":0.05,"Defense":0.05,"Health":0.05,"Real Estate":0.05}</p>
</blockquote>
| [] | [
{
"body": "<p>I don't fully understand what your script is doing, but I can offer a few refinements.</p>\n\n<ol>\n<li><p>Regarding <code>$sectorUrl = $baseUrl . implode(\",\", array_keys($sectorInfo[\"selected_tickers\"])) . \"&types=quote&range=1m\";</code>, because you are building a url, I think it would be better practices to implode with <code>%2C</code> to make the RFC folks happy.</p></li>\n<li><p>It doesn't look like a good idea to append json strings after json strings. For this reason, you should not be fwriting with <code>a+</code>. If you mean to consolidate json data on a single json file, then the pre-written data needs to be extracted, decoded, merged with the next data, then re-encoded before updating the file. Otherwise, you will generate invalid json in your .json file.</p></li>\n<li><p>Rather than manually converting negative values to positive with <code>if ($indexSign < 0) {$indexSign = - $indexSign;}</code>, you should be using <a href=\"http://php.net/manual/en/function.abs.php\" rel=\"nofollow noreferrer\">abs()</a> to force values to be positive.</p>\n\n<pre><code>$indexSign = abs($sectorIndexData[\"sector_value\"]);\n</code></pre></li>\n<li><p>The <code>$indexFactor</code> can be determined without iterated mathematics, you can treat it as a string and just count the zeros immediately to the right of the decimal place.</p>\n\n<pre><code>$indexFactor = 10 ** strlen(preg_match('~\\.\\K0+~', $float, $zeros) ? $zeros[0] : 0)\n</code></pre>\n\n<p>The <code>\\K</code> in the pattern means \"restart the fullstring match\" on perhaps it would be clearer for this situation to say \"forget the previously matched characters (the dot)\". \n<code>pow()</code> can be written as <code>**</code> from php5.6+</p></li>\n</ol>\n\n<p>Beyond those few pieces, I don't see much to comment on. As I have stated in recent posts on your questions, always endeavor to minimize total fwrite() calls as much as possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T12:23:02.280",
"Id": "215669",
"ParentId": "215541",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T01:40:08.060",
"Id": "215541",
"Score": "-1",
"Tags": [
"performance",
"beginner",
"php",
"json",
"api"
],
"Title": "Read JSON files, basic calculations and write over another JSON file"
} | 215541 |
<p>I'm working on a simple text based adventure game. I've just finished working on the character creation portion. The code works perfectly fine when run, but I would just like to get some feedback to ensure that it checks off from a professional and efficient standpoint.</p>
<p>The values of the materials, weapons, and spells are representing the amount of damage points each does for further and future calculations with the characters stats later in the game.</p>
<p>The code itself essentially allows you to input a characters name. Then, the strength, stamina, and intellect is randomly generated so that your character build is different at the beginning of each game. Then, once that has finished, the code takes into account the weapon type, the material of the weapon, the spell type and adds additional damage based on the players stats.</p>
<p>I would just like to know if there is a better way of writing my code to make it look cleaner, or if there possibly any concerns that might cause me issues down the road when I add more functionality to the game. Seeing as I am a beginner to C++, I am not incredibly great at determining whether my code is optimal or not.</p>
<pre><code>#include <iostream>
#include <string>
#include <ctime>
using namespace std;
/* Materials Structure */
typedef struct materials {
int wood = 1, oak = 2, maple = 3, ash = 4, bronze = 2, iron = 3, steel = 4, mithril = 5, dragon = 6;
};
/* Weapon Structure */
typedef struct weapons {
int dagger = 2, sword = 3, axe = 4, mace = 5, bow = 3, arrows = 2;
} weapons;
/* Spell Structure */
typedef struct spells {
int fire = 4, frost = 6, dark = 8, chaos = 10;
} spells;
/* Character Structure */
typedef struct character {
string name;
int health = 100, mana = 100, strength, stamina, intellect, weaponAttack, spellAttack, souls = 0;
spells spell;
weapons weapon;
materials material;
} character;
/* Function Declaration */
character characterCreation(string name);
void printInfo(character createChar);
/* Main Function */
int main() {
string characterName;
cout << "Please input character name: ";
cin >> characterName;
srand(time(NULL));
character player = characterCreation(characterName);
printInfo(player);
system("pause");
return 0;
}
/* Function Definition */
character characterCreation(string name) {
character createChar;
createChar.name = name;
createChar.strength = rand() % 5 + 5;
createChar.stamina = rand() % 5 + 5;
createChar.intellect = rand() % 5 + 5;
createChar.health += 2 * createChar.stamina;
createChar.mana += 3 * createChar.intellect;
createChar.weaponAttack = (createChar.weapon.dagger * createChar.material.bronze) + (2 * createChar.strength);
createChar.spellAttack = (createChar.spell.fire + (createChar.intellect * 2));
return createChar;
}
void printInfo(character createChar) {
cout << createChar.name << endl;
cout << createChar.health << endl;
cout << createChar.mana << endl;
cout << createChar.strength << endl;
cout << createChar.stamina << endl;
cout << createChar.intellect << endl;
cout << createChar.weaponAttack << endl;
cout << createChar.spellAttack << endl;
cout << createChar.souls << endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T22:48:18.343",
"Id": "417069",
"Score": "0",
"body": "Take a look at \"ncurses\" library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T02:46:27.830",
"Id": "417078",
"Score": "2",
"body": "If your goal is to write a text adventure (and not just a C++ exercise), have a look at the existing text adventure engines such as TADS and Inform 7. If you still decide to go with C++, understanding the architecture and feature sets in the existing engines will advise you in your own code's larger design."
}
] | [
{
"body": "<pre><code>typedef struct weapons {\n int dagger = 2, sword = 3, axe = 4, mace = 5, bow = 3, arrows = 2;\n} weapons;\n</code></pre>\n\n<p>The <code>typedef struct X { ... } X;</code> pattern is a C-ism; in C++ you don't need the typedef and can just write <code>struct X { ... };</code>.</p>\n\n<p>You're creating a struct type named <code>weapons</code> with a bunch of per-instance member variables. This is almost certainly not what you meant to do. Probably what you meant was</p>\n\n<pre><code>enum class Weapon {\n dagger = 2,\n sword = 3,\n axe = 4,\n mace = 5,\n};\n</code></pre>\n\n<p>so that you could later write</p>\n\n<pre><code>Weapon w = Weapon::sword;\nif (w == Weapon::axe) { ... }\n</code></pre>\n\n<p>What you actually wrote, unfortunately, is simply nonsense.</p>\n\n<hr>\n\n<pre><code>character characterCreation(string name);\n</code></pre>\n\n<p>Look up the C++ notion of \"constructors\" (and also destructors). What you have here would normally be spelled something like</p>\n\n<pre><code>Character::Character(const std::string& name) {\n this->name = name;\n this->strength = rand() % 5 + 5;\n}\n</code></pre>\n\n<p>and so on.</p>\n\n<p>Also consider writing yourself a helper function</p>\n\n<pre><code>int randint(int lo, int hi) {\n return rand() % (hi - lo) + lo;\n}\n</code></pre>\n\n<p>so that you can write simply</p>\n\n<pre><code> this->strength = randint(5, 10);\n</code></pre>\n\n<p>Ninety percent of what we call \"programming\" is just finding sources of repetition and eliminating them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T04:07:07.713",
"Id": "416973",
"Score": "0",
"body": "I apologize, I should have clarified what my code is doing and what my expectations were. My post is not a troll, I prefer not to waste peoples time if I do not have to. I will make edits to the question.\n\nThe numbers on the materials, weapons, and spells simply represent the amount of damage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T04:26:39.410",
"Id": "416975",
"Score": "0",
"body": "Thank you for the insight and helpful post though. I will take a look at more constructors and destructors. I used the struct with the hopes that I would be able to create a large combination of different weapon types/spells, being that my class has only just begun using structs I am not too familiar with constructors/destructors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T05:13:21.130",
"Id": "416977",
"Score": "0",
"body": "`randint(5,10)`, as written, only generates 5 to 9, inclusive. You’d want `hi - lo + 1` to get the full range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T05:33:30.320",
"Id": "416981",
"Score": "3",
"body": "@AJNeufeld: [Half-open ranges](http://wrschneider.github.io/2014/01/07/time-intervals-and-other-ranges-should.html) are the building blocks of C++ (as well as most other programming languages), and the sooner OP gets familiar with them, the better. See [here](https://codereview.stackexchange.com/a/138040/16369) and [here](https://codereview.stackexchange.com/a/210394/16369) for places I've used the phrase \"half-open range\" in previous reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T19:06:49.560",
"Id": "417356",
"Score": "0",
"body": "Nice answer, though rand() shouldn't be used, <random> is recommend instead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T19:18:21.080",
"Id": "417358",
"Score": "0",
"body": "@JVApen: For this beginner's purpose, I think `rand() % (hi - lo) + lo` is the right level of detail. I challenge anyone to write an implementation of `randint(int lo, int hi)` that they think is suitable for this context and yet depends on *anything* out of the `<random>` header. ;) `<random>` tends to [raise](http://www.pcg-random.org/posts/cpp-seeding-surprises.html) more [questions](https://www.reddit.com/r/cpp/comments/7i21sn/til_uniform_int_distribution_is_not_portable/) than it answers. (`rand()` does not answer these questions either; but it avoids conspicuously raising them.)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T02:22:18.220",
"Id": "215543",
"ParentId": "215542",
"Score": "10"
}
},
{
"body": "<ul>\n<li><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't use <code>using namespace std</code> </a></li>\n<li>Your comments add nothing to the program so leave them out. In general comments should tell you <em>why</em> not <em>what</em>. You should try to write <em>self-explaining</em> code. I.e. choose good names for your variables and functions so comments become almost unnecessary.</li>\n<li><code>system(\"pause\");</code> is not portable and can only be used on Windows.</li>\n<li>Unless you depend on the return code you can omit <code>return 0</code> from <code>main</code>. See <a href=\"http://c0x.coding-guidelines.com/5.1.2.2.3.html\" rel=\"noreferrer\">http://c0x.coding-guidelines.com/5.1.2.2.3.html</a>.</li>\n<li>It is better to use <a href=\"https://en.cppreference.com/w/cpp/header/random\" rel=\"noreferrer\"><code>random</code></a> than relying on <code>srand/rand</code>. You're also missing the header for it (<code><cstdlib></code>) and the qualifier (<code>std::</code>). See also <a href=\"https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"noreferrer\">https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful</a>.</li>\n<li><a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">Prefer using <code>\\n</code> over <code>std::endl</code></a></li>\n</ul>\n\n<p>In general you should read more about the Language and Programming. Here are some links to get you started:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list\">C++ book list</a></li>\n<li><a href=\"https://isocpp.org/faq\" rel=\"noreferrer\">C++ Super-FAQ</a></li>\n<li><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md\" rel=\"noreferrer\">C++ Core Guidelines</a></li>\n<li><a href=\"https://en.cppreference.com/w/\" rel=\"noreferrer\">cppreference</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T11:37:15.813",
"Id": "215563",
"ParentId": "215542",
"Score": "5"
}
},
{
"body": "<p>First, try not to declare all your types in the global namespace. Make your \"own\" space. This limits the exposure to other code you might integrate with.</p>\n\n<p>Your <code>materials</code>, <code>weapons</code>, and <code>spells</code> seem to be <code>enum</code> candidates as they are used as values. So use them as enum-values and define there size explicitly. In this case I'm not recommending scoped enums since you want to do calculations easily on there values.</p>\n\n<p>Added a constructor to your <code>character</code>.</p>\n\n<p><code>characterCreation</code> function should take string by universal reference to avoid unnecessary copies.</p>\n\n<p>Have you print method take and <code>ostream</code> so you easily can change to the any stream of your choosing.</p>\n\n<pre><code>namespace YourNamespaceName {\n\nenum materials : int {\n wood = 1, oak = 2, maple = 3, ash = 4, bronze = 2, iron = 3, steel = 4, mithril = 5, dragon = 6\n};\n\nenum weapons : int {\n dagger = 2, sword = 3, axe = 4, mace = 5, bow = 3, arrows = 2\n};\n\nenum spells : int {\n fire = 4, frost = 6, dark = 8, chaos = 10\n};\n\nstruct character {\n explicit character(std::string &&name)\n : name(std::move(name)), strength(rand() % 5 + 5), stamina(rand() % 5 + 5), intellect(rand() % 5 + 5),\n weaponAttack(weapons::dagger * materials::bronze + 2 * strength),\n spellAttack(spells::fire + intellect * 2) {\n health += 2 * stamina;\n mana += 3 * intellect;\n }\n\n std::string name;\n int health = 100, mana = 100, strength, stamina, intellect, weaponAttack, spellAttack, souls = 0;\n};\n\n// Function Declaration\ncharacter characterCreation(std::string &&name);\n\nstd::ostream &printInfo(std::ostream &os, const character &createChar);\n\n} // close YourNamespaceName namespace\n\n// Main Function\n\nint main() {\n std::string characterName;\n std::cout << \"Please input character name: \";\n std::cin >> characterName;\n\n std::srand(std::time(nullptr));\n auto player = YourNamespaceName::characterCreation(std::move(characterName));\n YourNamespaceName::printInfo(std::cout, player);\n\n system(\"pause\");\n return 0;\n}\n\nnamespace YourNamespaceName {\n\n// Function Definition\n\ncharacter characterCreation(std::string &&name) {\n return character(std::move(name));\n}\n\nstd::ostream &printInfo(std::ostream &os, const character &createChar) {\n return os << createChar.name << '\\n'\n << createChar.health << '\\n'\n << createChar.mana << '\\n'\n << createChar.strength << '\\n'\n << createChar.stamina << '\\n'\n << createChar.intellect << '\\n'\n << createChar.weaponAttack << '\\n'\n << createChar.spellAttack << '\\n'\n << createChar.souls << '\\n';\n}\n\n} // close YourNamespaceName namespace\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T14:12:16.727",
"Id": "215569",
"ParentId": "215542",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T01:43:22.063",
"Id": "215542",
"Score": "13",
"Tags": [
"c++",
"beginner",
"game",
"adventure-game"
],
"Title": "Adventure Game (text based) in C++"
} | 215542 |
<p>I am currently study the basic data structure and trying to implement everything as I go. can anyone give me some feedback about class LinkedList how to make the code more elegant. any review are appreciated. </p>
<pre><code>class Node(object):
def __init__(self, data, n=None):
self.val = data
self.next = n
def get(self):
return self.data
def set(self, data):
self.val = data
def get_next_node(self):
return self.next
def set_next_node(self, data):
self.next.val = data
class SingleLinkedList(object):
"""
Single Linked List object
Args:
data(Node): Node
Attributes:
head(Node): single LinkedList head
"""
def __init__(self, data):
self.head = data
def __repr__(self):
"""
:return:
"""
cur = self.head
s = ''
while cur:
s += f'{cur.val}->'
cur = cur.next
return s
def __len__(self):
cur, cnt = self.head, 0
while cur:
cnt += 1
cur = cur.next
return cnt
def append(self, data):
if not self.head:
self.head = Node(data)
return
cur = self.head
while cur.next: cur = cur.next
cur.next = Node(data)
def insert_before_key(self, key, data):
cur = self.head
prev = Node(None)
while cur:
if cur.val == key:
node = Node(data)
node.next = cur
prev.next = node
break
prev = cur
cur = cur.next
self.head = prev.next
def insert_after_key(self, key, data):
cur = self.head
while cur:
if cur.val == key:
node = Node(data)
node.next = cur.next
cur.next = node
cur = cur.next
def delete(self, key):
if not self.head: return
dummy = cur = self.head
prev = None
while cur:
if cur.val == key and prev:
prev.next = cur.next
self.head = dummy
return
elif cur.val == key:
self.head = cur.next
return
prev = cur
cur = cur.next
def search(self, key):
cur = self.head
while cur and cur.val != key:
cur = cur.next
return cur or None
def reverse(self):
cur = self.head
prev = None
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
self.head = prev
</code></pre>
| [] | [
{
"body": "<ol>\n<li>All of your methods on <code>Node</code> are useless. Just use <code>Node.val</code> and <code>Node.next</code> like you already are.</li>\n<li><code>insert_after_key</code> is likely to insert the data multiple times if there are multiple keys. Given how <code>insert_before_key</code> works differently you should <em>test</em> you code with <code>unittest</code>s.</li>\n<li>Your code fails silently. I don't recommend this.</li>\n<li>You can remove the looping from all your functions if you add add a <code>_iter</code> function.</li>\n<li>You can remove the need to loop to fine the key in most of your functions if you add a <code>_find_key</code> function, which returns the previous and next node.</li>\n<li>I'd implement (5) using <code>pairwise</code> (itertools recipe) and use the <code>_iter</code> function.</li>\n<li>You can simplify <code>append</code> if you use the <code>tail</code> itertools recipe.</li>\n<li>You don't seem to have much code to handle empty lists.</li>\n</ol>\n\n\n\n<pre><code>import collections\nimport itertools\n\n\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\ndef tail(n, iterable):\n \"Return an iterator over the last n items\"\n # tail(3, 'ABCDEFG') --> E F G\n return iter(collections.deque(iterable, maxlen=n))\n\n\nclass Node:\n def __init__(self, data, next=None):\n self.val = data\n self.next = next\n\n\nclass SingleLinkedList(object):\n def __init__(self, data):\n self.head = data\n\n def __repr__(self):\n return '->'.join(str(n) for n in self._iter())\n\n def __len__(self):\n return sum(1 for _ in self._iter())\n\n def _iter(self):\n node = self.head\n while node is not None:\n yield node\n node = node.next\n\n def append(self, data):\n if not self.head:\n self.head = Node(data)\n return\n\n last, = tail(self._iter(), 1)\n last.next = Node(data)\n\n def _find_key(self, key):\n if self.head is None:\n raise IndexError('Key not found')\n if key == self.head.value:\n return None, self.head\n\n for prev, curr in pairwise(self._iter()):\n if curr.val == key:\n return prev, curr\n raise IndexError('Key not found')\n\n def insert_before_key(self, key, data):\n prev, curr = self._find_key(key)\n if prev is None:\n self.head = Node(data, self.head)\n else:\n prev.next = Node(data, curr)\n\n def insert_after_key(self, key, data):\n _, node = self._find_key(key)\n node.next = Node(data, node.next)\n\n def delete(self, key):\n prev, curr = _find_key(key)\n if prev is None:\n self.head = curr.next\n else:\n prev.next = curr.next\n\n def search(self, key):\n _, node = _find_key(key)\n return node\n\n def reverse(self):\n cur = self.head\n prev = None\n while cur:\n nxt = cur.next\n cur.next = prev\n prev = cur\n cur = nxt\n self.head = prev\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T07:01:48.897",
"Id": "416991",
"Score": "0",
"body": "thank you.couple fo questions, why use `if prev is None` or `if self.head is None` but not `if not prev` or `if not self.head`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T07:12:31.937",
"Id": "416992",
"Score": "0",
"body": "how to make reverse function without `self.head =prev` on last line?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T14:24:00.507",
"Id": "417020",
"Score": "0",
"body": "@A.Lee I use `if x is None` for when I want to test if `x` is None. And use `if x` for when I want to test if `x` is truthy. Whilst you get the same outcome here, they have different meanings. You'll have to figure that second comment out on your own."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T05:20:47.613",
"Id": "215551",
"ParentId": "215546",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "215551",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T03:49:42.010",
"Id": "215546",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"linked-list"
],
"Title": "Implement LinkedList class in python"
} | 215546 |
<h3>Code Review</h3>
<p>I have two functions of <code>styleAppend</code> and <code>getCss</code>, which generate and append a <code>style</code> tag to a document. </p>
<p>Would you be so kind and review them and help me to possibly make it faster, simpler or more efficient? I'm hoping it would work with earlier versions of IE and other browsers. </p>
<h3>styleAppend</h3>
<pre><code>/*style append*/
styleAppend: function(z) {
var d, e, t, w, f, s, i, q, n, k, j, h, x, y;
x = window.innerWidth; /*window size*/
if (z.c == null || z.m == null || z.g == null) {
return;
}
c = JSON.parse(z.c);
d = '';
s = '';
t = '';
w = '';
i = 99;
f = 51; /*font count*/
q = 20; /*columns size*/
for (n in c) {
for (k in c[n]) {
i++;
d = d.concat('.r', i, ',r', i, ' a{color:#', c[n][k], '}.b', i, ',.b', i, ' a{background-color:#', c[n][k], '}');
}
}
for (j = 1; j < f; j++) {
s = s + '.s'.concat(j, '{font-size:', (j * window.e), 'px}');
} /*font-size*/
for (i = 1; i <= q; i++) {
t = t + '.' + window.y + i + ','; /*width calc*/
w = w + '.' + window.y + i + '{width:' + (100 / (q + 1 - i)) + '%}';
if (i == q) {
t = t.substr(0, t.length - 1);
h = '.ro{margin:0;padding:0;width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:inline-block;}'.concat(t, '{float:left;position:relative;min-height:1px}', w, s, z.g, z.m, d); /*assembled css*/
break;
}
}
s = document.createElement('style'); /*create style tag*/
t = document.createTextNode(h); /*create style text*/
s.appendChild(t); /*append text to tag*/
document.body.appendChild(s); /*append style to body*/
}
</code></pre>
<h3>getCss</h3>
<pre><code>getCSS: function(z) {
var w, y, e, ar, x = [];
Object.keys(z).forEach(function(a, b, c) {
window[a] = null;
x[a] = new XMLHttpRequest();
if (a == 'm') {
w = window.innerWidth; /*window size*/
switch (true) {
case (w < 200):
window.y = 'tiny';
window.e = 0.8; /*tiny*/
break;
case (w >= 200 && w <= 360):
window.y = 'very-small';
window.e = 0.9; /*x small*/
break;
case (w > 360 && w <= 480):
window.y = 'small';
window.e = 1; /*small*/
break;
case (w > 480 && w <= 768):
window.y = 'medium';
window.e = 1.1; /*medium*/
break;
case (w > 768 && w <= 1280):
window.y = 'large';
window.e = 1.3; /*large*/
break;
case (w > 1280 && w <= 1920):
window.y = 'very-large';
window.e = 1.6; /*x large*/
break;
case (w > 1920):
window.y = 'largest';
window.e = 1.9; /*xx large*/
break;
default:
window.y = 'large';
window.e = 1.2; /*default size */
break;
}
url = window.location.origin.concat('/', z[a.toString()], window.y, '.txt');
} else {
url = window.location.origin.concat('/', z[a.toString()]);
}
x[a].open("GET", url, true);
x[a].onreadystatechange = function() {
if (x[a].readyState === 4) {
if (x[a].status === 200 || x[a].status == 0) {
window[a] = x[a].responseText;
if (
z.g === 'dir/styles/z-css-031019-1000.txt' &&
z.m === 'dir/styles/css-' &&
z.c === 'dir/styles/color-hex.txt'
) {
J.styleAppend({
g: window['g'],
m: window['m'],
c: window['c']
}); // style and color
}
}
}
}
x[a].send();
});
}
</code></pre>
<h3>color-hex.txt</h3>
<pre><code>[
["FFFFFF", "F8F8FF", "F7F7F7", "F0F0F0", "F2F2F2", "EDEDED", "EBEBEB", "E5E5E5", "E3E3E3", "E0E0E0"],
["858585", "666666", "545454", "4D4D4D", "474747", "363636", "333333", "222222", "1C1C1C", "050505"],
["EEEE00", "FFD700", "EEC900", "EAC80D", "FFC125", "FFB90F", "EEAD0E", "DAA520", "BFA30C", "B78A00"],
["FFA500", "FF9912", "ED9121", "FF7F00", "FF8000", "EE7600", "EE6A50", "EE5C42", "FF6347", "FF6103"],
["32CD32", "00C957", "43CD80", "00C78C", "1ABC9C", "20B2AA", "03A89E", "00C5CD", "00CED1", "48D1CC"],
["63B8FF", "00B2EE", "1E90FF", "1C86EE", "1C86EE", "1874CD", "436EEE", "4169E1", "3A5FCD", "014B96"],
["EE7AE9", "DA70D6", "BA55D3", "BF3EFF", "B23AEE", "9B30FF", "836FFF", "7A67EE", "9F79EE", "8968CD"],
["FF6EB4", "FF69B4", "EE3A8C", "FF34B3", "FF1493", "EE1289", "CD2990", "D02090", "C71585", "CD1076"],
["FF4500", "EE4000", "FF4040", "EE3B3B", "EE2C2C", "FF0000", "DC143C", "CD0000", "B0171F", "8B2323"],
["FF6A6A", "CD7054", "CD6839", "CD661D", "C76114", "CD5B45", "CD4F39", "CD3333", "CD2626", "CD3700"]
]
</code></pre>
<h3>css-small.txt for small display (Example)</h3>
<pre><code>body {
font-size: 12px!important;
line-height: 190%!important
}
h1 {
font-size: 160%!important
}
h2 {
font-size: 140%!important
}
h3 {
font-size: 120%!important
}
h4 {
font-size: 100%!important
}
h5 {
font-size: 90%!important
}
h6 {
font-size: 80%!important
}
.w-0 {
width: 150px
}
.w-1 {
width: 200px
}
.w-2 {
width: 250px
}
.w-3 {
width: 320px
}
.w-4 {
width: 350px
}
.w-5 {
width: 375px
}
.p-1 {
padding: 1.5px
}
.p-2 {
padding: 3px
}
.p-3 {
padding: 5px
}
.p-4 {
padding: 10px
}
.p-5 {
padding: 15px
}
.m-1 {
margin: 1.5px
}
.m-2 {
margin: 3px
}
.m-3 {
margin: 5px
}
.m-4 {
margin: 10px
}
.m-5 {
margin: 15px
}
.ml-1 {
margin-left: -3px!important
}
.ml-2 {
margin-left: -6px!important
}
.ml-3 {
margin-left: -10px!important
}
.ml-4 {
margin-left: -20px!important
}
.ml-5 {
margin-left: -30px!important
}
.fh-1 {
min-height: 15px;
max-height: 15px
}
.fh-2 {
min-height: 20px;
max-height: 20px
}
.fh-3 {
min-height: 25px;
max-height: 25px
}
.fh-4 {
min-height: 30px;
max-height: 30px
}
.fh-5 {
min-height: 35px;
max-height: 35px
}
.mv-1 {
margin: 1.5px 0
}
.mv-2 {
margin: 3px 0
}
.mv-3 {
margin: 5px 0
}
.mv-4 {
margin: 10px 0
}
.mv-5 {
margin: 20px 0
}
.br-1 {
border-radius: 1.5px
}
.br-2 {
border-radius: 3px
}
.br-3 {
border-radius: 5px
}
.br-4 {
border-radius: 10px
}
.br-5 {
border-radius: 15px
}
.tg-up:after {
margin-left: -15px 0 0 -50px;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-bottom: 30px solid #999
}
</code></pre>
<h3>z-css-031019-1000.txt</h3>
<pre><code>* {
margin: 0;
padding: 0
}
body,
html {
height: 100%
}
body {
font-weight: 400;
overflow-x: hidden;
height: 100%;
min-height: 100%;
margin: 0;
padding: 0;
background: #fff;
font-family: "TradeGothic", -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
font-size: 14px;
line-height: 150%
}
body * {
transition: all 0.4s ease
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Raleway', sans-serif;
margin-top: 0;
text-transform: none;
margin: 0;
padding: 0;
font-weight: 600;
line-height: 200%
}
ul,
li {
list-style: none;
padding: 0px;
margin: 0px
}
a,
a:hover,
a:active,
a:focus {
color: #DA70D6;
outline: none;
border: none;
text-decoration: none
}
a {
color: #014B96;
transition: all 0.4s ease 0s
}
a:focus,
a:hover {
color: #4c7ff0;
-webkit-transition: all .3s ease 0s;
-moz-transition: all 0.4s ease 0s;
-o-transition: all 0.4s ease 0s;
transition: all 0.4s ease 0s
}
pre {
background: #eee;
color: #333;
padding: 10px;
border-radius: 5px;
overflow: scroll
}
article {
margin: 0;
display: inline-block;
min-height: 100%;
min-width: 100%
}
img {
vertical-align: middle
}
a,
a:hover,
a:active,
a:focus {
color: #DA70D6;
outline: none;
border: none;
text-decoration: none
}
a {
color: #014B96;
transition: all 0.4s ease 0s
}
a:focus,
a:hover {
color: #4c7ff0;
-webkit-transition: all .3s ease 0s;
-moz-transition: all 0.4s ease 0s;
-o-transition: all 0.4s ease 0s;
transition: all 0.4s ease 0s
}
ul,
ol {
padding: 0
}
li {
list-style: none
}
input,
textarea {
border: none;
box-shadow: 0px 1px 2px #999;
padding: 5px 0
}
u {
text-decoration: none
}
svg {
font-size: 250%
}
text {
text-rendering: optimizeSpeed;
text-align: justify;
font-size: 14;
white-space: normal!important
}
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none
}
.bn {
color: white!important;
display: inline-block;
margin-bottom: 0;
font-weight: 400;
text-align: center;
vertical-align: middle;
cursor: pointer;
background-image: none;
border: 1px solid transparent;
white-space: nowrap;
padding: 1px 3px;
line-height: 1.4;
border-radius: 3px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none
}
.bn:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color
}
.bn:hover,
.bn:focus {
color: #F7F7F7;
text-decoration: none
}
.bd {
color: #cb2027;
background-color: #f2f2f2;
margin: 3px
}
.lb {
display: inline;
padding: .2em .6em .3em;
font-size: 90%;
font-weight: 700;
line-height: 1;
color: #f2f2f2;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em
}
.lb[href]:hover,
.lb[href]:focus {
color: #f2f2f2;
text-decoration: none;
cursor: pointer
}
.lb:empty {
display: none
}
.bn .lb {
position: relative;
top: -1px
}
.bd {
display: inline-block;
min-width: 10px;
padding: 4px 8px;
font-weight: 700;
color: #f2f2f2;
line-height: 1;
vertical-align: baseline;
white-space: nowrap;
text-align: center;
border-radius: 10px
}
.bd:empty {
display: none
}
.bn .bd {
position: relative;
top: -1px
}
.bn-2 .bd {
top: 0;
padding: 1px 5px
}
a.bd:hover,
a.bd:focus {
color: #f2f2f2;
text-decoration: none;
cursor: pointer
}
.po-0 {
float: left!important
}
.po-1 {
float: center!important
}
.po-2 {
float: right!important
}
.tx-0 {
text-align: left!important
}
.tx-1 {
text-align: center!important
}
.tx-2 {
text-align: right!important
}
.tx-3 {
text-align: justify!important
}
.bx-0 {
box-shadow: none
}
.bx-1 {
padding: 2px 4px;
background-color: #f2f2f2;
box-shadow: 0 1px 2px #000000
}
.bx-2 {
padding: 2px 4px;
position: relative;
box-shadow: 0 1px 4px #A8AFC5
}
.va-b {
vertical-align: baseline!important
}
.di-0 {
display: none!important
}
.di-1 {
display: inline-block
}
.di-2 {
display: block
}
.di-3 {
display: grid
}
.t-11 {
text-shadow: 0 0px 1px #000000
}
.t-12 {
text-shadow: 1px 1px 0 #777777
}
.t-17 {
text-shadow: 1px 1px 4px #000000
}
.t-19 {
text-shadow: 0 2px 0 #000000
}
.t-20 {
text-shadow: 1px 2px 0 #000000
}
.t-21 {
text-shadow: 0 0 1px #999
}
.z0 {
z-index: -1
}
.z1 {
z-index: 11
}
.z2 {
z-index: 12
}
.z3 {
z-index: 13
}
.z4 {
z-index: 14
}
.z5 {
z-index: 15
}
.z6 {
z-index: 16
}
.z7 {
z-index: 17
}
.z8 {
z-index: 18
}
.z9 {
z-index: 19
}
.o0 {
opacity: 0
}
.o1 {
opacity: 1
}
.o2 {
opacity: .12
}
.o3 {
opacity: .3
}
.o4 {
opacity: .4
}
.o5 {
opacity: .5
}
.o6 {
opacity: .6
}
.o7 {
opacity: .7
}
.o8 {
opacity: .8
}
.o9 {
opacity: .9
}
.o0:hover,
.o1:hover,
.o2:hover,
.o3:hover,
.o4:hover,
.o5:hover,
.o6:hover,
.o7:hover,
.o8:hover,
.o9:hover {
opacity: 1;
cursor: pointer
}
.oc {
opacity: 0
}
.rl:hover .oc {
opacity: 1;
border-bottom: 2px solid #eeeeee
}
.cu-no {
cursor: none!important
}
.cu-po {
cursor: pointer
}
.cu-cr {
cursor: crosshair
}
.cu-ce {
cursor: cell
}
.cu-he {
cursor: help
}
.cu-mo {
cursor: move
}
.cu-wr {
cursor: w-resize
}
.cu-er {
cursor: e-resize
}
.cu-cm {
cursor: context-menu
}
.cu-zi {
cursor: zoom-in;
cursor: -webkit-zoom-in;
cursor: -moz-zoom-in
}
.cu-zo {
cursor: zoom-out;
cursor: -webkit-zoom-out;
cursor: -moz-zoom-out
}
.cu-gg {
cursor: grabbing
}
.cu-gr {
cursor: grab
}
.rl {
position: relative
}
.fx-tp-rt {
position: fixed;
right: 0;
top: 0
}
.fx-tp-lt {
position: fixed;
left: 0;
top: 0
}
.fx-tp-ct {
position: fixed;
left: 0;
top: 0;
right: 0;
margin-left: auto;
margin-right: auto;
text-align: center
}
.fx-bt-ct {
position: fixed;
left: 0;
bottom: 0;
right: 0;
margin-left: auto;
margin-right: auto;
text-align: center
}
.ab {
position: absolute;
z-index: 9
}
.ab-bt {
position: absolute;
right: 0;
left: 0;
bottom: 0;
overflow: scroll
}
.ab-tp {
position: absolute;
right: 0;
left: 0;
top: 0;
overflow: scroll
}
.fw-1 {
font-weight: 100
}
.fw-2 {
font-weight: 200
}
.fw-3 {
font-weight: 300
}
.fw-4 {
font-weight: 400
}
.fw-5 {
font-weight: 500
}
.fw-6 {
font-weight: 600
}
.fw-7 {
font-weight: 700
}
.fw-8 {
font-weight: 800
}
.fw-9 {
font-weight: 900
}
.sq-1 {
display: inline-block;
margin: 0;
padding: 10px;
box-shadow: 0 1px 4px #A8AFC5
}
.sq-2 {
display: inline-block;
margin: 0 -2px;
padding: 4px 8px;
box-shadow: 0 1px 2px #A8AFC5;
color: #fff;
text-shadow: 0 0px 1px #000000
}
.of-sc {
overflow: scroll!important
}
.w-5x {
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box
}
.mh-30 {
min-height: 30px;
max-height: 30px;
overflow: auto
}
.mh-50 {
min-height: 50px;
max-height: 50px;
overflow: auto
}
.tg-up {
display: inline-block
}
.tg-up:after {
content: "";
display: inline-block;
width: 0;
height: 0
}
.vs-hd {
visibility: hidden
}
.g-3 {
background: linear-gradient(to right, #CD0000, #EEEE00, #32CD32);
background-repeat: no-repeat;
transition: none
}
.g-3:hover {
background: linear-gradient(to right, #CD0000, #ED9121, #EEEE00, #E0E0E0, #FFF, #F5F5F5, #63B8FF, #4169E1, #32CD32)
}
.img-1 {
background-position: center center;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover
}
.img-2 {
background-repeat: no-repeat;
background-size: 100%
}
.vc {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0;
overflow: hidden
}
.vc iframe,
.video-container object,
.video-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%
}
/*menu*/
.ln,
.ln .cl-bn {
left: 0
}
.rn,
.rn .cl-bn {
right: 0
}
.ln,
.rn {
height: 100%;
width: 0;
position: fixed;
top: 0;
background-color: #333;
overflow-x: hidden;
transition: 0.3s
}
.ln a,
.rn a {
text-decoration: none;
color: #f2f2f2;
display: block;
transition: 0.2s
}
.ln a:hover,
.rn a:hover {
color: #fff
}
.ln .cl-bn,
.rn .cl-bn {
position: absolute;
top: 0
}
/*google custom search*/
.cse .gsc-search-button input.gsc-search-button-v2,
input.gsc-search-button-v2 {
height: 26px!important;
margin-top: 0!important;
min-width: 13px!important;
padding: 5px 26px!important;
width: 68px!important
}
.cse .gsc-search-button-v2,
.gsc-search-button-v2 {
box-sizing: content-box;
min-width: 13px!important;
min-height: 16px!important;
cursor: pointer;
border-radius: 20px
}
.gsc-search-button-v2 svg {
vertical-align: middle
}
.gs-title {
line-height: normal!important
}
.gsc-search-box-tools .gsc-search-box .gsc-input {
padding: 5px!important;
color: #4169E1!important;
border-radius: 20px
}
.gsc-input-box {
background: none!important;
border: none!important
}
@media print {
@page {
margin: 0.25in;
}
body {
-webkit-print-color-adjust: exact;
background-color: #fff
}
.pr-no {
display: none
}
}
</code></pre>
<h3>Output</h3>
<pre><code><style>
.ro {
margin: 0;
padding: 0;
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
display: inline-block;
}
.a51,
.a52,
.a53,
.a54,
.a55,
.a56,
.a57,
.a58,
.a59,
.a510,
.a511,
.a512,
.a513,
.a514,
.a515,
.a516,
.a517,
.a518,
.a519,
.a520 {
float: left;
position: relative;
min-height: 1px
}
.a51 {
width: 5%
}
.a52 {
width: 5.2631578947368425%
}
.a53 {
width: 5.555555555555555%
}
.a54 {
width: 5.882352941176471%
}
.a55 {
width: 6.25%
}
.a56 {
width: 6.666666666666667%
}
.a57 {
width: 7.142857142857143%
}
.a58 {
width: 7.6923076923076925%
}
.a59 {
width: 8.333333333333334%
}
.a510 {
width: 9.090909090909092%
}
.a511 {
width: 10%
}
.a512 {
width: 11.11111111111111%
}
.a513 {
width: 12.5%
}
.a514 {
width: 14.285714285714286%
}
.a515 {
width: 16.666666666666668%
}
.a516 {
width: 20%
}
.a517 {
width: 25%
}
.a518 {
width: 33.333333333333336%
}
.a519 {
width: 50%
}
.a520 {
width: 100%
}
.s1 {
font-size: 1.3px
}
.s2 {
font-size: 2.6px
}
.s3 {
font-size: 3.9000000000000004px
}
.s4 {
font-size: 5.2px
}
.s5 {
font-size: 6.5px
}
.s6 {
font-size: 7.800000000000001px
}
.s7 {
font-size: 9.1px
}
.s8 {
font-size: 10.4px
}
.s9 {
font-size: 11.700000000000001px
}
.s10 {
font-size: 13px
}
.s11 {
font-size: 14.3px
}
.s12 {
font-size: 15.600000000000001px
}
.s13 {
font-size: 16.900000000000002px
}
.s14 {
font-size: 18.2px
}
.s15 {
font-size: 19.5px
}
.s16 {
font-size: 20.8px
}
.s17 {
font-size: 22.1px
}
.s18 {
font-size: 23.400000000000002px
}
.s19 {
font-size: 24.7px
}
.s20 {
font-size: 26px
}
.s21 {
font-size: 27.3px
}
.s22 {
font-size: 28.6px
}
.s23 {
font-size: 29.900000000000002px
}
.s24 {
font-size: 31.200000000000003px
}
.s25 {
font-size: 32.5px
}
.s26 {
font-size: 33.800000000000004px
}
.s27 {
font-size: 35.1px
}
.s28 {
font-size: 36.4px
}
.s29 {
font-size: 37.7px
}
.s30 {
font-size: 39px
}
.s31 {
font-size: 40.300000000000004px
}
.s32 {
font-size: 41.6px
}
.s33 {
font-size: 42.9px
}
.s34 {
font-size: 44.2px
}
.s35 {
font-size: 45.5px
}
.s36 {
font-size: 46.800000000000004px
}
.s37 {
font-size: 48.1px
}
.s38 {
font-size: 49.4px
}
.s39 {
font-size: 50.7px
}
.s40 {
font-size: 52px
}
.s41 {
font-size: 53.300000000000004px
}
.s42 {
font-size: 54.6px
}
.s43 {
font-size: 55.9px
}
.s44 {
font-size: 57.2px
}
.s45 {
font-size: 58.5px
}
.s46 {
font-size: 59.800000000000004px
}
.s47 {
font-size: 61.1px
}
.s48 {
font-size: 62.400000000000006px
}
.s49 {
font-size: 63.7px
}
.s50 {
font-size: 65px
}
* {
margin: 0;
padding: 0
}
body,
html {
height: 100%
}
body {
font-weight: 400;
overflow-x: hidden;
height: 100%;
min-height: 100%;
margin: 0;
padding: 0;
background: #fff;
font-family: "TradeGothic", -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
font-size: 14px;
line-height: 150%
}
body * {
transition: all 0.4s ease
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Raleway', sans-serif;
margin-top: 0;
text-transform: none;
margin: 0;
padding: 0;
font-weight: 600;
line-height: 200%
}
ul,
li {
list-style: none;
padding: 0px;
margin: 0px
}
a,
a:hover,
a:active,
a:focus {
color: #DA70D6;
outline: none;
border: none;
text-decoration: none
}
a {
color: #014B96;
transition: all 0.4s ease 0s
}
a:focus,
a:hover {
color: #4c7ff0;
-webkit-transition: all .3s ease 0s;
-moz-transition: all 0.4s ease 0s;
-o-transition: all 0.4s ease 0s;
transition: all 0.4s ease 0s
}
pre {
background: #eee;
color: #333;
padding: 10px;
border-radius: 5px;
overflow: scroll
}
article {
margin: 0;
display: inline-block;
min-height: 100%;
min-width: 100%
}
img {
vertical-align: middle
}
a,
a:hover,
a:active,
a:focus {
color: #DA70D6;
outline: none;
border: none;
text-decoration: none
}
a {
color: #014B96;
transition: all 0.4s ease 0s
}
a:focus,
a:hover {
color: #4c7ff0;
-webkit-transition: all .3s ease 0s;
-moz-transition: all 0.4s ease 0s;
-o-transition: all 0.4s ease 0s;
transition: all 0.4s ease 0s
}
ul,
ol {
padding: 0
}
li {
list-style: none
}
input,
textarea {
border: none;
box-shadow: 0px 1px 2px #999;
padding: 5px 0
}
u {
text-decoration: none
}
svg {
font-size: 250%
}
text {
text-rendering: optimizeSpeed;
text-align: justify;
font-size: 14;
white-space: normal!important
}
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none
}
.bn {
color: white!important;
display: inline-block;
margin-bottom: 0;
font-weight: 400;
text-align: center;
vertical-align: middle;
cursor: pointer;
background-image: none;
border: 1px solid transparent;
white-space: nowrap;
padding: 1px 3px;
line-height: 1.4;
border-radius: 3px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none
}
.bn:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color
}
.bn:hover,
.bn:focus {
color: #F7F7F7;
text-decoration: none
}
.bd {
color: #cb2027;
background-color: #f2f2f2;
margin: 3px
}
.lb {
display: inline;
padding: .2em .6em .3em;
font-size: 90%;
font-weight: 700;
line-height: 1;
color: #f2f2f2;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em
}
.lb[href]:hover,
.lb[href]:focus {
color: #f2f2f2;
text-decoration: none;
cursor: pointer
}
.lb:empty {
display: none
}
.bn .lb {
position: relative;
top: -1px
}
.bd {
display: inline-block;
min-width: 10px;
padding: 4px 8px;
font-weight: 700;
color: #f2f2f2;
line-height: 1;
vertical-align: baseline;
white-space: nowrap;
text-align: center;
border-radius: 10px
}
.bd:empty {
display: none
}
.bn .bd {
position: relative;
top: -1px
}
.bn-2 .bd {
top: 0;
padding: 1px 5px
}
a.bd:hover,
a.bd:focus {
color: #f2f2f2;
text-decoration: none;
cursor: pointer
}
.po-0 {
float: left!important
}
.po-1 {
float: center!important
}
.po-2 {
float: right!important
}
.tx-0 {
text-align: left!important
}
.tx-1 {
text-align: center!important
}
.tx-2 {
text-align: right!important
}
.tx-3 {
text-align: justify!important
}
.bx-0 {
box-shadow: none
}
.bx-1 {
padding: 2px 4px;
background-color: #f2f2f2;
box-shadow: 0 1px 2px #000000
}
.bx-2 {
padding: 2px 4px;
position: relative;
box-shadow: 0 1px 4px #A8AFC5
}
.va-b {
vertical-align: baseline!important
}
.di-0 {
display: none!important
}
.di-1 {
display: inline-block
}
.di-2 {
display: block
}
.di-3 {
display: grid
}
.t-11 {
text-shadow: 0 0px 1px #000000
}
.t-12 {
text-shadow: 1px 1px 0 #777777
}
.t-17 {
text-shadow: 1px 1px 4px #000000
}
.t-19 {
text-shadow: 0 2px 0 #000000
}
.t-20 {
text-shadow: 1px 2px 0 #000000
}
.t-21 {
text-shadow: 0 0 1px #999
}
.z0 {
z-index: -1
}
.z1 {
z-index: 11
}
.z2 {
z-index: 12
}
.z3 {
z-index: 13
}
.z4 {
z-index: 14
}
.z5 {
z-index: 15
}
.z6 {
z-index: 16
}
.z7 {
z-index: 17
}
.z8 {
z-index: 18
}
.z9 {
z-index: 19
}
.o0 {
opacity: 0
}
.o1 {
opacity: 1
}
.o2 {
opacity: .12
}
.o3 {
opacity: .3
}
.o4 {
opacity: .4
}
.o5 {
opacity: .5
}
.o6 {
opacity: .6
}
.o7 {
opacity: .7
}
.o8 {
opacity: .8
}
.o9 {
opacity: .9
}
.o0:hover,
.o1:hover,
.o2:hover,
.o3:hover,
.o4:hover,
.o5:hover,
.o6:hover,
.o7:hover,
.o8:hover,
.o9:hover {
opacity: 1;
cursor: pointer
}
.oc {
opacity: 0
}
.rl:hover .oc {
opacity: 1;
border-bottom: 2px solid #eeeeee
}
.cu-no {
cursor: none!important
}
.cu-po {
cursor: pointer
}
.cu-cr {
cursor: crosshair
}
.cu-ce {
cursor: cell
}
.cu-he {
cursor: help
}
.cu-mo {
cursor: move
}
.cu-wr {
cursor: w-resize
}
.cu-er {
cursor: e-resize
}
.cu-cm {
cursor: context-menu
}
.cu-zi {
cursor: zoom-in;
cursor: -webkit-zoom-in;
cursor: -moz-zoom-in
}
.cu-zo {
cursor: zoom-out;
cursor: -webkit-zoom-out;
cursor: -moz-zoom-out
}
.cu-gg {
cursor: grabbing
}
.cu-gr {
cursor: grab
}
.rl {
position: relative
}
.fx-tp-rt {
position: fixed;
right: 0;
top: 0
}
.fx-tp-lt {
position: fixed;
left: 0;
top: 0
}
.fx-tp-ct {
position: fixed;
left: 0;
top: 0;
right: 0;
margin-left: auto;
margin-right: auto;
text-align: center
}
.fx-bt-ct {
position: fixed;
left: 0;
bottom: 0;
right: 0;
margin-left: auto;
margin-right: auto;
text-align: center
}
.ab {
position: absolute;
z-index: 9
}
.ab-bt {
position: absolute;
right: 0;
left: 0;
bottom: 0;
overflow: scroll
}
.ab-tp {
position: absolute;
right: 0;
left: 0;
top: 0;
overflow: scroll
}
.fw-1 {
font-weight: 100
}
.fw-2 {
font-weight: 200
}
.fw-3 {
font-weight: 300
}
.fw-4 {
font-weight: 400
}
.fw-5 {
font-weight: 500
}
.fw-6 {
font-weight: 600
}
.fw-7 {
font-weight: 700
}
.fw-8 {
font-weight: 800
}
.fw-9 {
font-weight: 900
}
.sq-1 {
display: inline-block;
margin: 0;
padding: 10px;
box-shadow: 0 1px 4px #A8AFC5
}
.sq-2 {
display: inline-block;
margin: 0 -2px;
padding: 4px 8px;
box-shadow: 0 1px 2px #A8AFC5;
color: #fff;
text-shadow: 0 0px 1px #000000
}
.of-sc {
overflow: scroll!important
}
.w-5x {
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box
}
.mh-30 {
min-height: 30px;
max-height: 30px;
overflow: auto
}
.mh-50 {
min-height: 50px;
max-height: 50px;
overflow: auto
}
.tg-up {
display: inline-block
}
.tg-up:after {
content: "";
display: inline-block;
width: 0;
height: 0
}
.vs-hd {
visibility: hidden
}
.g-3 {
background: linear-gradient(to right, #CD0000, #EEEE00, #32CD32);
background-repeat: no-repeat;
transition: none
}
.g-3:hover {
background: linear-gradient(to right, #CD0000, #ED9121, #EEEE00, #E0E0E0, #FFF, #F5F5F5, #63B8FF, #4169E1, #32CD32)
}
.img-1 {
background-position: center center;
background-repeat: no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover
}
.img-2 {
background-repeat: no-repeat;
background-size: 100%
}
.vc {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0;
overflow: hidden
}
.vc iframe,
.video-container object,
.video-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%
}
/*menu*/
.ln,
.ln .cl-bn {
left: 0
}
.rn,
.rn .cl-bn {
right: 0
}
.ln,
.rn {
height: 100%;
width: 0;
position: fixed;
top: 0;
background-color: #333;
overflow-x: hidden;
transition: 0.3s
}
.ln a,
.rn a {
text-decoration: none;
color: #f2f2f2;
display: block;
transition: 0.2s
}
.ln a:hover,
.rn a:hover {
color: #fff
}
.ln .cl-bn,
.rn .cl-bn {
position: absolute;
top: 0
}
/*google custom search*/
.cse .gsc-search-button input.gsc-search-button-v2,
input.gsc-search-button-v2 {
height: 26px!important;
margin-top: 0!important;
min-width: 13px!important;
padding: 5px 26px!important;
width: 68px!important
}
.cse .gsc-search-button-v2,
.gsc-search-button-v2 {
box-sizing: content-box;
min-width: 13px!important;
min-height: 16px!important;
cursor: pointer;
border-radius: 20px
}
.gsc-search-button-v2 svg {
vertical-align: middle
}
.gs-title {
line-height: normal!important
}
.gsc-search-box-tools .gsc-search-box .gsc-input {
padding: 5px!important;
color: #4169E1!important;
border-radius: 20px
}
.gsc-input-box {
background: none!important;
border: none!important
}
@media print {
@page {
margin: 0.25in;
}
body {
-webkit-print-color-adjust: exact;
background-color: #fff
}
.pr-no {
display: none
}
}
body {
font-size: 14px!important;
line-height: 220%!important
}
h1 {
font-size: 180%!important
}
h2 {
font-size: 160%!important
}
h3 {
font-size: 140%!important
}
h4 {
font-size: 120%!important
}
h5 {
font-size: 100%!important
}
h6 {
font-size: 75%!important
}
.w-0 {
width: 200px
}
.w-1 {
width: 250px
}
.w-2 {
width: 300px
}
.w-3 {
width: 375px
}
.w-4 {
width: 410px
}
.w-5 {
width: 420px
}
.p-1 {
padding: 3px
}
.p-2 {
padding: 5px
}
.p-3 {
padding: 8px
}
.p-4 {
padding: 12px
}
.p-5 {
padding: 20px
}
.m-1 {
margin: 3px
}
.m-2 {
margin: 5px
}
.m-3 {
margin: 8px
}
.m-4 {
margin: 12px
}
.m-5 {
margin: 20px
}
.ml-1 {
margin-left: -6px!important
}
.ml-2 {
margin-left: -10px!important
}
.ml-3 {
margin-left: -16px!important
}
.ml-4 {
margin-left: -24px!important
}
.ml-5 {
margin-left: -36px!important
}
.fh-1 {
min-height: 20px;
max-height: 20px
}
.fh-2 {
min-height: 25px;
max-height: 25px
}
.fh-3 {
min-height: 30px;
max-height: 30px
}
.fh-4 {
min-height: 35px;
max-height: 35px
}
.fh-5 {
min-height: 40px;
max-height: 40px
}
.mv-1 {
margin: 3px 0
}
.mv-2 {
margin: 5px 0
}
.mv-3 {
margin: 8px 0
}
.mv-4 {
margin: 12px 0
}
.mv-5 {
margin: 25px 0
}
.br-1 {
border-radius: 3px
}
.br-2 {
border-radius: 5px
}
.br-3 {
border-radius: 8px
}
.br-4 {
border-radius: 12px
}
.br-5 {
border-radius: 20px
}
.tg-up:after {
margin-left: -15px 0 0 -50px;
border-left: 15px solid transparent;
border-right: 15px solid transparent;
border-bottom: 45px solid #999
}
.r100,
r100 a {
color: #FFFFFF
}
.b100,
.b100 a {
background-color: #FFFFFF
}
.r101,
r101 a {
color: #F8F8FF
}
.b101,
.b101 a {
background-color: #F8F8FF
}
.r102,
r102 a {
color: #F7F7F7
}
.b102,
.b102 a {
background-color: #F7F7F7
}
.r103,
r103 a {
color: #F0F0F0
}
.b103,
.b103 a {
background-color: #F0F0F0
}
.r104,
r104 a {
color: #F2F2F2
}
.b104,
.b104 a {
background-color: #F2F2F2
}
.r105,
r105 a {
color: #EDEDED
}
.b105,
.b105 a {
background-color: #EDEDED
}
.r106,
r106 a {
color: #EBEBEB
}
.b106,
.b106 a {
background-color: #EBEBEB
}
.r107,
r107 a {
color: #E5E5E5
}
.b107,
.b107 a {
background-color: #E5E5E5
}
.r108,
r108 a {
color: #E3E3E3
}
.b108,
.b108 a {
background-color: #E3E3E3
}
.r109,
r109 a {
color: #E0E0E0
}
.b109,
.b109 a {
background-color: #E0E0E0
}
.r110,
r110 a {
color: #858585
}
.b110,
.b110 a {
background-color: #858585
}
.r111,
r111 a {
color: #666666
}
.b111,
.b111 a {
background-color: #666666
}
.r112,
r112 a {
color: #545454
}
.b112,
.b112 a {
background-color: #545454
}
.r113,
r113 a {
color: #4D4D4D
}
.b113,
.b113 a {
background-color: #4D4D4D
}
.r114,
r114 a {
color: #474747
}
.b114,
.b114 a {
background-color: #474747
}
.r115,
r115 a {
color: #363636
}
.b115,
.b115 a {
background-color: #363636
}
.r116,
r116 a {
color: #333333
}
.b116,
.b116 a {
background-color: #333333
}
.r117,
r117 a {
color: #222222
}
.b117,
.b117 a {
background-color: #222222
}
.r118,
r118 a {
color: #1C1C1C
}
.b118,
.b118 a {
background-color: #1C1C1C
}
.r119,
r119 a {
color: #050505
}
.b119,
.b119 a {
background-color: #050505
}
.r120,
r120 a {
color: #EEEE00
}
.b120,
.b120 a {
background-color: #EEEE00
}
.r121,
r121 a {
color: #FFD700
}
.b121,
.b121 a {
background-color: #FFD700
}
.r122,
r122 a {
color: #EEC900
}
.b122,
.b122 a {
background-color: #EEC900
}
.r123,
r123 a {
color: #EAC80D
}
.b123,
.b123 a {
background-color: #EAC80D
}
.r124,
r124 a {
color: #FFC125
}
.b124,
.b124 a {
background-color: #FFC125
}
.r125,
r125 a {
color: #FFB90F
}
.b125,
.b125 a {
background-color: #FFB90F
}
.r126,
r126 a {
color: #EEAD0E
}
.b126,
.b126 a {
background-color: #EEAD0E
}
.r127,
r127 a {
color: #DAA520
}
.b127,
.b127 a {
background-color: #DAA520
}
.r128,
r128 a {
color: #BFA30C
}
.b128,
.b128 a {
background-color: #BFA30C
}
.r129,
r129 a {
color: #B78A00
}
.b129,
.b129 a {
background-color: #B78A00
}
.r130,
r130 a {
color: #FFA500
}
.b130,
.b130 a {
background-color: #FFA500
}
.r131,
r131 a {
color: #FF9912
}
.b131,
.b131 a {
background-color: #FF9912
}
.r132,
r132 a {
color: #ED9121
}
.b132,
.b132 a {
background-color: #ED9121
}
.r133,
r133 a {
color: #FF7F00
}
.b133,
.b133 a {
background-color: #FF7F00
}
.r134,
r134 a {
color: #FF8000
}
.b134,
.b134 a {
background-color: #FF8000
}
.r135,
r135 a {
color: #EE7600
}
.b135,
.b135 a {
background-color: #EE7600
}
.r136,
r136 a {
color: #EE6A50
}
.b136,
.b136 a {
background-color: #EE6A50
}
.r137,
r137 a {
color: #EE5C42
}
.b137,
.b137 a {
background-color: #EE5C42
}
.r138,
r138 a {
color: #FF6347
}
.b138,
.b138 a {
background-color: #FF6347
}
.r139,
r139 a {
color: #FF6103
}
.b139,
.b139 a {
background-color: #FF6103
}
.r140,
r140 a {
color: #32CD32
}
.b140,
.b140 a {
background-color: #32CD32
}
.r141,
r141 a {
color: #00C957
}
.b141,
.b141 a {
background-color: #00C957
}
.r142,
r142 a {
color: #43CD80
}
.b142,
.b142 a {
background-color: #43CD80
}
.r143,
r143 a {
color: #00C78C
}
.b143,
.b143 a {
background-color: #00C78C
}
.r144,
r144 a {
color: #1ABC9C
}
.b144,
.b144 a {
background-color: #1ABC9C
}
.r145,
r145 a {
color: #20B2AA
}
.b145,
.b145 a {
background-color: #20B2AA
}
.r146,
r146 a {
color: #03A89E
}
.b146,
.b146 a {
background-color: #03A89E
}
.r147,
r147 a {
color: #00C5CD
}
.b147,
.b147 a {
background-color: #00C5CD
}
.r148,
r148 a {
color: #00CED1
}
.b148,
.b148 a {
background-color: #00CED1
}
.r149,
r149 a {
color: #48D1CC
}
.b149,
.b149 a {
background-color: #48D1CC
}
.r150,
r150 a {
color: #63B8FF
}
.b150,
.b150 a {
background-color: #63B8FF
}
.r151,
r151 a {
color: #00B2EE
}
.b151,
.b151 a {
background-color: #00B2EE
}
.r152,
r152 a {
color: #1E90FF
}
.b152,
.b152 a {
background-color: #1E90FF
}
.r153,
r153 a {
color: #1C86EE
}
.b153,
.b153 a {
background-color: #1C86EE
}
.r154,
r154 a {
color: #1C86EE
}
.b154,
.b154 a {
background-color: #1C86EE
}
.r155,
r155 a {
color: #1874CD
}
.b155,
.b155 a {
background-color: #1874CD
}
.r156,
r156 a {
color: #436EEE
}
.b156,
.b156 a {
background-color: #436EEE
}
.r157,
r157 a {
color: #4169E1
}
.b157,
.b157 a {
background-color: #4169E1
}
.r158,
r158 a {
color: #3A5FCD
}
.b158,
.b158 a {
background-color: #3A5FCD
}
.r159,
r159 a {
color: #014B96
}
.b159,
.b159 a {
background-color: #014B96
}
.r160,
r160 a {
color: #EE7AE9
}
.b160,
.b160 a {
background-color: #EE7AE9
}
.r161,
r161 a {
color: #DA70D6
}
.b161,
.b161 a {
background-color: #DA70D6
}
.r162,
r162 a {
color: #BA55D3
}
.b162,
.b162 a {
background-color: #BA55D3
}
.r163,
r163 a {
color: #BF3EFF
}
.b163,
.b163 a {
background-color: #BF3EFF
}
.r164,
r164 a {
color: #B23AEE
}
.b164,
.b164 a {
background-color: #B23AEE
}
.r165,
r165 a {
color: #9B30FF
}
.b165,
.b165 a {
background-color: #9B30FF
}
.r166,
r166 a {
color: #836FFF
}
.b166,
.b166 a {
background-color: #836FFF
}
.r167,
r167 a {
color: #7A67EE
}
.b167,
.b167 a {
background-color: #7A67EE
}
.r168,
r168 a {
color: #9F79EE
}
.b168,
.b168 a {
background-color: #9F79EE
}
.r169,
r169 a {
color: #8968CD
}
.b169,
.b169 a {
background-color: #8968CD
}
.r170,
r170 a {
color: #FF6EB4
}
.b170,
.b170 a {
background-color: #FF6EB4
}
.r171,
r171 a {
color: #FF69B4
}
.b171,
.b171 a {
background-color: #FF69B4
}
.r172,
r172 a {
color: #EE3A8C
}
.b172,
.b172 a {
background-color: #EE3A8C
}
.r173,
r173 a {
color: #FF34B3
}
.b173,
.b173 a {
background-color: #FF34B3
}
.r174,
r174 a {
color: #FF1493
}
.b174,
.b174 a {
background-color: #FF1493
}
.r175,
r175 a {
color: #EE1289
}
.b175,
.b175 a {
background-color: #EE1289
}
.r176,
r176 a {
color: #CD2990
}
.b176,
.b176 a {
background-color: #CD2990
}
.r177,
r177 a {
color: #D02090
}
.b177,
.b177 a {
background-color: #D02090
}
.r178,
r178 a {
color: #C71585
}
.b178,
.b178 a {
background-color: #C71585
}
.r179,
r179 a {
color: #CD1076
}
.b179,
.b179 a {
background-color: #CD1076
}
.r180,
r180 a {
color: #FF4500
}
.b180,
.b180 a {
background-color: #FF4500
}
.r181,
r181 a {
color: #EE4000
}
.b181,
.b181 a {
background-color: #EE4000
}
.r182,
r182 a {
color: #FF4040
}
.b182,
.b182 a {
background-color: #FF4040
}
.r183,
r183 a {
color: #EE3B3B
}
.b183,
.b183 a {
background-color: #EE3B3B
}
.r184,
r184 a {
color: #EE2C2C
}
.b184,
.b184 a {
background-color: #EE2C2C
}
.r185,
r185 a {
color: #FF0000
}
.b185,
.b185 a {
background-color: #FF0000
}
.r186,
r186 a {
color: #DC143C
}
.b186,
.b186 a {
background-color: #DC143C
}
.r187,
r187 a {
color: #CD0000
}
.b187,
.b187 a {
background-color: #CD0000
}
.r188,
r188 a {
color: #B0171F
}
.b188,
.b188 a {
background-color: #B0171F
}
.r189,
r189 a {
color: #8B2323
}
.b189,
.b189 a {
background-color: #8B2323
}
.r190,
r190 a {
color: #FF6A6A
}
.b190,
.b190 a {
background-color: #FF6A6A
}
.r191,
r191 a {
color: #CD7054
}
.b191,
.b191 a {
background-color: #CD7054
}
.r192,
r192 a {
color: #CD6839
}
.b192,
.b192 a {
background-color: #CD6839
}
.r193,
r193 a {
color: #CD661D
}
.b193,
.b193 a {
background-color: #CD661D
}
.r194,
r194 a {
color: #C76114
}
.b194,
.b194 a {
background-color: #C76114
}
.r195,
r195 a {
color: #CD5B45
}
.b195,
.b195 a {
background-color: #CD5B45
}
.r196,
r196 a {
color: #CD4F39
}
.b196,
.b196 a {
background-color: #CD4F39
}
.r197,
r197 a {
color: #CD3333
}
.b197,
.b197 a {
background-color: #CD3333
}
.r198,
r198 a {
color: #CD2626
}
.b198,
.b198 a {
background-color: #CD2626
}
.r199,
r199 a {
color: #CD3700
}
.b199,
.b199 a {
background-color: #CD3700
}
</style>
</code></pre>
| [] | [
{
"body": "<pre><code>var d, e, t, w, f, s, i, q, n, k, j, h, x, y;\n</code></pre>\n\n<p>It's impossible to write fast code if you can't understand it.</p>\n\n<p>My advice would be to focus on understandable code, then optimize the bottlenecks as needed. If you need to reduce the size of the script, you can use a minifier/uglifier for that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T20:26:28.700",
"Id": "215703",
"ParentId": "215549",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215703",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T05:13:17.500",
"Id": "215549",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"html",
"css",
"dom"
],
"Title": "Generate a Style Tag and Append to a Document"
} | 215549 |
<p>First, I am aware that this can be done in sklearn - I'm intentionally trying to do it myself.</p>
<p>I am trying to extract the eigenvectors from <code>np.linalg.eig</code> to form principal components. I am able to do it but I think there's a more elegant way. The part that is making it tricky is that, according to the documentation, the eigenvalues resulting from <code>np.linalg.eig</code> are not necessarily ordered.</p>
<p>To find the first principal component (and second and so on) I am sorting the eigenvalues, then finding their original indexes, then using that to extract the right eigenvectors. I am intentionally reinventing the wheel a bit up to the point where I find the eigenvalues and eigenvectors, but not afterward. If there's any easier way to get from <code>e_vals, e_vecs = np.linalg.eig(cov_mat)</code> to the principal components I'm interested.</p>
<pre><code>import numpy as np
np.random.seed(0)
x = 10 * np.random.rand(100)
y = 0.75 * x + 2 * np.random.randn(100)
centered_x = x - np.mean(x)
centered_y = y - np.mean(y)
X = np.array(list(zip(centered_x, centered_y))).T
def covariance_matrix(X):
# I am aware of np.cov - intentionally reinventing
n = X.shape[1]
return (X @ X.T) / (n-1)
cov_mat = covariance_matrix(X)
e_vals, e_vecs = np.linalg.eig(cov_mat)
# The part below seems inelegant - looking for improvement
sorted_vals = sorted(e_vals, reverse=True)
index = [sorted_vals.index(v) for v in e_vals]
i = np.argsort(index)
sorted_vecs = e_vecs[:,i]
pc1 = sorted_vecs[:, 0]
pc2 = sorted_vecs[:, 1]
</code></pre>
| [] | [
{
"body": "<p>There is a nice trick to get the eigenvalues and eigenvectors of the covariance matrix <em>without</em> ever forming the matrix itself. This can be done using the <a href=\"https://en.wikipedia.org/wiki/Singular_value_decomposition\" rel=\"nofollow noreferrer\">singular value decomposition (SVD)</a>, as described in <a href=\"https://stats.stackexchange.com/questions/134282/relationship-between-svd-and-pca-how-to-use-svd-to-perform-pca/134283#134283\">this post from Stats.SE</a>. Not only is this more numerically stable, but the results are automatically sorted.</p>\n\n<p>A python version might look like this:</p>\n\n<pre><code>def components(X):\n _, vals, vecs = np.linalg.svd(X - X.mean(axis=0), full_matrices=False)\n return vals**2/(len(X)-1), vecs\n</code></pre>\n\n<p>A few things to note:</p>\n\n<ul>\n<li>As described in the linked post above, the <a href=\"https://en.wikipedia.org/wiki/Design_matrix\" rel=\"nofollow noreferrer\">data matrix</a> is typically defined with dimensions as columns, i.e. the transpose of your <code>X</code>.</li>\n<li>The principle values and components are typically sorted from largest to smallest, i.e. the reverse of yours.</li>\n<li>The function above does not assume that <code>X</code> has been pre-centered.</li>\n</ul>\n\n<p>So to get results comparable to yours, you would need to do:</p>\n\n<pre><code>vals, vecs = components(X.T)\ne_vals, e_vecs = vals[::-1], vecs[::-1]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T06:01:05.297",
"Id": "220700",
"ParentId": "215552",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T05:21:23.987",
"Id": "215552",
"Score": "7",
"Tags": [
"python",
"reinventing-the-wheel",
"numpy"
],
"Title": "Extract principal components"
} | 215552 |
<h3>Problem</h3>
<p>This project gets the past ~20 days of an equity data (such as $AAPL, $AMZN, $GOOG) plus the current equity "quote" (which comes every 60 seconds using a free API) and estimates seven "real-time" future price targets. It only uses one main class, <a href="https://github.com/emarcier/usco/blob/master/master/cron/equity/EQ.php" rel="nofollow noreferrer"><code>EQ</code></a> and slowly does this task using a CRON job.</p>
<p>Code in the <a href="https://github.com/emarcier/usco/blob/master/master/cron/equity/EQ.php" rel="nofollow noreferrer"><code>EQ</code> class</a> scrapes equities data using <a href="https://github.com/emarcier/usco/blob/master/master/cron/equity/EquityRecords.php" rel="nofollow noreferrer"><code>EquityRecords</code></a>, calculates sector (e.g., technology, healthcare) coefficients using <a href="https://github.com/emarcier/usco/blob/master/master/cron/equity/SectorMovers.php" rel="nofollow noreferrer"><code>SectorMovers</code></a>, estimates equity prices, and finally writes ~8,000 HTML strings (~100Kb-120Kb) for each equity on <code>.md</code> files for viewing. </p>
<h3>Performance</h3>
<p>The goal is making <a href="https://github.com/emarcier/usco/blob/master/master/cron/equity/EQ.php" rel="nofollow noreferrer"><code>EQ</code></a> as fast/efficient as possible for a single server. However, all comments/helps/advices are so welcomed. </p>
<p>This is my first scripting project and it has so many issues. I also couldn't add <a href="https://github.com/emarcier/usco/blob/master/master/cron/equity/EQ.php" rel="nofollow noreferrer"><code>EQ</code></a> in the post due to character limitations. Please see the entire code on this <a href="https://github.com/emarcier/usco" rel="nofollow noreferrer">GitHub link</a>.</p>
<hr>
<h3>EquityRecords</h3>
<pre><code>date_default_timezone_set("UTC");
ini_set('max_execution_time', 0);
ini_set('memory_limit', '-1');
set_time_limit(0);
// EquityRecords::allEquitiesSignleJSON(new EquityRecords());
class EquityRecords
{
const NUMBER_OF_STOCKS_PER_REQUEST = 100;
const NEW_LINE = "\n";
/**
*
* @var a string of iextrading symbols
*/
const SYMBOLS_PATH = '/../../config/z-iextrading-symbs.md';
/**
*
* @var a string of our symbols json directory
*/
const SYMBOLS_DIR = "/../../blog-back/equities/real-time-60sec/z-raw-equilibrium-estimation";
/**
*
* @var a string of target path and query
*/
const TARGET_QUERY = "stock/market/batch?symbols=";
/**
*
* @var a string of iextrading base URL
*/
const BASE_URL = "https://api.iextrading.com/1.0/";
/**
*
* @var a string of iextrading end point
*/
const END_POINT = "&types=quote,chart&range=1m&last=10";
/**
*
* @var an integer for maximum number of stocks per URL on each call
*/
//***************** A ********************** //
// public static function getSymbols() {
// return array_map(function($line){ return str_getcsv($line, "\t"); }, file(__DIR__ . self::SYMBOLS_PATH));
// }
public static function getSymbols()
{
//***************** START: ALL SYMBOLS ARRAY ********************** //
// var: is a filename path directory, where there is an md file with list of equities
$list_of_equities_file = __DIR__ . self::SYMBOLS_PATH;
// var: is content of md file with list of equities
$content_of_equities = file_get_contents($list_of_equities_file);
// var is an array(3) of equities such as: string(4) "ZYNE", string(10) "2019-01-04", string(27) "ZYNERBA PHARMACEUTICALS INC"
// $symbols_array=preg_split('/\r\n|\r|\n/', $content_of_equities);
$symbols_array = preg_split('/\R/', $content_of_equities);
//***************** END: ALL SYMBOLS ARRAY ********************** //
// child and mother arrays are created to help calling equities in batches of 100, which seems to be the API limit.
$child = array();
$mother = array();
// var: is 100 counter
$limit_counter = self::NUMBER_OF_STOCKS_PER_REQUEST;
foreach ($symbols_array as $ticker_arr) {
$limit_counter = $limit_counter - 1;
$symbols_array = preg_split('/\t/', $ticker_arr);
array_push($child, $symbols_array);
if ($limit_counter <= 0) {
$limit_counter = self::NUMBER_OF_STOCKS_PER_REQUEST;
array_push($mother, $child);
$child = array();
}
}
return $mother;
}
public static function allEquitiesSignleJSON()
{
$equity_arrays = EquityRecords::getSymbols();
$base_url = self::BASE_URL . self::TARGET_QUERY;
$current_time = date("Y-m-d-H-i-s");
$all_equities = array();
// ticker: AAPL, GE, AMD
foreach ($equity_arrays as $ticker_arr) {
$ticker = array_column($ticker_arr, 0);
$equity_url = $base_url . implode("%2C", $ticker) . self::END_POINT;
$raw_eauity_json = file_get_contents($equity_url);
$raw_equity_array = json_decode($raw_eauity_json, true);
$all_equities = array_merge($all_equities, $raw_equity_array);
}
$all_equities_json = json_encode($all_equities);
$symbols_dir = __DIR__ . self::SYMBOLS_DIR;
if (!is_dir($symbols_dir)) {mkdir($symbols_dir, 0755, true);}
$raw_equity_file = $symbols_dir . "/" . $current_time . ".json";
$fp = fopen($raw_equity_file, "x+");
fwrite($fp, $all_equities_json);
fclose($fp);
echo "YAAAY! Equity JSON file success at " . __METHOD__ . " ! " . self::NEW_LINE;
}
}
</code></pre>
<h3>SectorMovers</h3>
<pre><code>date_default_timezone_set("UTC");
ini_set('max_execution_time', 0);
ini_set('memory_limit', '-1');
set_time_limit(0);
require_once __DIR__ . "/EquityRecords.php";
SectorMovers::getSectors();
class SectorMovers
{
/**
*
* @var a string of iextrading base URL
*/
const BASE_URL = "https://api.iextrading.com/1.0/";
/**
*
* @var a string of target path and query
*/
const TARGET_QUERY = "stock/market/batch?symbols=";
/**
*
* @var a string for backend path for every sector
*/
const EACH_SECTOR_DIR_PREFIX = "/../../blog-back/sectors/real-time-60sec/z-raw-sector-";
/**
*
* @var a string for backend path for index sector
*/
const INDEX_SECTOR_DIR_PREFIX = "/../../blog-back/sectors/real-time-60sec/y-index/";
/**
*
* @var a string for live data path
*/
const LIVE_DATA_DIR = "/../../../public_html/blog/files/";
const DIR_FRONT_SECTOR_COEF_FILENAME = "s-1.txt"; // Filename that records sector coefficient JSON
public static function getSectors()
{
$base_url = self::BASE_URL . self::TARGET_QUERY;
$current_time = date("Y-m-d-H-i-s");
$permission = 0755;
$index_data = array("Overall" => array("sector_weight" => 1, "sector_coefficient" => 1, "sector_value" => 0));
$sector_movers = SectorMovers::iexSectorParams();
foreach ($sector_movers as $sector_mover) {
// $sector_url = $base_url . implode(",", array_keys($sector_mover["selected_tickers"])) . "&types=quote&range=1m";
$sector_url = $base_url . implode("%2C", array_keys($sector_mover["selected_tickers"])) . "&types=quote&range=1m";
$rawSectorJson = file_get_contents($sector_url);
$raw_sector_array = json_decode($rawSectorJson, true);
// ******************* Back Data ***************** //
// Write the raw file in the back directories
// $rawSectorDir = __DIR__ . self::EACH_SECTOR_DIR_PREFIX . $sector_mover["directory"];
// // if back directory not exist
// if (!is_dir($rawSectorDir)) {mkdir($rawSectorDir, $permission, true);}
// // create and open/write/close sector data to back directories
// $rawSectorFile = $rawSectorDir . "/" . $current_time . ".json";
// $fp = fopen($rawSectorFile, "a+");
// fwrite($fp, $rawSectorJson);
// fclose($fp);
// ******************* End Back Data ***************** //
// Calculate the real-time index
$index_value = 0;
foreach ($raw_sector_array as $ticker => $ticker_stats) {
if (isset($sector_mover["selected_tickers"][$ticker], $ticker_stats["quote"], $ticker_stats["quote"]["extendedChangePercent"], $ticker_stats["quote"]["changePercent"], $ticker_stats["quote"]["ytdChange"])) {
$change_amount = ($ticker_stats["quote"]["extendedChangePercent"] + $ticker_stats["quote"]["changePercent"] + $ticker_stats["quote"]["ytdChange"]) / 200;
$index_value += $sector_mover["sector_weight"] * $sector_mover["selected_tickers"][$ticker] * $change_amount;
}
}
$index_data[$sector_mover["sector"]] = array("sector_weight" => $sector_mover["sector_weight"], "sector_coefficient" => $sector_mover["sector_coefficient"], "sector_value" => $index_value);
$index_data["Overall"]["sector_value"] += $index_data[$sector_mover["sector"]]["sector_value"];
}
// Calculate the index factor for better visibility between -1 and +1
$front_index_data = array();
foreach ($index_data as $sector_name => $sector_index_data) {
// $index_sign = $sector_index_data["sector_value"];
// if ($index_sign < 0) {
// $index_sign = - $index_sign;
// }
$index_sign = abs($sector_index_data["sector_value"]);
$index_factor = 1;
for ($i = 0; $i <= 10; $i++) {
$index_factor = pow(10, $i);
if (($index_factor * $index_sign) > 1) {
$index_factor = pow(10, $i - 1);
break;
}
}
// $index_factor = 10 ** strlen(preg_match('~\.\K0+~', $float, $zeros) ? $zeros[0] : 0);
$front_index_data[$sector_name] = $sector_index_data["sector_weight"] * $sector_index_data["sector_coefficient"] * $sector_index_data["sector_value"] * $index_factor;
}
// Write the index file
$index_sector_dir = __DIR__ . self::INDEX_SECTOR_DIR_PREFIX;
if (!is_dir($index_sector_dir)) {mkdir($index_sector_dir, $permission, true);}
$index_sector_file = $index_sector_dir . $current_time . ".json";
$index_sector_json = json_encode($front_index_data, JSON_FORCE_OBJECT);
$fp = fopen($index_sector_file, "a+");
fwrite($fp, $index_sector_json);
fclose($fp);
$sector_dir = __DIR__ . self::LIVE_DATA_DIR;
if (!is_dir($sector_dir)) {mkdir($sector_dir, $permission, true);} // if data directory did not exist
// if s-1 file did not exist
if (!file_exists($sector_dir . self::DIR_FRONT_SECTOR_COEF_FILENAME)) {
$handle = fopen($sector_dir . self::DIR_FRONT_SECTOR_COEF_FILENAME, "wb");
fwrite($handle, "d");
fclose($handle);
}
$sector_coef_file = $sector_dir . self::DIR_FRONT_SECTOR_COEF_FILENAME;
copy($index_sector_file, $sector_coef_file);
echo "YAAAY! " . __METHOD__ . " updated sector coefficients successfully !\n";
return $front_index_data;
}
public static function iexSectorParams()
{
$sector_movers = array(
array(
"sector" => "IT",
"directory" => "information-technology",
"sector_weight" => 0.18,
"sector_coefficient" => 4,
"selected_tickers" => array(
"AAPL" => 0.18,
"AMZN" => 0.16,
"GOOGL" => 0.14,
"IBM" => 0.2,
"MSFT" => 0.1,
"FB" => 0.1,
"NFLX" => 0.08,
"ADBE" => 0.06,
"CRM" => 0.04,
"NVDA" => 0.02,
),
),
array(
"sector" => "Telecommunication",
"directory" => "telecommunication-services",
"sector_weight" => 0.12,
"sector_coefficient" => 4,
"selected_tickers" => array(
"VZ" => 0.18,
"CSCO" => 0.16,
"CMCSA" => 0.14,
"T" => 0.12,
"CTL" => 0.1,
"CHTR" => 0.1,
"S" => 0.08,
"DISH" => 0.06,
"USM" => 0.04,
"VOD" => 0.02,
),
),
array(
"sector" => "Finance",
"directory" => "financial-services",
"sector_weight" => 0.1,
"sector_coefficient" => 6,
"selected_tickers" => array(
"JPM" => 0.18,
"GS" => 0.16,
"V" => 0.14,
"BAC" => 0.12,
"AXP" => 0.1,
"WFC" => 0.1,
"USB" => 0.08,
"PNC" => 0.06,
"AMG" => 0.04,
"AIG" => 0.02,
),
),
array(
"sector" => "Energy",
"directory" => "energy",
"sector_weight" => 0.1,
"sector_coefficient" => 6,
"selected_tickers" => array(
"CVX" => 0.18,
"XOM" => 0.16,
"APA" => 0.14,
"COP" => 0.12,
"BHGE" => 0.1,
"VLO" => 0.1,
"APC" => 0.08,
"ANDV" => 0.06,
"OXY" => 0.04,
"HAL" => 0.02,
),
),
array(
"sector" => "Industrials",
"directory" => "industrials",
"sector_weight" => 0.08,
"sector_coefficient" => 8,
"selected_tickers" => array(
"CAT" => 0.18,
"FLR" => 0.16,
"GE" => 0.14,
"JEC" => 0.12,
"JCI" => 0.1,
"MAS" => 0.1,
"FLS" => 0.08,
"AAL" => 0.06,
"AME" => 0.04,
"CHRW" => 0.02,
),
),
array(
"sector" => "Materials and Chemicals",
"directory" => "materials-and-chemicals",
"sector_weight" => 0.08,
"sector_coefficient" => 8,
"selected_tickers" => array(
"DWDP" => 0.18,
"APD" => 0.16,
"EMN" => 0.14,
"ECL" => 0.12,
"FMC" => 0.1,
"LYB" => 0.1,
"MOS" => 0.08,
"NEM" => 0.06,
"PPG" => 0.04,
"MLM" => 0.02,
),
),
array(
"sector" => "Utilities",
"directory" => "utilities",
"sector_weight" => 0.08,
"sector_coefficient" => 8,
"selected_tickers" => array(
"PPL" => 0.18,
"PCG" => 0.16,
"SO" => 0.14,
"WEC" => 0.12,
"PEG" => 0.1,
"XEL" => 0.1,
"D" => 0.08,
"NGG" => 0.06,
"NEE" => 0.04,
"PNW" => 0.02,
),
),
array(
"sector" => "Consumer Discretionary",
"directory" => "consumer-discretionary",
"sector_weight" => 0.08,
"sector_coefficient" => 8,
"selected_tickers" => array(
"DIS" => 0.18,
"HD" => 0.16,
"BBY" => 0.14,
"CBS" => 0.12,
"CMG" => 0.1,
"MCD" => 0.1,
"GPS" => 0.08,
"HOG" => 0.06,
"AZO" => 0.04,
"EXPE" => 0.02,
),
),
array(
"sector" => "Consumer Staples",
"directory" => "consumer-staples",
"sector_weight" => 0.06,
"sector_coefficient" => 8,
"selected_tickers" => array(
"PEP" => 0.18,
"PM" => 0.16,
"PG" => 0.14,
"MNST" => 0.12,
"TSN" => 0.1,
"CPB" => 0.1,
"HRL" => 0.08,
"SJM" => 0.06,
"CAG" => 0.04,
"KHC" => 0.02,
),
),
array(
"sector" => "Defense",
"directory" => "defense-and-aerospace",
"sector_weight" => 0.04,
"sector_coefficient" => 10,
"selected_tickers" => array(
"BA" => 0.18,
"LMT" => 0.16,
"UTX" => 0.14,
"NOC" => 0.12,
"HON" => 0.1,
"RTN" => 0.1,
"TXT" => 0.08,
"LLL" => 0.06,
"COL" => 0.04,
"GD" => 0.02,
),
),
array(
"sector" => "Health",
"directory" => "health-care-and-pharmaceuticals",
"sector_weight" => 0.04,
"sector_coefficient" => 10,
"selected_tickers" => array(
"UNH" => 0.18,
"JNJ" => 0.16,
"PFE" => 0.14,
"UHS" => 0.12,
"AET" => 0.1,
"RMD" => 0.1,
"TMO" => 0.08,
"MRK" => 0.06,
"ABT" => 0.04,
"LLY" => 0.02,
),
),
array(
"sector" => "Real Estate",
"directory" => "real-estate",
"sector_weight" => 0.04,
"sector_coefficient" => 10,
"selected_tickers" => array(
"CCI" => 0.18,
"AMT" => 0.16,
"AVB" => 0.14,
"HCP" => 0.12,
"RCL" => 0.1,
"HST" => 0.1,
"NCLH" => 0.08,
"HLT" => 0.06,
"ARE" => 0.04,
"AIV" => 0.02,
),
),
);
return $sector_movers;
}
}
</code></pre>
<hr>
<h3>Acknowledgment</h3>
<p>I'd like to thank these <a href="https://github.com/emarcier/usco#acknowledgment" rel="nofollow noreferrer">users</a> for being so kind and helpful, which I could implement some of their advices in the code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T16:10:46.097",
"Id": "417832",
"Score": "1",
"body": "@Emma, Can you change the title to represent business requirement and not what you are doing. Ex: Creating Equity Dump?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T23:16:36.493",
"Id": "419004",
"Score": "1",
"body": "The first thing you need to do is to discover what the bottlenecks are. Have you tried to [profile your code](https://stackify.com/php-profilers)? Common bottlenecks are: Slow APIs, too many database calls or file access, inefficient loops, or simply bad code/algorithms. There's way too many code in your project for me to dive into, but I think you can probably find the bottlenecks yourself. Once located you need to find a way to eliminate them, if possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T08:00:02.527",
"Id": "419039",
"Score": "1",
"body": "So you're doing a slow calculation and updating lots of files every minute? And how often are those files read on average? If it's less than once per minute, you might have a good case for generating the data on demand instead."
}
] | [
{
"body": "<p>Overall the methods look a bit too long. In <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> Rafael Dohms talks about limiting the indentation level to one per method and keeping methods to ~15 lines or less. (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>).</p>\n\n<p>Either you didn't comprehend it, or you didn't want to heed the advice of the first section of <a href=\"https://codereview.stackexchange.com/a/214282/120114\">my answer to your first question</a>. You don't need to to have an instance of the <a href=\"https://github.com/emarcier/usco/blob/master/master/cron/equity/EQ.php\" rel=\"nofollow noreferrer\"><code>EQ</code> class</a> that holds values that come from the static methods. You could simply call the static methods wherever the properties of that instance are currently used. For example, in the static method <code>EQ::getEquilibriums()</code> the symbols are used like this:</p>\n\n<blockquote>\n<pre><code>foreach ($class_obj->symbols as $symb => $arr) {\n</code></pre>\n</blockquote>\n\n<p>Instead of utilizing <code>$class_obj->symbols</code> just utilize <code>EQ::getSymbols()</code>- this could be stored in a local variable if that needs to be used multiple times within a method/function. </p>\n\n<pre><code>foreach (self::getSymbols() as $symb => $arr) {\n</code></pre>\n\n<p>Notice that this example uses the keyword <code>self</code> instead of <code>EQ</code>. This is a shortcut that can be used when accessing methods and static properties on the same class - <a href=\"https://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php#example-202\" rel=\"nofollow noreferrer\">see this example in the documentation for the scope resolution operator</a>.</p>\n\n<p>The same is true for the other methods called by that method - e.g. <code>EQ::getCharts()</code>. <code>EQ::getOverallCoef()</code> can just call <code>EQ::getSectors()</code> to get the sectors. And those methods can store fetched data the first time in static variables instead of re-fetching data on subsequent calls.</p>\n\n<p>There shouldn't be a need to create that <code>new EQ()</code> object and pass it to the methods. So this line:</p>\n\n<blockquote>\n<pre><code>EQ::getEquilibriums(new EQ());\n</code></pre>\n</blockquote>\n\n<p>should be updated like this:</p>\n\n<pre><code>EQ::getEquilibriums();\n</code></pre>\n\n<p>If you need to check if any of those helper methods doesn't return anything (i.e. the following check at the end of the EQ constructor) </p>\n\n<blockquote>\n<pre><code>if ($this->symbols == null || $this->sector == null || $this->overall == null || $this->emojis == null) {\n</code></pre>\n</blockquote>\n\n<p>Check for each case in the respective getter method and consider throwing an exception if appropriate. </p>\n\n<hr>\n\n<p>The array returned by <code>SectorMovers::iexSectorParams()</code> could be declared as a constant and the method can be removed.</p>\n\n<hr>\n\n<p><strike>The following three lines in <code>EquityRecords::allEquitiesSignleJSON()</code>:</p>\n\n<blockquote>\n<pre><code>$fp = fopen($raw_equity_file, \"x+\");\nfwrite($fp, $all_equities_json);\nfclose($fp);\n</code></pre>\n</blockquote>\n\n<p>Should likely be replaceable with a call to <a href=\"https://www.php.net/manual/en/function.file-put-contents.php\" rel=\"nofollow noreferrer\"><code>file_put_contents()</code></a></strike></p>\n\n<p>You pointed me to the SO question with <a href=\"https://stackoverflow.com/a/6415972/1575353\">this accepted answer</a> which claims \"<em>the <code>fwrite()</code> is a smidgen faster.</em>\" and cites <a href=\"http://web.archive.org/web/20100109103851/http://balancedbraces.com/2008/06/12/fopen-fwrite-fclose-vs-file_put_contents/\" rel=\"nofollow noreferrer\">this article</a>. I would be curious if that is still the case in PHP 7. I will research this.</p>\n\n<hr>\n\n<p>You could also consider using <a href=\"https://php.net/explode\" rel=\"nofollow noreferrer\"><code>explode()</code></a> instead of <code>preg_split()</code> if it works - depending on the delimiter. Refer to answers to <a href=\"https://stackoverflow.com/q/27303235/1575353\">_In PHP, which is faster: preg_split or explode?_</a> for more information.</p>\n\n<blockquote>\n <p><strong>Tip</strong> If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like <a href=\"https://www.php.net/manual/en/function.explode.php\" rel=\"nofollow noreferrer\"><code>explode()</code></a> or <a href=\"https://www.php.net/manual/en/function.str-split.php\" rel=\"nofollow noreferrer\"><code>str_split()</code></a>.<sup><a href=\"https://www.php.net/manual/en/function.preg-split.php#refsect1-function.preg-split-notes\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<p><sup>1</sup><sub><a href=\"https://www.php.net/manual/en/function.preg-split.php#refsect1-function.preg-split-notes\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.preg-split.php#refsect1-function.preg-split-notes</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:13:21.457",
"Id": "216673",
"ParentId": "215553",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216673",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T05:50:18.083",
"Id": "215553",
"Score": "2",
"Tags": [
"performance",
"beginner",
"php",
"object-oriented",
"array"
],
"Title": "Equity data processing: Fast and/or efficient file writing using PHP"
} | 215553 |
<p>I have a list of strings. I need to list them in rows and columns. Each row should not have more than "cols" number of values. Each of the values in a given row should be "step" away from the previous value. The values should appear only once in the output. Here is what I have. Any better way to write this code?</p>
<pre><code>cols = 4
step = 10
vlist = ["Value" + str(i+1) for i in range(100)]
vlen = len(vlist)
start = 0
while start < vlen and start < step:
num = 0
for idx in range(start, vlen, step):
if num < cols:
print(vlist[idx], end=", ")
num += 1
print("\n")
start += 1
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T06:33:20.390",
"Id": "416990",
"Score": "0",
"body": "Welcome to Code Review! Is `Each [value] should be \"step\" away from the previous value` an \"external\" requirement? ((Block-) Quote the specification of the result to achieve.) Another interpretation is *In a monospace font, each value shall be output 10 places to the right of the preceding one*, the advantage being all values getting displayed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T09:38:48.970",
"Id": "417236",
"Score": "0",
"body": "I don't really understand the problem statement. Could you possibly provide a sample input and the expected output to show what's required? That would really help!"
}
] | [
{
"body": "<p>The code can be made more understandable by:</p>\n\n<ul>\n<li>introducing row and column indices</li>\n<li>replace the while loop with a for loop</li>\n<li>calculate the index for <code>vlist</code> from the values of the row/col indices</li>\n</ul>\n\n<p>This reduces the number of help variables needed and could result in something like this:</p>\n\n<pre><code>vlist = [\"Value\" + str(i+1) for i in range(100)]\n\ncols = 4\nrows = 10\nfor row_idx in range(rows):\n for col_idx in range(cols):\n\n idx = row_idx + rows * col_idx\n print(vlist[idx], end=\", \")\n\n print(\"\\n\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T20:24:24.730",
"Id": "417056",
"Score": "0",
"body": "Thanks Jan. I used this approach as well. But your code looks cleaner :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T07:05:32.827",
"Id": "215557",
"ParentId": "215556",
"Score": "1"
}
},
{
"body": "<p>Fancy iteration in Python is often made easier using the <code>itertools</code> module. For this case, <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice()</code></a> can help pick out the values for each row.</p>\n\n<pre><code>from itertools import islice\n\ncols = 4\nstep = 10\nvlist = [\"Value\" + str(i+1) for i in range(100)]\n\nfor row in range(step):\n print(', '.join(islice(vlist, row, cols * step, step)), end=\", \\n\\n\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T07:26:31.273",
"Id": "215558",
"ParentId": "215556",
"Score": "7"
}
},
{
"body": "<p>It can be solved by using the slice object.</p>\n\n<p><a href=\"https://docs.python.org/3/glossary.html#term-slice\" rel=\"nofollow noreferrer\">From Python documentation:</a></p>\n\n<blockquote>\n <p><strong>slice</strong> - An object usually containing a portion of a sequence. A slice is created using the subscript notation, [] with colons between numbers\n when several are given, such as in variable_name[1:3:5]. The bracket\n (subscript) notation uses slice objects internally.</p>\n</blockquote>\n\n<pre><code>cols = 4 \nstep = 10\nvlist = [\"Value\" + str(i+1) for i in range(100)]\n\nend = step * cols\nfor start in range(step):\n print(', '.join(vlist[start:end:step]))\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code>Value1, Value11, Value21, Value31\nValue2, Value12, Value22, Value32\nValue3, Value13, Value23, Value33\nValue4, Value14, Value24, Value34\nValue5, Value15, Value25, Value35\nValue6, Value16, Value26, Value36\nValue7, Value17, Value27, Value37\nValue8, Value18, Value28, Value38\nValue9, Value19, Value29, Value39\nValue10, Value20, Value30, Value40\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T14:51:38.413",
"Id": "417120",
"Score": "0",
"body": "Thank you @MinMax. 200_success also gave the same answer earlier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T14:56:16.800",
"Id": "417121",
"Score": "0",
"body": "@RebornCodeLover It is different. @200_success uses the `islice` from `itertools`. I use built-in slice. But yes, they are similar in other ways."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T14:56:54.027",
"Id": "417123",
"Score": "0",
"body": "True. Yes I like it. Thanks"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T14:47:57.027",
"Id": "215612",
"ParentId": "215556",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T06:08:09.207",
"Id": "215556",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"formatting"
],
"Title": "Displaying elements of a list, in columns"
} | 215556 |
<p>I wanted to load every page under index.php with a simple <code>index.php?do=login</code></p>
<p>For example when the link <code>index.php?do=login</code> or <code>/login/</code> is opened, the file <code>login.php</code> is loaded (from outside <code>public_html</code>), and so everything is done under index.php instead of having a separate php file in <code>public_html</code> for each action!</p>
<p>This is what I've tried already, am I doing it okay? (I'm not sure if what I'm doing has any security vulnerabilities, so please kindly advise)</p>
<p><strong>index.php</strong></p>
<pre><code><?php
// application path (outside public_html)
define('FILESPATH', APP.'../application/actions/');
// Default file
$file_name = 'home_page';
// e.g. index.php?do=login or /login/
if(isset($_GET['do'])){
$file_name = rtrim($_GET['do'],'/');
}
// Set file path
$fpath = FILESPATH."{$file_name}.php";
// Make sure user input has valid characters a-z 0-9 _
if(preg_match('/^[A-Za-z0-9_]+$/', $file_name) !== 1 OR ! file_exists($fpath)){
// Error
require_once('404.php');
die();
}
// Load the do=file
require_once($fpath);
// Nothing more comes in index.php
</code></pre>
<p><strong>login.php</strong></p>
<pre><code><?php
// Load template file header
require_once('header_template.php');
//
// Stuff that happens in login.php
// Checking if $_POST['username'] has valid chars then searching for it with pdo in db,
// password_verify() for $_POST['password'], etc...
//
// Load login's html template
// (which includes the html form submitted to /login/)
require_once('login_template.php');
// Load template footer
require_once('footer_template.php');
</code></pre>
<p><strong>.htaccess</strong></p>
<p>To run with <code>site.com/login/</code> etc instead of <code>site.com?do=login</code></p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^((?s).*)$ index.php?do=$1 [QSA,L]
</IfModule>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:16:30.213",
"Id": "418482",
"Score": "1",
"body": "Using GET for this is completely the wrong approach, your basically nuking your ability to properly use GET for what it's intended. Instead use the URI part of the URL. For example see this simple [MVC router](https://github.com/ArtisticPhoenix/MISC/tree/master/Router) I made using URI instead of GET (as most major MVC framworks do) - the added benefit is you never have to touch HTACCESS except to remove `index.php`. To be clear the URI is the imaginary part of the URL `www.example.com/index.php/controller/method/args` so everything after `index.php`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:30:23.410",
"Id": "418486",
"Score": "0",
"body": "@ArtisticPhoenix This comment was exactly what I was looking for :) I had a feeling that I'm doing something wrong, could you kindly post it as an answer please"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:31:14.497",
"Id": "418488",
"Score": "1",
"body": "I'll post an answer explaining it in a few minutes."
}
] | [
{
"body": "<p>You can simplify your regex pattern and you might like to combine your validation with the preparation step. The following pattern is just like yours except it allows a single trailing slash and omits it from the capture group.</p>\n\n<pre><code>if (isset($_GET['do']) && preg_match('~^(\\w+)/?$~', $_GET['do'], $valid)) {\n $file_name = $valid[1];\n} else {\n $file_name = \"home_page\";\n}\n\n$fpath = FILESPATH . \"{$file_name}.php\";\n\nif (!file_exists($fpath)) {\n // Error\n require_once('404.php');\n die();\n}\n</code></pre>\n\n<p>It doesn't make sense to valid <code>home_page</code> with your pattern, you know it will pass every time. I suppose it could be possible that your <code>home_page</code> file may not exist in the directory.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T06:09:19.870",
"Id": "215648",
"ParentId": "215566",
"Score": "2"
}
},
{
"body": "<p><strong>Preface</strong></p>\n\n<p>I wouldn't use the query string of the URL at all. </p>\n\n<p>The problem with using GET, is that GET is meant for other things such as bookmarkable search link etc. As you add more <code>do</code> stuff in your logic will become more and more complex. Harder and harder to keep track of what ever <code>do</code> does etc. There is no clear structure to it, no way to tell <code>foo.php</code> is a controller and <code>bar.php</code> is some other piece of code (like a DB class etc).</p>\n\n<p>A better method is to use a MVC style router that does not affect the GET query string at all.</p>\n\n<p>Another issue in your code is this:</p>\n\n<pre><code> if(preg_match('/^[A-Za-z0-9_]+$/', $file_name) !== 1 OR ! file_exists($fpath)){\n</code></pre>\n\n<p>Which is ... muah ... ok. But it's the only thing preventing directory transversal attacks.</p>\n\n<p>One more point is that while this may seem like the simplest method</p>\n\n<pre><code>if(isset($_GET['do'])){\n $file_name = rtrim($_GET['do'],'/');\n}\n</code></pre>\n\n<p>You really have no control over what is being loaded. No way to know if that PHP file really should be used as a controller.</p>\n\n<p>We can fix all these issues by using the URI part of the URL. For example take this URL</p>\n\n<pre><code> www.example.com/index.php/user/login\n</code></pre>\n\n<p>The URI is the part after the <code>index.php</code>. We can very easly remove the <code>index.php</code> file (same as wordpress, or many MVC frameworks do).</p>\n\n<p><strong>So how do we do this:</strong></p>\n\n<p>Below I will post the full code for My Simple Router you can find <a href=\"https://github.com/ArtisticPhoenix/MISC/tree/master/Router\" rel=\"nofollow noreferrer\">here</a>. This is a minimal example and not really meant for production use.</p>\n\n<p>.htaccess (very similar or identical to what you'll find in wordpress etc.)</p>\n\n<pre><code><IfModule mod_rewrite.c>\n RewriteEngine On\n\n # For sub-foder installs set your RewriteBase including trailing and leading slashes\n # your rewrite base will vary, possibly even being / if no sub-foder are involved\n RewriteBase /MISC/Router/\n\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule ^(.*)$ index.php/$1 [L]\n</IfModule>\n</code></pre>\n\n<p>index.php</p>\n\n<pre><code><?php\nrequire_once __DIR__.'/SimpleRouter.php';\nSimpleRouter::route();\n</code></pre>\n\n<p>SimpleRouter.php</p>\n\n<pre><code><?php\n/**\n * A simple 1 level router\n * \n * URL schema is http://example.com/{controller}/{method}/{args ... }\n * \n * @author ArtisticPhoenix\n * @package SimpleRouter\n */\nclass SimpleRouter{\n\n /**\n * should be the same as rewrite base in .htaccess\n * @var string\n */\n const REWRITE_BASE = '/MISC/Router/';\n\n /**\n * path to controller files\n * \n * @var string\n */\n const CONTOLLER_PATH = __DIR__.'/Controllers/';\n\n /**\n * route a url to a controller\n */\n public static function route(){\n //normalize\n if(self::REWRITE_BASE != '/'){\n $uri = preg_replace('~^'.self::REWRITE_BASE.'~i', '',$_SERVER['REQUEST_URI']);\n }\n\n $uri = preg_replace('~^index\\.php~i', '',$uri); \n $uri = trim($uri,'/');\n\n //empty url, like www.example.com\n if(empty($uri)) $uri = 'home/index';\n\n //empty method like www.example.com/home\n if(!substr_count($uri, '/')) $uri .= '/index';\n\n $arrPath = explode('/', $uri);\n\n $contollerName = array_shift($arrPath);\n $methodName = array_shift($arrPath);;\n $contollerFile = self::CONTOLLER_PATH.$contollerName.'.php';\n\n //require_once $contollerFile; //> when not autoloading, explode takes care of / in REQUEST_URI\n\n if(!file_exists($contollerFile)||!class_exists($contollerName)){\n self::error404($uri);\n return;\n }\n\n $Controller = new $contollerName();\n\n if(!method_exists($Controller, $methodName)){\n self::error404($uri);\n return;\n }\n\n if(!count($arrPath)){\n call_user_func([$Controller, $methodName]);\n }else{\n call_user_func_array([$Controller, $methodName], $arrPath);\n } \n }\n\n /**\n * call error 404\n * \n * @param string $uri\n */\n protected static function error404($uri){\n require_once self::CONTOLLER_PATH.'home.php'; \n $Controller = new home();\n $Controller->error404($uri);\n }\n}\n</code></pre>\n\n<p>Contollers/home.php</p>\n\n<pre><code><?php\n/**\n * \n * The default controller\n * \n * @author ArtisticPhoenix\n * @package SimpleRouter\n */\nclass home{\n\n public function index($arg=false){\n echo \"<h3>\".__METHOD__.\"</h3>\";\n echo \"<pre>\";\n print_r(func_get_args());\n }\n\n public function otherpage($arg){\n echo \"<h3>\".__METHOD__.\"</h3>\";\n echo \"<pre>\";\n print_r(func_get_args());\n }\n\n public function error404($uri){\n header('HTTP/1.0 404 Not Found');\n echo \"<h3>Error 404 page {$uri} not found</h3>\";\n }\n\n}\n</code></pre>\n\n<p><strong>How it works</strong></p>\n\n<p>This is a decent amount of code, so the first thing is you'll probably want to change the <code>RewriteBase</code> to just <code>/</code> in both Htaccess and the Router class. On my Dev server it's located in <code>www/MISC/Router/</code> and so I have to use those so that it routes properly. Otherwise I would have to setup a vHost and I am way to lazy for that.</p>\n\n<p>This may seem way more complex then using GET etc. etc. But it's really quite simple, the main part is right here:</p>\n\n<pre><code> $_SERVER['REQUEST_URI']\n</code></pre>\n\n<p>Which may contain <code>index.php</code> depending on the URL. So using my above example:</p>\n\n<pre><code> www.example.com/index.php/user/login //REQUEST_URI = index.php/user/login\n</code></pre>\n\n<p>So in this case we remove <code>index.php</code> </p>\n\n<pre><code> $uri = preg_replace('~^index\\.php~i', '',$uri); \n</code></pre>\n\n<p>Then after some more checks and what not we split this <code>user/login</code> into <code>['user','login']</code>. Which if we go by the pattern at the top of the Router class.</p>\n\n<pre><code> http://example.com/{controller}/{method}/{args ... }\n</code></pre>\n\n<p>This tells us that <code>user</code> is the \"Controller\" and the method is <code>\"login\"</code>. So we look for that controller file:</p>\n\n<pre><code> if(!file_exists($contollerFile)||!class_exists($contollerName)){\n</code></pre>\n\n<p>If your not using an autoloader you can split this, and require the file between:</p>\n\n<pre><code> if(!file_exists($contollerFile)) self::error404($uri);\n\n require_once $contollerFile;\n\n if(!class_exists($contollerName)) self::error404($uri);\n</code></pre>\n\n<p>When using an autoloader the <code>class_exists</code> method will trigger autoloading of the Controller class.</p>\n\n<p>In anycase there is little chance a URL like </p>\n\n<pre><code> http://example.com/../../foobar.php\n</code></pre>\n\n<p>Will work because the controller would be <code>..</code> with a method of <code>..</code> and an argument of <code>foobar.php</code>.</p>\n\n<p>In anycase in the above example we don't have a <code>user</code> controller, so lets add one now.</p>\n\n<p>Contollers/user.php</p>\n\n<pre><code>class user{\n\n public function index(){\n echo \"<h3>\".__METHOD__.\"</h3>\";\n }\n\n\n public function login(){\n echo \"<h3>\".__METHOD__.\"</h3>\";\n }\n\n}\n</code></pre>\n\n<p>So this <code>www.example.com/index.php/user/login</code> would basically go to the login method of this <code>user</code> controller class. If you just did <code>www.example.com/index.php/user</code> this would go to the <code>index</code> method above. And if you just did <code>www.example.com/index.php/</code> it goes to <code>home::index</code>.</p>\n\n<p>As you can see now we can really organize our code, instead of multiple files we can have multiple methods <code>user::login</code>, <code>user::logout</code>, <code>user::profile</code>, etc... Which keeps things neat and simple.</p>\n\n<p>Any extra path parts such as <code>www.example.com/index.php/user/login/foo</code> would pass <code>foo</code> as the first argument to <code>user::login('foo')</code> and so on for any additional arguments. So instead of losing <code>$_GET</code> we gain the ability to send extra information along with the URL itself, all the wile leaving <code>$_GET</code> to do what it was intended for.</p>\n\n<p>With the rewriting we can actually set all our links up without the <code>index.php</code> so you would just omit that when creating navigation links etc.., and the rewrite rule will take care of it. The really big advantage is once it's setup you can just add new controllers or methods in and that is the extent of the changes you need to make for it to work.</p>\n\n<p><strong>Summery</strong></p>\n\n<p>This solves a lot of the above mentioned problems, because you have total control over what is a Controller and what is not. There is 100% no chance for directory transversal (if autoloading) because the path is never used, auto loading uses the Class Name/Namespace, not the file name. Even without autoloading, by it's very nature it will split the paths on the directory separator. So the protection is inherent, instead of added as an after thought.</p>\n\n<p>The only real issue this type of router has it that you are tied to a naming convention for your URL and Controllers, but you have that anyway. A way around that is the next step up which is an \"event\" based router, where you would subscribe to the request event. This would let you run any function or callable as the endpoint of any URL, and break this dependence on the file system.</p>\n\n<p>You can obviously go much deeper then this, such as having sub-folders in the Controller folder etc.</p>\n\n<p>But this is just a simple example, I hope that helps explain the basics.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:12:54.657",
"Id": "418494",
"Score": "0",
"body": "Would not be better to just use a Alias?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:17:27.873",
"Id": "418495",
"Score": "0",
"body": "`Would not be better to just use a Alias` - I don't know what you mean, but this is just a simple example that doesn't transform the Class name or methods etc. It was about the smallest I could make this with still having good fallback protection for variation in the URL>"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:19:39.413",
"Id": "418497",
"Score": "0",
"body": "The problem is as soon as you do this in mod rewrite `RewriteRule ^((?s).*)$ index.php?do=$1 [QSA,L]` - your forever changing the GET part of the request. This makes it difficult to use it for what it's intended such as search arguments etc... Essentially your taking the responsibility of the URL (routing to resources) and infecting the Query string with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:37:49.470",
"Id": "418501",
"Score": "0",
"body": "https://serverfault.com/a/362041 He could point the folder: `/user/` to `application/actions/`. So this is another way to load files outsite public_html, and this don't really needs a GET request. he could use this url: `https://example.com/user/login.php`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:40:54.710",
"Id": "418503",
"Score": "0",
"body": "You could just as easily put the Controller path somewhere else and then just change `CONTOLLER_PATH` - to be outside of the webroot, no? Then you don't need any alias or any modification to HTACCESS. The point is usually to remove the `.php` as well as `index.php` So I am not sure what that means. In fact in my Code Igniter site (which is a big one > 150mil searches for clients per day) the whole framework is outside of the webroot with only index.php exposed. This is no different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:48:11.210",
"Id": "418504",
"Score": "0",
"body": "PS if you need an autoloader, I have one of those too. https://github.com/ArtisticPhoenix/Autoloader"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:51:33.830",
"Id": "418505",
"Score": "0",
"body": "@ArtisticPhoenix Thank you very much for the awesome answer, you taught me a lot today"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:56:57.423",
"Id": "418507",
"Score": "1",
"body": "Sure, glad I could help expand your understanding."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:56:09.630",
"Id": "216293",
"ParentId": "215566",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216293",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T12:54:14.260",
"Id": "215566",
"Score": "4",
"Tags": [
"php",
"url-routing",
".htaccess"
],
"Title": "Load other files (from outside public_html) under index.php"
} | 215566 |
<p>I have a problem similar to <a href="https://stackoverflow.com/questions/4174372/haskell-date-parsing-and-formatting">the question</a>, namely reading in text which describes a date - in various formats. I want to use the <code>parseTimeM</code> function from <code>Date.Time</code> module in <code>time</code> package. </p>
<p>My current solution can probably be improved style wise but it should remain easy to read and easy to extend. Suggestion?</p>
<pre><code>readDate3 :: Text -> UTCTime
readDate3 datestring =
case shortMonth of
Just t -> t
Nothing -> case longMonth of
Just t2 -> t2
Nothing -> case monthPoint of
Just t3 -> t3
Nothing -> case germanNumeralShort of
Just t3 -> t3
Nothing -> case germanNumeral of
Just t3 -> t3
Nothing -> case isoformat of
Just t4 -> t4
Nothing -> errorT ["readDate3", datestring, "is not parsed"]
where
shortMonth = parseTimeM True defaultTimeLocale
"%b %-d, %Y" (t2s datestring) :: Maybe UTCTime
longMonth = parseTimeM True defaultTimeLocale
"%B %-d, %Y" (t2s datestring) :: Maybe UTCTime
monthPoint = parseTimeM True defaultTimeLocale
"%b. %-d, %Y" (t2s datestring) :: Maybe UTCTime
germanNumeral = parseTimeM True defaultTimeLocale
"%-d.%-m.%Y" (t2s datestring) :: Maybe UTCTime
germanNumeralShort = parseTimeM True defaultTimeLocale
"%-d.%-m.%y" (t2s datestring) :: Maybe UTCTime
isoformat = parseTimeM True defaultTimeLocale
"%Y-%m-%d" (t2s datestring) :: Maybe UTCTime
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T11:48:12.660",
"Id": "417027",
"Score": "0",
"body": "I think you can use the `>>=` combinator instead of this huge `case` expression."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T11:53:55.520",
"Id": "417028",
"Score": "0",
"body": "I tried but did not succeed (I nearly never use the `>>=` constructors. Can you show me the start of the chain?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T11:59:47.180",
"Id": "417029",
"Score": "1",
"body": "@ForceBru That's not applicable in this case - `>>=` continues the computation on `Just`, whereas here we need to continue it on `Nothing`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:10:09.593",
"Id": "417030",
"Score": "0",
"body": "@user855443 Small detail: `>>=` is a function, not a constructor. I know that's nitpicking a bit, but these details can start to matter in more advanced stuff (e.g. you can pattern-match on constructors but not on functions)."
}
] | [
{
"body": "<p>Define an auxilliary function:</p>\n\n<pre><code>replaceIfNothing :: Maybe a -> a -> a\nreplaceIfNothing (Just x) _ = x\nreplaceIfNothing Nothing x = x\n</code></pre>\n\n<p>And then you can do:</p>\n\n<pre><code>replaceIfNothing shortMonth $\nreplaceIfNothing longMonth $\nreplaceIfNothing monthPoint $\n-- I think you get the idea now\n</code></pre>\n\n<p>You can also do it as an operator, which I personally think is nicer:</p>\n\n<pre><code>(&>) :: Maybe a -> a -> a\n(&>) (Just x) _ = x\n(&>) Nothing x = x\ninfixr 1 &>\n\nshortMonth &> longMonth &> monthPoint &> ...\n</code></pre>\n\n<p>Of course, since this is Haskell, a <a href=\"https://hoogle.haskell.org/?hoogle=a%20-%3E%20Maybe%20a%20-%3E%20a\" rel=\"nofollow noreferrer\">quick search</a> shows that this is just <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Maybe.html#v:fromMaybe\" rel=\"nofollow noreferrer\"><code>Data.Maybe.fromMaybe</code></a> with the arguments reversed; you can thus just define <code>replaceIfNothing = flip fromMaybe</code> (although you have to do <code>import Data.Maybe</code> first). It's possible to use <code>fromMaybe</code> directly as well, although it feels a little clumsy:</p>\n\n<pre><code>flip fromMaybe shortMonth $\nflip fromMaybe longMonth $\nflip fromMaybe monthPoint $\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T12:37:29.483",
"Id": "417032",
"Score": "2",
"body": "Why not just `shortMonth <|> longMonth <|> monthPoint <|> ...` (using `<|>` from [Control.Applicative](https://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Applicative.html#g:2))?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T12:39:12.920",
"Id": "417033",
"Score": "0",
"body": "@melpomene Yes, that's even better! I completely forgot about `(<|>)`! I'll edit that in now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T12:42:14.073",
"Id": "417034",
"Score": "0",
"body": "@melpomene After a bit more thought, it actually turns out that `(<|>)` is not exactly the same as what I've defined: I defined `(&>) :: Maybe a -> a -> a`, whereas `(<|>) :: Maybe a -> Maybe a -> Maybe a`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:03:47.627",
"Id": "417035",
"Score": "1",
"body": "`<|>` can still be used, you would just unwrap the end result with `fromMaybe` (for the error case)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:08:51.243",
"Id": "417036",
"Score": "0",
"body": "@4castle That is definitely one way to go about it. I do think that approach is slightly more boilerplate-ey than necessary though; compare `a &> b &> c` to `fromJust $ a <|> b <|> Just c`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:19:16.637",
"Id": "417037",
"Score": "0",
"body": "It would be `fromMaybe (error ...) $ a <|> b <|> c`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T21:46:09.907",
"Id": "417065",
"Score": "0",
"body": "@melpomene Yes, you are right actually - for some reason I thought `c` wasn't in `Maybe`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T12:08:24.900",
"Id": "215572",
"ParentId": "215571",
"Score": "2"
}
},
{
"body": "<h1>Don't repeat yourself</h1>\n\n<p>Your code violates the DRY principle. If we replace</p>\n\n<pre><code>germanNumeralShort = parseTimeM True defaultTimeLocale\n \"%-d.%-m.%y\" (t2s datestring) :: Maybe UTCTime\nisoformat = parseTimeM True defaultTimeLocale\n \"%Y-%m-%d\" (t2s datestring) :: Maybe UTCTime\n...\n</code></pre>\n\n<p>with</p>\n\n<pre><code>parse format = parseTimeM True defaultTimeLocale format (t2s datestring)\n\ngermanNumeralShort = parse \"%-d.%-m.%y\"\nisoformat = parse \"%Y-%m-%d\"\n...\n</code></pre>\n\n<p>then we immediately notice that we use <code>parse</code> on all formats after another till we find a suitable one.</p>\n\n<p>This can be modelled with <code>map parse</code>, e.g.</p>\n\n<pre><code>map parse\n [ \"%b %-d, %Y\"\n , \"%B %-d, %Y\"\n , \"%b. %-d, %Y\"\n , \"%-d.%-m.%Y\"\n , \"%-d.%-m.%y\"\n , \"%Y-%m-%d\"\n ]\n</code></pre>\n\n<p>We could use <code><|></code> alternatively, e.g.</p>\n\n<pre><code>parse \"%b %-d, %Y\" <|> parse \"%B %-d, %Y\" <|> ...\n</code></pre>\n\n<p>but that's less flexible than the list approach.</p>\n\n<h1>Use <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Foldable.html#v:asum\" rel=\"nofollow noreferrer\"><code>asum</code></a> to get a single <code>Maybe</code> from a list of <code>Maybe</code>s</h1>\n\n<p>To get a single <code>Maybe a</code> from <code>[Maybe a]</code>, we can use <code>asum</code>. To get the <code>errorT</code>, we just need to pattern match on a single result and end up with</p>\n\n<pre><code>readDate3 :: Text -> UTCTime\nreadDate3 datestring = case result of\n Nohing -> errorT [\"readDate3\", datestring, \"is not parsed\"]\n Just t -> t\n where \n parse format = parseTimeM True defaultTimeLocale format (t2s datestring) \n result = asum . map parse $\n [ \"%b %-d, %Y\"\n , \"%B %-d, %Y\"\n , \"%b. %-d, %Y\"\n , \"%-d.%-m.%Y\"\n , \"%-d.%-m.%y\"\n , \"%Y-%m-%d\"\n ]\n</code></pre>\n\n<p>As the current strings are missing some documentation, we could introduce additional types to remedy that:</p>\n\n<pre><code>data DateFormat = ShortMonth\n | LongMonth\n | MonthPoint\n | GermanNumeral\n | GermanNumeralShort\n | ISOFormat\n\ntoFormatString :: DateFormat -> String\ntoFormatString f = case f of\n ShortMonth -> \"%b %-d, %Y\"\n LongMonth -> \"%B %-d, %Y\"\n MonthPoint -> \"%b. %-d, %Y\"\n -- other left as an exercise\n</code></pre>\n\n<p>We can also use <code>fromMaybe</code> to get rid of the last pattern match and end up with</p>\n\n<pre><code>import Data.Foldable (asum)\nimport Data.Maybe (fromMaybe)\n\nreadDate :: Text -> UTCTime\nreadDate datestring = \n fromMaybe (errorT [\"readDate\", datestring, \"is not parsed\"]) $\n asum . map parse $\n [ ShortMonth\n , LongMonth\n , MonthPoint\n , GermanNumeral\n , GermanNumeralShort\n , ISOFormat\n ]\n where \n parse format = parseTimeM True defaultTimeLocale (toFormatString format) (t2s datestring) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:32:20.547",
"Id": "417031",
"Score": "0",
"body": "@4castle thanks for the edit. I don't have a programming environment or editor at the moment at hand (not even a spell checker)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:22:41.380",
"Id": "417038",
"Score": "0",
"body": "@melpomene added that; it has been a while since I answered Haskell questions and used the language, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:18:14.143",
"Id": "417039",
"Score": "0",
"body": "The final pattern match can be replaced by `fromMaybe`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T13:13:52.840",
"Id": "215573",
"ParentId": "215571",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T11:30:10.800",
"Id": "215571",
"Score": "3",
"Tags": [
"parsing",
"datetime",
"haskell"
],
"Title": "Parse a date in various formats"
} | 215571 |
<h1>BrainFreeze</h1>
<p>This is my implementation of a brainfuck compiler in C. The instruction to build/run the project (GitHub repo) can be found <a href="https://github.com/GnikDroy/brainfreeze/tree/59b6e08d5cb883f8e52af312fc2eb49bb6d80278" rel="noreferrer">here</a>.</p>
<p>I am first <strong>converting the brainfuck source to x86 assembly</strong> and then using <code>ld</code> and <code>as</code> to generate the executable file (currently generates a 32 bit executable for linux only). I was planning on having no dependencies, but the ELF format was too intimidating to learn at first, therefore; I am using <code>as</code> (the GNU assembler) and <code>ld</code> (the GNU linker) for now.</p>
<p>The size of the brain fuck array is currently set to 30,000 and is allocated on the heap and one byte is allocated to each cell. Negative cell index should be UB right now.</p>
<p>I have <strong>zero experience</strong> with making compilers and am pretty sure this is not the way to make a compiler. I haven't even implemented lexers/parsers. Also, I thought it would be easier to implement it in a switch case since the language is so simple.</p>
<p>That being said, I think I have done a good job with this compiler. The compiled program runs x2 as fast as <a href="https://codereview.stackexchange.com/questions/147806/brainfuck-to-x86-assembly-compiler">this</a> when I used it for mandelbrot generation.</p>
<p>There is some information about the functions in the header files. Hope that improves readability and understanding.</p>
<p>I would appreciate any improvements/suggestions.</p>
<ul>
<li><strong>style/convention/performance/memory and everything else</strong>.</li>
</ul>
<p>I am not currently concerned with optimizing the compiler. I have got a few ideas. But if I missed some pretty obvious ones (very easy to implement), I would love if you could mention them.</p>
<h2>bf_asm.h</h2>
<pre><code>#pragma once
/*
Some general techniques used.
1) edi always contains the address in memory of the current cell
2) edx is always 1 (for read and write syscalls).
*/
/** The assembly instructions for allocating 30,000 bytes of memory.
Uses the brk() system call without any library wrappers.
NOTE: brk() zeros out memory during first call. No need to initialize to 0.*/
const char ALLOCATE_MEMORY[] = ".intel_syntax noprefix\n"
".global _start\n"
"_start:\n"
"mov eax,0x2d\n"
"xor ebx,ebx\n"
"int 0x80\n"
"add eax,30000\n"
"mov ebx,eax\n"
"mov eax,0x2d\n"
"int 0x80\n"
"mov edi,eax\n"
"sub edi,30000\n"
//Sets edx=1 for future read and write calls. This is never modified.
"xor edx,edx\n"
"inc edx\n";
/** The assembly instructions for increasing the current cell pointer. */
const char INCREMENT_POINTER[] = "add edi,0x%02x\n";
/** The assembly instructions for decreasing the current cell pointer. */
const char DECREMENT_POINTER[] = "sub edi,0x%02x\n";
/** The assembly instruction to increase the value at current cell */
const char INCREMENT[] = "add byte ptr [edi],0x%02x\n";
/** The assembly instruction to decrease the value at current cell */
const char DECREMENT[] = "sub byte ptr [edi],0x%02x\n";
/** The assembly instructions for starting a loop in bf. LABEL references are not present and are calculated at compile time. */
const char LOOP_START[] =
//"_LABEL_XXXX:\n"
"cmp byte ptr [edi],0x00\n"
//"je _LABEL_XXXX\n";
"je ";
/** The assembly instructions for ending a loop in bf. LABEL references are not present and are calculated at compile time. */
const char LOOP_END[] =
//"_LABELXXXX:\n"
"cmp byte ptr [edi],0x00\n"
//"jne _LABEL_XXXX\n";
"jne ";
/** The assembly instructions for the write syscall. Executes the raw syscall. The value is printed to stdout. */
const char WRITE_CHAR[] = "mov eax,0x04\n"
"xor ebx,ebx\n"
"inc ebx\n"
"mov ecx,edi\n"
"int 0x80\n";
/** The assembly instructions for the read syscall. Executes the raw syscall. The value is stored in the current cell. */
const char READ_CHAR[] = "mov eax,0x03\n"
"xor ebx,ebx\n"
"mov ecx,edi\n"
"int 0x80\n";
/** The assembly instructions for the exit syscall. Executes the raw syscall.*/
const char SYS_EXIT_CALL[] = "mov eax,0x01\n"
"xor ebx,ebx\n"
"int 0x80\n";
</code></pre>
<h2>compiler.h</h2>
<pre><code>#pragma once
#include <stdio.h>
/** The structure which represents the parsed global args.*/
struct global_args_t
{
/** The path to the source brainfuck code.*/
char *input_file;
/** The path to the output executable file.*/
char *output_file;
} global_args; ///< The variable which is populated by the parse_args() function.
/**
* @brief Print the help text
*/
void print_help();
/**
* @brief Parse the args provided from the command line
*
* The global_args struct is populated from this function.
*
* @param argc Number of arguments.
* @param argv The list of arguments.
*/
void parse_args(int argc, char **argv);
/**
* @brief Verifies if the brainfuck source file is valid
*
* The file seek is set to 0 after the verfication of the source is complete.
*
* @param input_fp The brainfuck input source file.
*/
void verify_syntax(FILE *input_fp);
/**
* @brief Creates the .s assembly source file that contains the list of assembly instructions for the brainfuck program.
*
* Calls assemble() after checking if the output file could be created.
*
* @param input_fp The brainfuck input source file.
* @param output_file The .s assembly file.
*/
void create_assembly_source(FILE *input_fp, const char *output_file);
/**
* @brief Creates the .s assembly source file that contains the list of assembly instructions for the brainfuck program.
*
* Writes the assembly instructions by parsing the source and refering to the bf_asm.h constants.
*
* @param input_fp The brainfuck input source file.
* @param output_fp The .s assembly file.
*/
void assemble(FILE *input_fp, FILE *output_fp);
/**
* @brief Creates the .o elf file from the .s assembly file.
*
* Calls the GNU assembler 'as'.
*
* @param input_file The file path to the .s assembly file.
*/
void execute_assembler(char *input_file);
/**
* @brief Creates the executable file from the .o elf file.
*
* Calls the GNU linker 'ld'.
*
* @param input_file The file path to the .o elf file.
*/
void execute_linker(const char *input_file);
/**
* @brief Creates the executable file from the .o elf file.
*
* Compiles the source.
* This function calls create_assembly_source(),execute_assembler() and execute_linker() with proper arguments.
*
* @param input_fp The brainfuck source file.
*/
void compile(FILE *input_fp);
/**
* @brief The main start point of the compiler.
*
* @param argc The number of arguments.
* @param argv Pointer to the argument list.
*/
int main(int argc, char **argv);
</code></pre>
<h2>stack.h</h2>
<pre><code>#pragma once
#include <stdbool.h>
#include <stdlib.h>
/** A Node on the stack */
struct StackNode
{
/** The address of loop start */
unsigned int jmp_address;
/** The address of loop end */
unsigned int second_jmp_address;
/** The address of the next node in stack */
struct StackNode *next;
};
/**
* @brief Creates a new node
*
* Creates a new node in the stack.
* Memory is allocated on the heap.
* The next stackNode is automatically set to NULL.
*
* @param jmp_addr The jump label index for the start of loop.
* @param second_jmp_addr The jump label index for the end of loop.
* @return The new node created.
*/
struct StackNode *newNode(int jmp_addr, int second_jmp_addr);
/**
* @brief Checks if the stack is empty.
*
* @param root The current stack top.
* @return If stack is empty
*/
bool isEmpty(struct StackNode *root);
/**
* @brief Push a new node to top of stack
*
* @param root The current stack top.
* @param jmp_addr The jump label index for the start of loop.
* @param second_jmp_addr The jump label index for the end of loop.
*/
void push(struct StackNode **root, int jmp_addr, int second_jmp_addr);
/**
* @brief Pop the top of stack and free memory allocated on the heap.
* The next node becomes the top of the stack.
*
* @param root The current stack top.
*/
bool pop(struct StackNode **root);
</code></pre>
<h2>compiler.c</h2>
<pre><code>#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include "bf_asm.h"
#include "stack.h"
#include "compiler.h"
void verify_syntax(FILE *inputfp)
{
char c;
unsigned int stack_count = 0;
unsigned int line = 0;
while ((c = fgetc(inputfp)) != EOF)
{
if (c == ']')
stack_count--;
if (c == '[')
stack_count++;
if (c == '\n')
line++;
if (stack_count < 0)
{
fprintf(stderr, "SYNTAX ERROR: Unexpected instruction '%c' in line %u. A corresponding bracket couldn't be found.\n", c, line);
exit(EXIT_FAILURE);
}
}
if (stack_count > 0)
{
fprintf(stderr, "SYNTAX ERROR: Brackets are not balanced. Found %u stray brackets.\n", stack_count);
exit(EXIT_FAILURE);
}
fseek(inputfp, 0, SEEK_SET);
}
void assemble(FILE *inputfp, FILE *outputfp)
{
char c;
fputs(ALLOCATE_MEMORY, outputfp);
unsigned int jmp_label = 0;
struct StackNode *stack = NULL;
while ((c = fgetc(inputfp)) != EOF)
{
switch (c)
{
case '+':
case '-':
{
int counter = (c == '+') ? 1 : -1;
while ((c = fgetc(inputfp)) != EOF) //Counts the total value to be put into the cell
{
if (c == '+')
counter++;
if (c == '-')
counter--;
if (c == '<' || c == '>' || c == '.' || c == ',' || c == ']' || c == '[')
{
fseek(inputfp, -1, SEEK_CUR);
break;
}
}
if (counter > 0)
fprintf(outputfp, INCREMENT, counter);
else if (counter < 0)
fprintf(outputfp, DECREMENT, (-counter));
break;
}
case '>':
case '<':
{
int counter = (c == '>') ? 1 : -1;
while ((c = fgetc(inputfp)) != EOF) //Counts the total value be increased to the pointer of cell.
{
if (c == '>')
counter++;
if (c == '<')
counter--;
if (c == '+' || c == '-' || c == '.' || c == ',' || c == ']' || c == '[')
{
fseek(inputfp, -1, SEEK_CUR);
break;
}
}
if (counter > 0)
fprintf(outputfp, INCREMENT_POINTER, (unsigned int)(counter * sizeof(char) * 4));
else if (counter < 0)
fprintf(outputfp, DECREMENT_POINTER, (unsigned int)((-counter) * sizeof(char) * 4));
break;
}
case '.':
fputs(WRITE_CHAR, outputfp);
break;
case ',':
fputs(READ_CHAR, outputfp);
break;
case '[':
{
push(&stack, jmp_label, jmp_label + 1);
fprintf(outputfp, "_LABEL_%u:\n", jmp_label);
fputs(LOOP_START, outputfp);
fprintf(outputfp, "_LABEL_%u\n", jmp_label + 1);
jmp_label += 2;
break;
}
case ']':
{
fprintf(outputfp, "_LABEL_%u:\n", stack->second_jmp_address);
fputs(LOOP_END, outputfp);
fprintf(outputfp, "_LABEL_%u\n", stack->jmp_address);
pop(&stack);
}
default:;
}
}
fputs(SYS_EXIT_CALL, outputfp);
}
void print_help()
{
puts("Usage: bf [OPTION] -f [INPUT FILE]\n"
"Compiles brainfuck code to 32-bit executable file.\n"
"\nThe cell size is set to 30,000 and one byte is allocated to each cell.\n"
"\nThe default output file is 'a.out'.\n"
"This compiler also uses the GNU linker 'ld' and the GNU assembler 'as'.\n"
"Make sure both of these are installed and in your path before running this program.\n"
"\nOptions:\n"
" -f <INPUT FILE> \t\tSpecifies the input file.\n"
" -o <OUTPUT FILE> \t\tSpecifies the output file.\n"
" -h \t\tDisplay the help message.\n");
}
void parse_args(int argc, char **argv)
{
global_args.output_file = "a.out";
global_args.input_file = NULL;
int opt;
while ((opt = getopt(argc, argv, "ho:f:")) != -1)
{
if (opt == 'h')
{
print_help();
exit(EXIT_SUCCESS);
}
if (opt == 'o')
global_args.output_file = optarg;
if (opt == 'f')
global_args.input_file = optarg;
}
if (global_args.input_file == NULL)
{
fputs("ERROR: No input file was specified.\n\n", stderr);
print_help();
exit(EXIT_FAILURE);
}
}
void create_assembly_source(FILE *inputfp, const char *assembler_output_file)
{
FILE *assembler_output_fp = fopen(assembler_output_file, "w");
if (assembler_output_fp == NULL)
{
fprintf(stderr, "The file %s couldn't be opened while assembling code.", assembler_output_file);
exit(EXIT_FAILURE);
}
assemble(inputfp, assembler_output_fp);
fclose(assembler_output_fp);
}
void execute_assembler(char *assembler_input_file)
{
const char *start_command = "as --32 ";
char *command = (char *)malloc(sizeof(char) * (strlen(start_command) + strlen(assembler_input_file) * 2 + 5));
if (command == NULL)
{
fputs("FATAL: Memory allocation failed.", stderr);
exit(EXIT_FAILURE);
}
strcpy(command, start_command);
strcat(command, assembler_input_file);
strcat(command, " -o ");
assembler_input_file[strlen(assembler_input_file) - 1] = 'o';
strcat(command, assembler_input_file);
assembler_input_file[strlen(assembler_input_file) - 1] = 's';
system(command);
remove(assembler_input_file);
free(command);
}
void execute_linker(const char *linker_input_file)
{
const char *start_command = "ld -m elf_i386 -s ";
char *command = (char *)malloc(sizeof(char) * (strlen(start_command) + strlen(linker_input_file) * 2 + 4));
if (command == NULL)
{
fputs("FATAL: Memory allocation failed.", stderr);
exit(EXIT_FAILURE);
}
strcpy(command, start_command);
strcat(command, linker_input_file);
strcat(command, " -o ");
strcat(command, global_args.output_file);
system(command);
remove(linker_input_file);
free(command);
}
void compile(FILE *inputfp)
{
int str_size = strlen(global_args.output_file) + 3;
char *input_file = (char *)malloc(str_size * sizeof(char));
if (input_file == NULL)
{
fputs("FATAL: Memory allocation failed.", stderr);
exit(EXIT_FAILURE);
}
strcpy(input_file, global_args.output_file);
strcat(input_file, ".s");
create_assembly_source(inputfp, input_file);
execute_assembler(input_file);
input_file[strlen(input_file) - 1] = 'o'; //Converting input_file to .o which was created by the assembler.
execute_linker(input_file);
free(input_file);
}
int main(int argc, char **argv)
{
parse_args(argc, argv);
FILE *inputfp = fopen(global_args.input_file, "r");
if (inputfp == NULL)
{
fputs("ERROR: The input file couldn't be opened.", stderr);
exit(EXIT_FAILURE);
}
verify_syntax(inputfp);
compile(inputfp);
fclose(inputfp);
return EXIT_SUCCESS;
}
</code></pre>
<h2>stack.c</h2>
<pre><code>#include "stack.h"
#include <stddef.h>
#include <stdio.h>
struct StackNode *newNode(int jmp_addr, int second_jmp_addr)
{
struct StackNode *stack_node =
(struct StackNode *)malloc(sizeof(struct StackNode));
if (stack_node == NULL)
{
fputs("FATAL: Memory allocation failed.", stderr);
exit(EXIT_FAILURE);
}
stack_node->jmp_address = jmp_addr;
stack_node->second_jmp_address = second_jmp_addr;
stack_node->next = NULL;
return stack_node;
}
bool isEmpty(struct StackNode *root)
{
return !root;
}
void push(struct StackNode **root, int jmp_addr, int second_jmp_addr)
{
struct StackNode *stack_node = newNode(jmp_addr, second_jmp_addr);
stack_node->next = *root;
*root = stack_node;
}
bool pop(struct StackNode **root)
{
if (isEmpty(*root))
return false;
struct StackNode *temp = *root;
*root = (*root)->next;
free(temp);
return true;
}
</code></pre>
| [] | [
{
"body": "<p><strong>I'm mostly reviewing the code-gen choices, <em>not</em> the style / implementation of the compiler itself.</strong></p>\n\n<p>The compiler itself mostly looks fine in the parts I've skimmed over (looking for how it uses the format strings). The design is pretty clear and easy to dive into, and the C is well-formatted. It could be simpler and/or more efficient in some cases. (e.g. an array instead of linked-list for the stack would be faster, but without a C++ std::vector to handle reallocation for you you'd have to pick an arbitrary large size. But that's normally fine because untouched virtual memory normally doesn't cost anything.)</p>\n\n<hr>\n\n<p>Writing an optimizing compiler is a huge task. If you want efficient asm, by far your best bet is to take advantage of an existing optimizing compiler back-end like LLVM or GCC.</p>\n\n<p>For example, compile to LLVM-IR instead of x86 asm directly, and let LLVM-end produce optimized asm for whatever target platform. (This also gets you portability to multiple platforms, like ARM, MIPS, and/or different OSes, except for your dependence on x86 Linux system calls.) LLVM-IR looks like an assembly language, and can be compiled from a stand-alone file by clang, similar to how as + ld can compile a <code>.s</code></p>\n\n<p>Or see <a href=\"https://llvm.org/docs/tutorial/index.html\" rel=\"noreferrer\">https://llvm.org/docs/tutorial/index.html</a> for a (possibly out-of-date) tutorial on implementing a language with LLVM as a back end, where you write the front-end. (Writing your compiler as a gcc front-end is also an option, using the GCC back-end instead of LLVM.) </p>\n\n<p>It's kind of fun that BF is such a simple language that you can get non-terrible performance by transliterating it into x86 asm, though, with only local optimizations like collapsing a sequence if increments into a single add/sub.</p>\n\n<p><strong>Another option is to transliterate to C, and feed that to an optimizing C compiler.</strong> Let it optimize a few frequently-used memory cells (array elements) into registers. Or even auto-vectorize a sequence of INCREMENT and INCREMENT_POINTER into <code>paddb</code> instructions.</p>\n\n<hr>\n\n<h3>32-bit Linux <code>int 0x80</code> is low-performance</h3>\n\n<p>If you're going to make a lot of system calls, x86-64 <code>syscall</code> has lower overhead than 32-bit <code>int 0x80</code>, both intrinsically (the <code>int</code> instruction itself is slower than <code>syscall</code>) and a little bit inside the kernel with slightly more efficient dispatch for native system calls instead of compat 32-bit. However, this is pretty minor compared to system call overhead with Spectre + Meltdown mitigation enabled on current CPUs, though (that makes adds enough overhead to make simple system calls maybe 10x more expensive than before, dwarfing the difference between <code>int 0x80</code> vs. <code>syscall</code> or <code>sysenter</code>)</p>\n\n<p>If you do want to keep using 32-bit code, calling into the VDSO so it can use <code>sysenter</code> is faster than using the simple / slow 32-bit x86 <code>int 0x80</code> ABI.</p>\n\n<p><strong>Or better, use libc's stdio to buffer I/O.</strong> emit code to call <a href=\"http://man7.org/linux/man-pages/man3/unlocked_stdio.3.html\" rel=\"noreferrer\"><code>putchar_unlocked</code> and <code>getchar_unlocked</code></a>. (The 32-bit ABI sucks, passing args on the stack. The x86-64 ABI uses register args. In x86-64 System V, <code>rdi</code> is a call-clobbered register so you'd probably want to use <code>rbx</code> for your pointer.)</p>\n\n<p>You might have to call <code>fflush_unlocked(stdout)</code> before <code>getchar</code>, because (unlike C++ cin/cout), getchar doesn't automatically flush buffered output before blocking to read input, and a BF program might print a prompt that doesn't end with <code>\\n</code> before reading input. To keep the generated code compact, you might want to emit a definition (at the top of the asm) for a helper function that sets up the arg-passing and calls the real libc function.</p>\n\n<p>In I/O intensive BF programs, buffered stdio could maybe give you a speedup by a factor of 100 or 1000, with getchar / <code>putchar_unlocked</code> being nearly free compared to a system call that's only needed much less frequently.</p>\n\n<hr>\n\n<h2>Code-gen choices</h2>\n\n<p><code>xor ebx,ebx</code> / <code>inc ebx</code> saves 2 bytes but isn't generally faster than <code>mov ebx, 1</code>. But you're only doing this as part of a system-call sequence, and you're potentially compiling large programs into big straight-line sequences of code, so this is not bad. <strong>You actually have a register with a known value of <code>1</code> (EDX) at all times other than inside the ALLOC block, so <code>mov ebx, edx</code> is by far your best bet.</strong></p>\n\n<p><code>add eax,30000</code> / <code>mov ebx,eax</code> to EBX should be done with <code>lea ebx, [eax + 30000]</code> since you overwrite EAX afterwards anyway. The LEA instruction is good as a copy-and-add.</p>\n\n<p>You can also use LEA to put small constants in registers, given a known base. You have EDX=1, so you can do <code>lea eax, [edx-1 + 0x04]</code> for <code>__NR_write</code>. This is a 3-byte instruction, same as <code>xor-zero</code>/<code>inc</code> or <code>push imm8</code>/<code>pop</code>, but almost as efficient as <code>mov eax, 0x04</code>. (Runs on fewer possible ports on many CPUs, but still only 1 single-uop instruction with single-cycle latency on all relevant CPUs. <a href=\"https://agner.org/optimize/\" rel=\"noreferrer\">https://agner.org/optimize/</a>)</p>\n\n<hr>\n\n<h2>ALLOCATE_MEMORY: use the BSS unless you want dynamic growth</h2>\n\n<p>You allocate this at program startup, and never dynamically allocate more. <em>If</em> you wanted to support that (e.g. handle SIGSEGV if the program uses more memory than had allocated), then yes, <code>brk</code> is a decent choice for allocating more contiguous memory. (<code>mmap(MAP_ANONYMOUS)</code> does let you give a hint address, which the kernel will use if there aren't any conflicting mappings, but <code>brk</code> leaves room to grow.)</p>\n\n<p>But for your current simple design, where you allocate it all up front, you might as well use the BSS and let the kernel's ELF program loader do the allocation for you.</p>\n\n<p>You're targeting Linux, which like other modern OSes does lazy allocation. <strong>Allocated virtual pages aren't backed by real physical pages until they're written.</strong> They're often not even wired into the hardware page table. Thus <strong>it costs you basically nothing to use a large-ish BSS array like 2MB, and won't waste physical RAM for programs that only touch the first 4k of it.</strong> 2MB is the size of an x86-64 hugepage, so a BF program that uses most of its 2MB might get fewer TLB misses if the kernel decides to use one hugepage instead of separate 4k pages. (Linux can use transparent hugepages for the BSS, I think.)</p>\n\n<pre><code>const char PROGRAM_INIT[] = \".intel_syntax noprefix\\n\"\n \".global _start\\n\"\n \"_start:\\n\"\n \".lcomm bf_memory, 2 * 1024 * 1024\\n\"\n \"mov edx, 1\\n\"\n \"mov edi, OFFSET bf_memory\\n\"\n</code></pre>\n\n<p><strong>Note I changed the variable name from <code>ALLOCATE_MEMORY</code>, because that doesn't clearly imply once-at-startup</strong>, and some of the stuff in that string is definitely only once.</p>\n\n<p><code>.lcomm</code> allocates space in the BSS without needing to use <code>.section .bss</code>. (And unlike <code>.comm</code>, the label is a file-scoped local label.)</p>\n\n<p>I tested this, and it correctly assembles to a program that maps <code>0x200000</code> bytes of virtual memory. You can see the segment in the program headers with <code>readelf -a</code>.</p>\n\n<hr>\n\n<h2>ADD vs. SUB decision</h2>\n\n<pre><code> if (counter > 0)\n fprintf(outputfp, INCREMENT, counter);\n else if (counter < 0)\n fprintf(outputfp, DECREMENT, (-counter));\n</code></pre>\n\n<p>This is unnecessary: x86's ADD instruction works with negative immediates. For the plain <code>INCREMENT</code> (memory-destination), the operand-size is <code>byte</code> so it's always going to be an 8-bit immediate, even if it has to be truncated at assemble time. (Which is fine; it means the BF program wrapped its counter, and that truncation by the assembler does the same modulo-256 that you want to implement for BF, I assume.) So there's no saving from using <code>sub</code> -128 instead of <code>add</code> 128 to allow a narrower immediate. 8-bit <code>128</code> and <code>-128</code> are the same number.</p>\n\n<p>You might as well just <code>ADD</code> the signed count, unless you care about how CF and OF flags are set.</p>\n\n<pre><code> if (counter & 0xFF != 0)\n fprintf(outputfp, INCREMENT, counter);\n // else optimize away cancelling / wrapping operations\n</code></pre>\n\n<p><strong>For the <code>INCREMENT_POINTER</code> version of this, you <em>want</em> to use <code>add edi, -128</code> instead of sub 128, because -128 can use a more compact signed 8-bit <code>imm8</code> encoding</strong>. Immediates in the <code>[-128, 127]</code> range can use the <code>add r/m32, sign_extended_imm8</code> encoding.</p>\n\n<p>It's worth considering keeping your pointer in EAX so the compact <code>add/sub \neax, imm32</code> encoding is available (saving 1 byte vs. the generic <code>add/sub r/m32, imm32</code> encoding that uses a ModRM to encode the register or addressing mode instead of implicit EAX). But EAX is used for system calls, so they'd need to <code>mov eax, ecx</code> after system calls to put the pointer back. Since pointer increments of more than 128 are probably rare in most BF programs, and it only saves 1 byte of code-size then, it's not worth it.</p>\n\n<p><strong>The Linux <code>int 0x80</code> ABI does <em>not</em> clobber any registers other than the return value in EAX, so your best bet is to keep your pointer in ECX, not EDI.</strong> Then you don't need any <code>mov ecx, edi</code> instructions.</p>\n\n<p>So for the pointer version, you might want to do</p>\n\n<pre><code> if (counter > 0)\n fprintf(outputfp, DECREMENT_POINTER, -counter); // Prefer negative immediates for code-size\n else if (counter < 0)\n fprintf(outputfp, INCREMENT_POINTER, counter);\n // else no net offset: optimize away\n</code></pre>\n\n<p>Passing signed negative counts to printf means that for correctness we should change the format strings to use decimal counts, <code>%d</code>, not <code>0x%02x</code>. (And BTW, you can get printf to print the <code>0x</code> part by using <code>%#02x</code>). GCC prints asm using signed decimal integers, so there's precedent there for simplicity of doing it this way, even though hex is a more efficient format to write and to parse.</p>\n\n<p>(Your version with <code>%02x</code> was not strictly correct: <code>counter</code> is a signed <code>int</code> but you're passing it a format string that expects <code>unsigned int</code>. On a 2's complement system where they're the same width with no padding, that's equivalent, but you don't need to assume that if you make your types match your format string. Compile with <code>-Wall</code> to get gcc/clang to warn about format string mismatches. You might need to enable optimization to get warnings to work with global variables instead of string literals.)</p>\n\n<hr>\n\n<h2>Pointer scaling??</h2>\n\n<pre><code> if (counter > 0)\n fprintf(outputfp, INCREMENT_POINTER, (unsigned int)(counter * sizeof(char) * 4));\n else if (counter < 0)\n fprintf(outputfp, DECREMENT_POINTER, (unsigned int)((-counter) * sizeof(char) * 4));\n break;\n</code></pre>\n\n<p><strong>Scaling the <em>target</em> count by the host <code>sizeof(char)</code> is a bug</strong>: it will compile differently depending on what platform you're cross-compiling from. Or it would if <code>sizeof(char)</code> wasn't fixed at 1 by ISO C.</p>\n\n<p>It's still a logical error, unless your program is only supposed to work when running on the target machine (not cross-compiling). (If that was the case, you could avoid hard-coding the system-call numbers, and <code>#include <unistd_32.h></code> and use <code>__NR_write</code> instead of <code>0x04</code>. But there's no reason this compiler shouldn't itself be portable C and run on PowerPC Windows NT for example, still producing the same x86 asm.)</p>\n\n<p><strong>I don't understand why we're scaling by 4, though, because you're using <code>add/sub byte ptr [edi]</code>, so your cells are only 1 byte wide in the target machine's memory</strong>. Maybe I missed something elsewhere, and you're using the other 3 bytes of each cell for something?</p>\n\n<hr>\n\n<p><strong>For most modern CPUs, <code>inc</code>/<code>dec</code> are not slower than add/sub on registers</strong>, so (if remove the scale factor) you could look for that peephole optimization on <code>INCREMENT_POINTER</code> / <code>DECREMENT_POINTER</code>. (<a href=\"https://stackoverflow.com/questions/36510095/inc-instruction-vs-add-1-does-it-matter\">INC instruction vs ADD 1: Does it matter?</a>). This will save you 2 bytes in 32-bit mode, or 1 byte in 64-bit mode. (Although instruction-fetch in the front-end is probably not a bottleneck when executing code generated by this compiler.)</p>\n\n<p>But on modern Intel CPUs <code>inc</code>/<code>dec [mem]</code> is 3 uops vs. 2 for add/sub 1, so you <em>don't</em> want to look for inc/dec as a peephole optimization for <code>INCREMENT</code>. That's why I didn't mention it in the previous section.</p>\n\n<p><strong>Thus <code>inc edi</code>/<code>dec edi</code> is a peephole optimization we can look for</strong>. I've renamed the format-strings to x86-specific instruction names. If you're planning ports to other targets, you might keep the ADD/SUB names and have a name like <code>SUB1_POINTER</code> for that special case. But some ISAs like MIPS for example don't have a sub-immediate instruction at all: just add-immediate with a sign-extended immediate. (Some MIPS assemblers support <code>subi</code> as a pseudo-instruction).</p>\n\n<pre><code> // look for the inc / dec peephole optimization.\n if (counter > 0) {\n if (counter == 1) { // && tune != silvermont or P4\n fprintf(outputfp, INC_POINTER);\n } else {\n fprintf(outputfp, SUB_POINTER, -counter); // Prefer negative immediates for larger range with imm8\n }\n } else if (counter < 0) {\n if (counter == -1) {\n fprintf(outputfp, DEC_POINTER);\n } else {\n fprintf(outputfp, ADD_POINTER, counter);\n }\n }\n // else no net offset: optimize away\n</code></pre>\n\n<hr>\n\n<h2>Using FLAGS results</h2>\n\n<p><strong><code>LOOP_START</code> / <code>LOOP_END</code> can omit the <code>cmp byte ptr [edi],0x00</code> if ZF is already set according to the 0 / non-zero status of <code>[edi]</code></strong>. This is the case after a non-zero <code>counter</code> for INCREMENT / DECREMENT, because add/sub set ZF according to the zero / non-zero status of the result.</p>\n\n<p>Looking for this optimization might be as easy as keeping a <code>flags_good</code> local variable that's set to <code>true</code> inside the <code>if(counter & 0xFF != 0)</code> to emit a memory-destination add, and cleared by any ADD_POINTER/DEC_POINTER / etc.</p>\n\n<hr>\n\n<h3>Optimizing for multi-byte I/O with one system call</h3>\n\n<p>If we can look for patterns like inc / write / inc / write, we can turn that into an <code>n</code>-byte <code>sys_write</code>. (Or if you decide to use libc stdio, an <code>fwrite</code> function call, but with stdio buffering this optimization becomes <em>much</em> less valuable.)</p>\n\n<p>Maybe after a <code>'.'</code>, look-ahead for a sequence of <code>+.</code>. This might miss the optimization in some cases like <code>-++</code> instead of <code>+</code>, but dumb source defeating optimizing compilers is not your problem if there's no reason anyone would ever write that in a BF program.</p>\n\n<hr>\n\n<h3>stdio lookahead in the compiler</h3>\n\n<p>Instead of using <code>fseek</code> to rewind, you can use <a href=\"http://man7.org/linux/man-pages/man3/fgetc.3.html\" rel=\"noreferrer\"><code>ungetc(c, stdin);</code></a> to <em>put back</em> a char you read. ISO C guarantees that at least 1 char of pushback is supported, which is all you need. I assume glibc usually supports more.</p>\n\n<p>Another option might be to put reading the next character at the bottom of the loop, separate from the loop condition, so you could use <code>continue;</code>. That might be kind of ugly, though.</p>\n\n<p>Or since it's not rare for your parser to want lookahead, bake that in to the main loop.</p>\n\n<pre><code>int c, next_c = fgetc(inputfp);\nwhile (c = next_c, next_c = fgetc(inputfp), c != EOF) {\n ...\n}\n</code></pre>\n\n<p>The loop body will run with <code>c = last_char</code> and <code>next_c = EOF</code>. I'm not sure if there's a better idiom for this; I just made this up and I'm not sure it's as clean as I'd like. Perhaps a <code>do{}while()</code> loop structure would be better, with the <code>c = next_c</code> stuff at the top.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T23:06:11.120",
"Id": "215885",
"ParentId": "215574",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "215885",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T15:39:13.930",
"Id": "215574",
"Score": "17",
"Tags": [
"c",
"console",
"assembly",
"brainfuck",
"compiler"
],
"Title": "Brainfreeze: A Brainfuck compiler in C"
} | 215574 |
<p>I am experimenting with Perlin Noise and random map generation. I have a 2D numpy ndarray full of 16-bit floats called <code>map_list</code> that I call from the singleton <code>ST</code>. It has 900 rows with 1600 elements each. I am iterating through it to display different colored pixels to represent terrain at different points in the map. Array values in different ranges produce pixels of different colors. The total possible range is [0, 1] because I am normalizing the values. </p>
<p>Is there a way to display the aforementioned pixels faster than I am capable of now?</p>
<pre><code>"""
This file holds functions that modify pyGame surfaces.
"""
from __future__ import division
from singleton import ST
from pygame import gfxdraw
def display_map(surface):
"""
This takes in a pyGame surface, and draws colored tiles on it according to
the values in ST.map_list. The higher the value, the lighter the shade of
the tile.
:param surface: A pyGame surface.
"""
x_pos = 0
y_pos = 0
for y in range(len(ST.map_list)):
for x in range(len(ST.map_list[y])):
noise_value = ST.map_list[y][x]
shade = int(noise_value * 255)
color = __color_tiles(noise_value, shade)
gfxdraw.pixel(surface, x_pos, y_pos, color)
x_pos += ST.TILE_SIZE
x_pos = 0
y_pos += ST.TILE_SIZE
def __color_tiles(noise_value, shade):
"""
Treat this function as private. It should only be called by functions and
methods within this file. It returns a 3-element 1D tuple that represents
the rgb color values to display the tile as.
:param noise_value: The noise value at a specific point in ST.map_list.
:param shade: How dark or light the tile should be.
:return: tuple
"""
if noise_value < ST.WATER_LEVEL:
rgb = (shade, shade, 255)
elif noise_value > ST.MOUNTAIN_LEVEL:
rgb = (shade, shade, shade)
else:
rgb = (shade, 255, shade)
return rgb
</code></pre>
<p><strong>What it generates</strong></p>
<p><a href="https://i.stack.imgur.com/Y86TM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y86TM.png" alt="enter image description here"></a></p>
| [] | [
{
"body": "<p>If you have a lot of data in a rectangle, and you need to go fast, the answer is always the same: <code>import numpy as np</code></p>\n\n<p>Pygame has added some functions that support numpy arrays for exactly this reason. So you can fairly painlessly convert from an appropriately sized numpy array to a surface. You could even go back again, if you wanted.</p>\n\n<p>Here's some code that does something similar to what you appear to be doing. I stripped out the stuff that you didn't provide source for, and focused on just doing the high/low/mid cutoff you seem to want. Also note, I'm using python 3, so there will likely be some slight gotchas in the syntax:</p>\n\n<pre><code># https://codereview.stackexchange.com/questions/215575/plotting-terrain-pixels-with-pygame-based-on-random-numpy-array\n\"\"\"\n\nThis file holds functions that modify pyGame surfaces.\n\n\"\"\"\n\nimport numpy as np\nimport pygame\n\nscreen_size = (180, 320)\n\ndef display_map(noise): # NOTE: I expect noise to be a 2-d np.ndarray\n ''' Return a surface with terrain mapped onto it. '''\n\n CHANNELS = 3 # use 4 for alpha, I guess\n RED = 0\n GREEN = 1\n BLUE = 2\n WATER_LEVEL = 0.20\n MOUNTAIN_LEVEL = 0.75\n\n # NOTE: numpy automagically \"vectorizes\" things like this. \n # array times scalar means a[i,j] * scalar, for all i,j\n shade = (noise * 255).astype(np.ubyte)\n\n # NOTE: dstack \"stacks\" however-many 2d arrays along the \"depth\" axis\n # producing a 3d array where each [i,j] is (X,X,X)\n rgb = np.dstack([shade] * 3)\n\n # NOTE: (WATER_LEVEL <= noise) produces a 2d boolean array, where \n # result[i,j] = (WATER_LEVEL <= noise[i,j]), kind of like the scalar\n # multiply above. The '&' operator is overloaded for boolean 'and'.\n # The upshot is that this assignment only happens where the boolean\n # array is 'True'\n rgb[(WATER_LEVEL <= noise) & (noise <= MOUNTAIN_LEVEL), GREEN] = 255\n rgb[(noise < WATER_LEVEL), BLUE] = 255\n\n # NOTE: pygame.surfarray was added mainly to talk to numpy, I believe.\n surf = pygame.surfarray.make_surface(rgb)\n return surf\n\npygame.init()\nrunning = True\ndisplay = pygame.display.set_mode(screen_size)\n\nnoise = np.random.random_sample(screen_size)\nterrain = display_map(noise)\n\nwhile running:\n for ev in pygame.event.get():\n if ev.type == pygame.QUIT:\n running = False\n\n display.blit(terrain, (0, 0))\n pygame.display.update()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T02:59:37.520",
"Id": "215643",
"ParentId": "215575",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215643",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T17:19:58.177",
"Id": "215575",
"Score": "7",
"Tags": [
"python",
"performance",
"python-2.x",
"numpy",
"pygame"
],
"Title": "Plotting terrain pixels with PyGame based on random NumPy array"
} | 215575 |
<p>Please review my serial port class written in C++. It is completely asynchronous, ie event driven. My idea for later is to inherit from this a sync_serial, where timeouts can be specified and it waits for responses. But that is not the purpose of this review. It is Windows only and I have tested on a Conexant voice modem. It uses the Microsoft overlapped IO model.</p>
<p>Header file, async_serial.hpp:</p>
<pre><code>/*
asynchronous serial communications class
*/
#ifndef ASYNC_SERIAL_
#define ASYNC_SERIAL_
#include <thread>
#include <queue>
#include <unordered_map>
#include <stdint.h>
// forward declare pimpl
struct serialimpl;
// utility namespace
namespace utl {
enum line_status {
LS_CTS, // clear to send signal changed state
LS_DSR, // data set ready signal changed
LS_CD, // carrier detect signal changed state
LS_BREAK, // a break was detected in input
LS_ERR, // a line status error occurred
LS_RING // ring indicator detected
};
struct datum
{
datum(char* data, size_t length) : data_(data), length_(length) {}
char* data_;
size_t length_;
};
enum parity_type
{
PARITYTYPE_NONE, // most common
PARITYTYPE_ODD,
PARITYTYPE_EVEN
};
// bits per packet/frame
enum databits_type
{
DATA_5 = 5,
DATA_6 = 6,
DATA_7 = 7,
DATA_8 = 8 // most common
};
enum stopbits_type
{
STOPBIT_1, // most common
STOPBIT_1_5,
STOPBIT_2
};
enum flow_control_type
{
FLOWCONTROL_OFF, // no flow control - worth trying to get something working
FLOWCONTROL_HARDWARE_RTSCTS, // For best performance if supported by modem/cable
FLOWCONTROL_HARDWARE_DTRDSR, // not very common hardware flow control
FLOWCONTROL_XONXOFF // if cable has no flow control pins connected
};
struct port_settings
{
port_settings(unsigned baud, databits_type databits = DATA_8, parity_type parity = PARITYTYPE_NONE,
unsigned stopbits = STOPBIT_1, flow_control_type flowcontrol = FLOWCONTROL_HARDWARE_RTSCTS)
: baud_rate_(baud), databits_(databits), parity_type_(parity), stopbits_(stopbits), flowcontrol_(flowcontrol) {}
unsigned baud_rate_; // speed in bits per second
databits_type databits_; // usually set to 8 (8 bits per packet/frame)
parity_type parity_type_;
unsigned stopbits_;
flow_control_type flowcontrol_;
};
class async_serial
{
public:
// construct using port and baudrate
async_serial(int port, unsigned baudrate);
// construct using port and port_settings data
async_serial(int port, port_settings settings);
// close port related system resources
virtual ~async_serial();
// open serial port and setup handling for data
virtual bool open();
// check if serial port open
bool is_open() const;
// close serial port
virtual bool close();
// write data to port
bool write(const char* data, size_t length);
// override this function to handle received data
virtual void on_read(char* data, size_t length);
// override this function to identify when data successfully sent
virtual void on_write();
// override this function to indentify serial port state changes
virtual void on_status(const unsigned statechange, bool set = true);
// // override this function for diagnostic information
virtual void on_error(const std::string& error);
// get line status
inline unsigned get_status() const { return status_; }
// helper to convert status to a descriptive string
std::string get_status_string();
// helper function to get list of ports available and any available string description
static long enumerate_ports(std::unordered_map <uint32_t, std::string>& ports);
async_serial(const async_serial&) = delete;
async_serial& operator=(const async_serial&) = delete;
private:
// forward declare pimpl
serialimpl *pimpl_; // Handle object - pimpl
std::thread reader_thread; // thread to handle read events
void reader_thread_func(); // read thread handler function
bool closing_port_; // to indicate port is in process of being closed
int port_; // port indentifier
unsigned status_; // status indication
void update_pin_states(); // updates internal pin status flags
void update_error_states(unsigned long comm_event); // reports errors if any
port_settings settings_;
bool configure_comport(); // initial port setup called in open
std::thread writer_thread; // thread to handle write events
void writer_thread_func(); // write thread handler function
std::queue<datum> write_queue_; // data is queued for sending/(writing)
inline bool job_queue_empty() const { return write_queue_.empty(); }
};
} // utl
#endif // ASYNC_SERIAL_
</code></pre>
<p>Implementation file, async_serial.cpp:</p>
<pre><code>/*
async_serial class implementation for Windows. Inspired by MTTTY sample application.
*/
#include <cstdio>
#include <cctype>
#include <chrono>
#include <memory>
#include <string>
#include <unordered_map>
#include <iostream>
#include <sstream>
#include <Windows.h>
// WMI header for Windows
#include <Wbemcli.h>
// WMI library for Windows
#pragma comment(lib, "wbemuuid.lib")
#include "async_serial.hpp"
static const DWORD READ_BUFFER_SIZE = 512;
// milliseconds timeout for waiting for serial port events - read or status
static const DWORD OVERLAPPED_CHECK_TIMEOUT = 500;
using namespace utl;
// port handle - keep system specifics out of header
// *** PROBLEM - TODO - problem if user wants to create multiple instances of class. PIMPL?
// hide implementation details from header
struct serialimpl {
HANDLE handle_ = INVALID_HANDLE_VALUE;
};
static std::string system_error() {
// Retrieve, format, and print out a message from the last error.
char buf[256] = {};
DWORD lasterror = GetLastError();
DWORD chars = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, lasterror, 0, buf, 255, NULL);
std::string error;
if (chars) {
error = buf;
}
else {
error = "FormatMessage returned zero characters. Last error code: ";
error += std::to_string(lasterror);
}
return error;
}
static std::string create_error_msg(const char* prepend) {
std::string s(prepend);
s += system_error();
return s;
}
long async_serial::enumerate_ports(std::unordered_map <uint32_t, std::string>& ports) {
// Initialize COM.
HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hr))
return hr;
// Initialize security for application
hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
if (FAILED(hr)) {
CoUninitialize();
return hr;
}
//Create the WBEM locator (to WMI)
std::shared_ptr<IWbemLocator> wben_locator;
hr = CoCreateInstance(CLSID_WbemLocator, nullptr, CLSCTX_INPROC_SERVER,
IID_IWbemLocator, reinterpret_cast<void**>(&wben_locator));
if (FAILED(hr)) {
CoUninitialize();
return hr;
}
IWbemServices* wbem_services = NULL;
hr = wben_locator->ConnectServer(L"ROOT\\CimV2", nullptr, nullptr, nullptr,
0, nullptr, nullptr, &wbem_services);
if (FAILED(hr)) {
wben_locator->Release();
CoUninitialize();
return hr;
}
// WMI query of serial ports on this computer
IEnumWbemClassObject* wbem_enumerate_object = NULL;
hr = wbem_services->CreateInstanceEnum(L"Win32_SerialPort",
WBEM_FLAG_RETURN_WBEM_COMPLETE, nullptr, &wbem_enumerate_object);
if (FAILED(hr)) {
wben_locator->Release();
CoUninitialize();
return hr;
}
// Now enumerate all the ports
hr = WBEM_S_NO_ERROR;
// when no Next object enumerated, WBEM_S_FALSE returned
while (hr == WBEM_S_NO_ERROR) {
ULONG numports = 0;
IWbemClassObject** wbem_object = (IWbemClassObject**)malloc(10 * sizeof(IWbemClassObject));
hr = wbem_enumerate_object->Next(WBEM_INFINITE, 10, reinterpret_cast<IWbemClassObject**>(wbem_object), &numports);
if (SUCCEEDED(hr)) {
// if > 10 objects returned have to re-allocate wbem_object
if (numports > 10) {
wbem_object = (IWbemClassObject**)realloc(wbem_object, numports * sizeof(IWbemClassObject));
}
for (ULONG i = 0; i < numports; ++i) {
VARIANT device_property1;
const HRESULT hrGet = wbem_object[i]->Get(L"DeviceID", 0, &device_property1, nullptr, nullptr);
if (SUCCEEDED(hrGet) && (device_property1.vt == VT_BSTR) && (wcslen(device_property1.bstrVal) > 3)) {
// if deviceID is prefaced with "COM" add ports list
if (wcsncmp(device_property1.bstrVal, L"COM", 3) == 0) {
// get port number
std::wistringstream wstrm(std::wstring(&(device_property1.bstrVal[3])));
unsigned int port;
wstrm >> port;
VariantClear(&device_property1);
std::pair<UINT, std::string> pair;
pair.first = port;
// get the friendly name of the port
VARIANT device_property2;
if (SUCCEEDED(wbem_object[i]->Get(L"Name", 0, &device_property2, nullptr, nullptr)) && (device_property2.vt == VT_BSTR)) {
std::wstring ws(device_property2.bstrVal);
std::string name(ws.begin(), ws.end());
pair.second = name;
VariantClear(&device_property2);
}
ports.insert(pair);
}
}
}
}
free(wbem_object);
}
// cleanup
wbem_enumerate_object->Release();
wbem_services->Release();
wben_locator->Release();
CoUninitialize();
return S_OK;
}
// comport settings based on configuration requested
bool async_serial::configure_comport()
{
DCB dcb = { 0 };
dcb.DCBlength = sizeof(dcb);
// get current DCB settings
if (!GetCommState(pimpl_->handle_, &dcb)) {
on_error(create_error_msg("GetCommState error "));
return false;
}
// update DCB rate, byte size, parity, and stop bits size
dcb.BaudRate = settings_.baud_rate_;
dcb.ByteSize = settings_.databits_;
dcb.Parity = settings_.parity_type_;
dcb.StopBits = settings_.stopbits_;
// event flag
dcb.EvtChar = '\0';
// set suitable flow control settings
switch (settings_.flowcontrol_) {
case FLOWCONTROL_HARDWARE_RTSCTS: // most common hardware flow control
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
dcb.fOutxCtsFlow = 1;
dcb.fOutxDsrFlow = 0;
dcb.fOutX = 0;
dcb.fInX = 0;
break;
case FLOWCONTROL_HARDWARE_DTRDSR: // not very common hw flow control
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 1;
dcb.fOutX = 0;
dcb.fInX = 0;
break;
case FLOWCONTROL_XONXOFF: // software flow control
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fOutX = 1;
dcb.fInX = 1;
break;
case FLOWCONTROL_OFF: // no flow control
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fOutX = 0;
dcb.fInX = 0;
break;
}
// set the rest to suitable defaults
dcb.fDsrSensitivity = 0;
dcb.fTXContinueOnXoff = 0;
dcb.XonChar = 0x11; // Tx and Rx XON character
dcb.XoffChar = 0x13; // Tx and Rx XOFF character
dcb.XonLim = 0; // transmit XON threshold
dcb.XoffLim = 0; // transmit XOFF threshold
dcb.fAbortOnError = 0; // abort reads/writes on error
dcb.ErrorChar = 0; // error replacement character
dcb.EofChar = 0; // end of input character
// Windows does not support non-binary mode so this must be TRUE
dcb.fBinary = TRUE;
// DCB settings not in the user's control
dcb.fParity = TRUE;
// set new state
if (!SetCommState(pimpl_->handle_, &dcb)) {
on_error(create_error_msg("SetCommState error "));
return false;
}
COMMTIMEOUTS ctout = { 0x01, 0, 0, 0, 0 };
if (!SetCommTimeouts(pimpl_->handle_, &ctout)) {
on_error(create_error_msg("SetCommTimeouts error "));
}
return true;
}
async_serial::async_serial(int port, port_settings settings) :
port_(port),
settings_(settings),
closing_port_(false),
status_(0),
pimpl_(new serialimpl) {}
async_serial::async_serial(int port, unsigned baudrate)
: port_(port),
settings_(9600),
closing_port_(false),
status_(0),
pimpl_(new serialimpl) {}
void async_serial::writer_thread_func() {
OVERLAPPED overlapped_write = { 0 };
DWORD bytes_written;
// create this writes overlapped structure hEvent
overlapped_write.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (overlapped_write.hEvent == NULL)
{
on_error("Error creating writer overlapped event");
return;
}
// keep thread running all the time that we are not shutting down
while (!closing_port_) {
if (!is_open())
std::this_thread::sleep_for(std::chrono::seconds(5));
else if (job_queue_empty())
std::this_thread::sleep_for(std::chrono::seconds(1));
else {
// get next job
datum d = write_queue_.front();
write_queue_.pop();
// issue write
if (!WriteFile(pimpl_->handle_, d.data_, d.length_, &bytes_written, &overlapped_write)) {
if (GetLastError() == ERROR_IO_PENDING) {
// write is delayed
DWORD wait_result = WaitForSingleObject(overlapped_write.hEvent, OVERLAPPED_CHECK_TIMEOUT);
switch (wait_result)
{
// write event set
case WAIT_OBJECT_0:
SetLastError(ERROR_SUCCESS);
if (!GetOverlappedResult(pimpl_->handle_, &overlapped_write, &bytes_written, FALSE)) {
if (GetLastError() != ERROR_OPERATION_ABORTED) {
on_error(system_error());
}
}
if (bytes_written != d.length_) {
on_error(system_error());
}
else {
// success - we have written data ok
on_write();
}
break;
// wait timed out
case WAIT_TIMEOUT:
// timeout expected
break;
case WAIT_FAILED:
default:
on_error("WaitForSingleObject WAIT_FAILED in writer_thread_function");
break;
}
// deallocate data memory
delete[] d.data_;
}
else
// writefile failed - but not dut to ERROR_OPERATION_ABORTED
on_error(system_error());
}
else {
// writefile returned immediately
if (bytes_written != d.length_) {
on_error(system_error());
}
else {
// success - we have written data ok
on_write();
}
}
}
}
// don't leak event handle
CloseHandle(overlapped_write.hEvent);
}
std::string async_serial::get_status_string() {
std::string state;
if (status_ & (1UL << LS_CTS)) {
state += "CTS,";
}
if (status_ & (1UL << LS_DSR)) {
state += "DSR,";
}
if (status_ & (1UL << LS_CD)) {
state += "CD,";
}
if (status_ & (1UL << LS_BREAK)) {
state += "BREAK,";
}
if (status_ & (1UL << LS_ERR)) {
state += "ERROR,";
}
if (status_ & (1UL << LS_RING)) {
state += "RING,";
}
if (state.size() > 0 && state[state.size() - 1] == ',') {
state.erase(state.rfind(','));
}
return state;
}
void async_serial::update_pin_states() {
// GetCommModemStatus provides cts, dsr, ring and cd states
// if status checks are not allowed, then don't issue the
// modem status check nor the com stat check
DWORD modem_status;
if (!GetCommModemStatus(pimpl_->handle_, &modem_status))
{
on_error(create_error_msg("serial::update_pin_states GetCommModemStatus error "));
}
else {
const std::pair<unsigned, unsigned> mapping_list[] = {
{ MS_CTS_ON, LS_CTS }, { MS_DSR_ON, LS_DSR }, { MS_RING_ON, LS_RING }, { MS_RLSD_ON, LS_CD } };
for (const auto& item : mapping_list) {
bool is_set = (item.first & modem_status) == item.first;
if (is_set != ((status_ >> item.second) & 1U)) {
// update status_
is_set != 0 ? status_ |= (1 << item.second) : status_ &= ~(1 << item.second);
on_status(item.second, is_set != 0 ? true : false); // notify state change
}
}
}
}
void async_serial::reader_thread_func() {
DWORD bytes_read;
// flip between waiting on read and waiting on status events
BOOL wait_on_read = FALSE; // waiting on read
BOOL wait_on_status = FALSE; // waiting on line status events
OVERLAPPED overlapped_reader = { 0 }; // overlapped structure for read operations
OVERLAPPED overlapped_status = { 0 }; // overlapped structure for status operations
HANDLE event_array[2]; // list of events that WaitForxxx functions wait on
char read_buffer[READ_BUFFER_SIZE]; // temp storage of read data
DWORD comms_event; // result from WaitCommEvent
// Create the overlapped event. Must be closed before exiting
// to avoid a handle leak.
overlapped_reader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (overlapped_reader.hEvent == NULL)
{
on_error("Error creating reader overlapped event");
return;
}
overlapped_status.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (overlapped_status.hEvent == NULL)
{
on_error("Error creating status overlapped event");
return;
}
// array of handles to wait for signals - we wait on read and status events
event_array[0] = overlapped_reader.hEvent;
event_array[1] = overlapped_status.hEvent;
// keep thread running until shutting down flag set
while (!closing_port_) {
if (!is_open())
std::this_thread::sleep_for(std::chrono::seconds(1));
else {
if (!wait_on_read) {
// issue read operation
if (!ReadFile(pimpl_->handle_, read_buffer, READ_BUFFER_SIZE, &bytes_read, &overlapped_reader)) {
if (GetLastError() != ERROR_IO_PENDING) { // read not delayed
on_error(system_error());
break;
}
else
wait_on_read = TRUE;
}
else {
on_read(read_buffer, bytes_read);
}
}
// if no status check is outstanding, then issue another one
if (!wait_on_status) {
if (!WaitCommEvent(pimpl_->handle_, &comms_event, &overlapped_status)) {
if (GetLastError() == ERROR_IO_PENDING) {
wait_on_status = TRUE; // have to wait for status event
} else {
on_error(create_error_msg("WaitCommEvent error "));
}
} else {
// WaitCommEvent returned immediately
update_error_states(comms_event);
}
}
// wait for pending operations to complete
if (wait_on_status || wait_on_read) {
DWORD wait_result = WaitForMultipleObjects(2, event_array, FALSE, OVERLAPPED_CHECK_TIMEOUT);
switch (wait_result)
{
// read completed
case WAIT_OBJECT_0:
if (!GetOverlappedResult(pimpl_->handle_, &overlapped_reader, &bytes_read, FALSE)) {
if (GetLastError() == ERROR_OPERATION_ABORTED) {
on_error("Read aborted");
wait_on_read = FALSE;
}
else {
on_error(create_error_msg("GetOverlappedResult (in reader_thread_func) error "));
}
}
else {
// read completed successfully
if (bytes_read) {
on_read(read_buffer, bytes_read);
}
}
wait_on_read = FALSE;
break;
// status completed
case WAIT_OBJECT_0 + 1:
{
DWORD overlapped_result;
if (!GetOverlappedResult(pimpl_->handle_, &overlapped_status, &overlapped_result, FALSE)) {
if (GetLastError() == ERROR_OPERATION_ABORTED) {
on_error("WaitCommEvent aborted");
} else {
on_error(create_error_msg("GetOverlappedResult for status wait returned "));
}
}
else {
// status check completed successfully
update_error_states(comms_event);
update_pin_states();
}
wait_on_status = FALSE;
}
break;
case WAIT_TIMEOUT:
update_pin_states(); // periodically update pin states if changed
break;
default:
break;
}
}
}
}
// close reader event handle - otherwise will get resource leak
CloseHandle(overlapped_reader.hEvent);
}
async_serial::~async_serial() {
// if port is not open then reader and writer threads not running
close();
delete pimpl_;
}
bool async_serial::open() {
// in case we are already open
close();
closing_port_ = false;
// The "\\.\" prefix form to access the Win32 device namespace must be used for com ports above COM9
char portname[100] = { 0 };
_snprintf_s(portname, sizeof(portname), sizeof(portname) - 1, "\\\\.\\COM%d", port_);
pimpl_->handle_ = CreateFileA(portname, GENERIC_READ | GENERIC_WRITE, 0, 0,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 0);
if (pimpl_->handle_ == INVALID_HANDLE_VALUE)
return false;
// Save original comm timeouts and set new ones
COMMTIMEOUTS origtimeouts;
if (!GetCommTimeouts(pimpl_->handle_, &origtimeouts)) {
on_error(create_error_msg("GetCommTimeouts error "));
}
if (!configure_comport()) {
on_error("failed to configure serial port");
}
// set size of modem driver read and write buffers
if (!SetupComm(pimpl_->handle_, READ_BUFFER_SIZE, READ_BUFFER_SIZE)) {
on_error(create_error_msg("SetupComm error: "));
}
// Sends the DTR (data-terminal-ready) signal
if (!EscapeCommFunction(pimpl_->handle_, SETDTR)) {
on_error(create_error_msg("EscapeCommFunction(SETDTR) error: "));
}
// WaitCommEvent, in reader_thread_func, will monitor for these events
if (!SetCommMask(pimpl_->handle_, EV_BREAK | EV_CTS | EV_DSR | EV_ERR | EV_RING | EV_RLSD)) {
on_error(create_error_msg("SetCommMask error: "));
}
reader_thread = std::thread(&async_serial::reader_thread_func, this);
writer_thread = std::thread(&async_serial::writer_thread_func, this);
std::this_thread::yield();
return pimpl_->handle_ != INVALID_HANDLE_VALUE;
}
inline bool async_serial::is_open() const {
return pimpl_->handle_ != INVALID_HANDLE_VALUE;
}
bool async_serial::close() {
if (is_open()) {
closing_port_ = true;
// give the reader and writer threads time to finish
std::this_thread::sleep_for(std::chrono::seconds(2));
if (reader_thread.joinable())
reader_thread.join(); // prevents crash - due to terminate being called on running thread still 'alive'
if (writer_thread.joinable())
writer_thread.join();
BOOL b = CloseHandle(pimpl_->handle_);
pimpl_->handle_ = INVALID_HANDLE_VALUE;
return b == TRUE ? true : false;
}
else {
return false;
}
}
bool async_serial::write(const char* data, size_t length) {
// add to writer queue
char* cpy = new char[length]();
memcpy(cpy, data, length);
write_queue_.push(datum(cpy, length));
return true;
}
void async_serial::on_read(char* data, size_t length) {
// override this function to handle received data
}
void async_serial::on_write() {
// override this function to identify when data successfully sent
}
void async_serial::on_status(const unsigned statechange, bool set) {
// override this function to see line status changes
}
void async_serial::on_error(const std::string& error) {
// override this function for diagnostic information
}
void async_serial::update_error_states(unsigned long comm_event) {
// cache previous status for comparison
unsigned prev_status = status_;
if (comm_event & EV_BREAK) {
on_error("BREAK signal received");
status_ |= (1UL << LS_BREAK);
if (!((prev_status >> LS_BREAK) & 1U)) {
on_status(LS_BREAK, true);
}
}
else {
on_error("BREAK signal reset");
status_ &= ~(1UL << LS_BREAK);
if (((prev_status >> LS_BREAK) & 1U)) {
on_status(LS_BREAK, false);
}
}
// A line-status error occurred. Line-status errors are CE_FRAME, CE_OVERRUN, and CE_RXPARITY.
if (comm_event & EV_ERR) {
on_error("A line status error has occurred");
status_ |= (1UL << LS_ERR);
if (!((prev_status >> LS_ERR) & 1U)) {
on_status(LS_ERR, true);
}
COMSTAT ComStatNew;
DWORD dwErrors;
if (!ClearCommError(pimpl_->handle_, &dwErrors, &ComStatNew))
on_error("ErrorReporter(\"ClearCommError\")");
if (ComStatNew.fCtsHold)
on_error("waiting for the CTS(clear - to - send) signal to be sent.");
if (ComStatNew.fDsrHold)
on_error("waiting for the DSR (data-set-ready) signal to be sent.");
if (ComStatNew.fRlsdHold)
on_error("waiting for the RLSD (receive-line-signal-detect) aka CD (Carrier Detect) signal to be sent.");
if (ComStatNew.fXoffHold)
on_error("waiting because an XOFF character was received.");
if (ComStatNew.fXoffSent)
on_error("Transmission waiting because an XOFF character was sent.");
if (ComStatNew.fEof)
on_error("An end-of-file (EOF) character has been received.");
}
else {
on_error("A line status error cleared");
status_ &= ~(1UL << LS_ERR);
if (((prev_status >> LS_ERR) & 1U)) {
on_status(LS_ERR, false);
}
}
}
</code></pre>
<p>Test program, main.cpp:</p>
<pre><code>#include <iostream>
#include <unordered_map>
#include <string>
#include <chrono>
#include <thread>
#include "async_serial.hpp"
static void print_byte_as_binary(unsigned n, unsigned numbits) {
for (int i = numbits; i >= 0; i--) {
std::cout << (n & (1 << i) ? '1' : '0');
}
}
class modem_tester : public utl::async_serial {
public:
modem_tester(int port, unsigned baudrate) : utl::async_serial(port, baudrate) {
}
modem_tester(int port, utl::port_settings settings) : utl::async_serial(port, settings) {
}
virtual bool open() {
return utl::async_serial::open();
}
// bytes read
virtual void on_read(char* data, size_t length) {
std::string s(data, length);
std::cout << "data: " << s;
}
// bytes written
virtual void on_write() {
std::cout << "on_write()\n";
}
// Line status change detected
virtual void on_status(const unsigned statechange, bool set = true) {
std::cout << "on_status bit: " << statechange << " " << (set ? "set" : "not set") << std::endl;
}
virtual void on_error(const std::string& error) {
std::cout << "on_error: " << error << std::endl;
}
};
int main() {
{
// get list of ports available on system
std::unordered_map <uint32_t, std::string> ports;
utl::async_serial::enumerate_ports(ports);
for (const auto& item : ports) {
std::cout << item.first << "->" << item.second << std::endl;
}
std::cout << "From list above select port number (number before arrow)\n";
int port;
std::cin >> port;
std::cin.ignore(1, '\n'); // ignore newline received after number entered
// verify a valid port selected
if (ports.find(port) == ports.end()) {
std::cout << "You have selected a port that doesn't exist on this system. Aborting...\n";
return 0;
}
utl::port_settings ps(1200);
ps.databits_ = utl::DATA_8;
ps.flowcontrol_ = utl::FLOWCONTROL_HARDWARE_RTSCTS;
//ps.flowcontrol = utl::FLOWCONTROL_XONXOFF; // select if hardware flow control not possible
ps.parity_type_ = utl::PARITYTYPE_NONE;
ps.stopbits_ = utl::STOPBIT_1;
modem_tester s(port, 1200);
bool ret = s.open();
std::cout << "open(" << port << ") returned " << std::boolalpha << ret << std::endl;
const char* commands[] = {
"ATQ0V1E0\r\n", // initialise the query, Q0=enable result codes, V1=verbal result codes, E0=disable command echo
"AT+GMM\r\n", // Request Model Indentification
"AT+FCLASS=?\r\n", // list of supported modes (data, fax, voice)
"AT#CLS=?\r\n", // not sure, I think similar to above command (CLS being shorthand for class?)
"AT+GCI?\r\n", // currently selected country code (US=B5)
"AT+GCI=?\r\n", // list of supported country codes
"ATI0\r\n", "ATI1\r\n", "ATI2\r\n", "ATI3\r\n", "ATI4\r\n", "ATI5\r\n", "ATI6\r\n", "ATI7\r\n", // Identification requests
"AT+GMI\r\n", // Request Manufacturer Identification
"AT+GMI9\r\n", // Request Conexant Identification
"AT+GCAP\r\n" }; // Request complete capabilities list
for (const auto& cmd : commands) {
std::cout << "Sending: " << cmd;
s.write(cmd, strlen(cmd));
std::this_thread::sleep_for(std::chrono::seconds(2));
}
// Give tester 10 seconds to ring modem - check for RING indicator - LS_RING
std::this_thread::sleep_for(std::chrono::seconds(10));
print_byte_as_binary(s.get_status(), 6);
std::cout << '\n' << s.get_status_string() << '\n';
ret = s.close();
std::cout << "close() returned " << std::boolalpha << ret << std::endl;
} // out of scope - so can check destructor
std::cout << "finished\n";
}
</code></pre>
<p>Example output using a Conexant voice modem:</p>
<pre><code>1->Communications Port (COM1)
4->SAMSUNG Mobile USB Modem
12->Conexant USB CX93010 ACF Modem
From list above select port number (number before arrow)
12
open(12) returned true
on_status bit: 0 set
on_status bit: 1 set
on_status bit: 5 set
Sending: ATQ0V1E0
on_write()
data:
OK
Sending: AT+GMM
on_write()
data:
+GMM: V90
OK
Sending: AT+FCLASS=?
on_write()
data:
0,1,1.0,2,8
OK
Sending: AT#CLS=?
on_write()
data:
ERROR
Sending: AT+GCI?
on_write()
data:
+GCI: B4
OK
Sending: AT+GCI=?
on_write()
data:
+GCI: (00,07,09,0A,0F,16,1B,20,25,26,27,2D,2E,31,36,3C,3D,42,46,50,51,52,53,54,5
7,58,59,61,62,64,69,6C,73,77,7B,7E,82,84,89,8A,8B,8E,98,99,9C,9F,A0,A1,A5,A6,A9,
AD,AE,B3,B4,B5,B7,B8,C1,F9,FA,FB,FC,FD,FE)
OK
Sending: ATI0
on_write()
data:
56000
OK
Sending: ATI1
on_write()
data:
OK
Sending: ATI2
on_write()
data:
OK
Sending: ATI3
on_write()
data:
CX93001-EIS_V0.2013-V92
OK
Sending: ATI4
on_write()
data:
OK
Sending: ATI5
on_write()
data:
B4
OK
Sending: ATI6
on_write()
data:
OK
Sending: ATI7
on_write()
data:
OK
Sending: AT+GMI
on_write()
data:
+GMI: CONEXANT
OK
Sending: AT+GMI9
on_write()
data:
+GMI9: CONEXANT ACF
OK
Sending: AT+GCAP
on_write()
data:
+GCAP: +FCLASS,+MS,+ES,+DS
OK
0100011
CTS,DSR,RING
close() returned true
on_error: Read aborted
finished
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T19:51:35.750",
"Id": "418609",
"Score": "0",
"body": "this is not asynchronous code at all. asynchronous code not used dedicated threads for io operations, loops and main wait for io complete just after it begin. for real asynchronous code you need or use apc completion. if you work with single thread and wait in alertable state. or bind your file handle to iocp. use WMI extremally not efficient and here no sense. use config api for enumerate serial ports. not use hardcoded \"\\\\\\\\.\\\\COM%d\". many code simply not multithreaded safe like `is_open`. all program logic very complex and not clean, due wrong asynchronous io implementation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:29:23.723",
"Id": "418671",
"Score": "0",
"body": "@RbMm the way serial comms is handled in the code seems to be asynchronous according to this definition: https://stackify.com/when-to-use-asynchronous-programming/ How do you think this code is not asynchronous?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:35:46.047",
"Id": "418672",
"Score": "0",
"body": "@RbMm Are you suggesting to use iocp? Do you have an example for serial comms? Ideally a code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:41:45.900",
"Id": "418673",
"Score": "0",
"body": "if you begin asynchronous I/O and then just call `WaitForSingleObject` - this is already not asynchronous I/O by sense. by fact synchronous I/O - when your request sent to driver and then if pending returned - code is wait in kernel for complete. you simply move wait from kernel to user mode. if you use **dedicated** threads and **loops** - this is already not asynchronous I/O by sense, even if you formally use it. asynchronous I/O - this is when you begin it - and **not wait** after, and not do any loops. all program structure must be absolute another."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:46:06.540",
"Id": "418675",
"Score": "0",
"body": "asynchronous I/O - this is when you do i/o request and continue do another tasks. asynchronous I/O is event driven. you must have loop for got events - from user GUI, console, iocp. only this loop. why you say decide write to port ? you got some event - from user, another src, etc. and on this event - you write data to port. and after this - you return to code which wait for new event, instead wait write complete. after you open port - you call read and return to your tasks. not wait in any place. when read complete - you begin new read, and return. this is asynchronous I/O"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:56:35.227",
"Id": "418676",
"Score": "0",
"body": "from another side -- if you create dedicated thread for read, dedicated thread for write - what sense here have asynchronous io at all ? you can use synchronous io here (synchronous io == asynchronous io + wait until complete). code will be almost the same and more simply. another note that many conctruction not thread safe (yes, by fact they usually will be work, but it incorrect anyway), use wmi - always bad - this is not for c/c++, for high level language. wmi this is only request to remote process enumerate comp ports in your case. but how remote process do this ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:56:51.953",
"Id": "418677",
"Score": "0",
"body": "instead this wmi request you can do this yourself"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T17:55:45.667",
"Id": "418716",
"Score": "0",
"body": "@RbMm I can't find the config api? How will I find? Also I want to get the friendly names, eg <brand and model> modem etc which WMI provides. Would this config api provide that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:08:10.333",
"Id": "418719",
"Score": "0",
"body": "use `CM_Get_Device_Interface_ListW` and `CM_Get_Device_Interface_List_SizeW` for get list of interfaces for `GUID_DEVINTERFACE_COMPORT`. query `CM_Get_Device_Interface_PropertyW` with `DEVPKEY_Device_InstanceId` for get device id, than `CM_Locate_DevNodeW` and finally you can query devnode for many properties - like `DEVPKEY_NAME`, etc. try understand - how wmi internal get this ?"
}
] | [
{
"body": "<p>Let us start from nit picking.</p>\n<ol>\n<li>I would say that makes sense to use modern C++ at least for the sake of using <code>enum class</code>.</li>\n<li>There is a wide general convention to start type names from a capital letter, adds to readability.</li>\n<li>Encapsulation: this code introduces several enums and structs at namespace level. I would make them public members of the main class.</li>\n<li>It seems that the class is not what I would expect from async. It pushes unlimited data on write queue; I would expect for an async class to have write implemented as a callback <code>on_write_ready</code> followed by write. May be you should consider changing the name? And I would definitely add limits on the queue size and some alarms when limits are exceeded.</li>\n<li>Enumerate_ports returns Windows-specific value mapped to <code>long</code> should return <code>bool</code> or some generic result applicable across platforms.</li>\n<li>The class implementation is Windows-specific and then there is pimpl. I would expect either platform-independent implementation with Windows-specific pimpl or Windows-specific implementation without pimpl.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T14:28:56.823",
"Id": "267631",
"ParentId": "215577",
"Score": "2"
}
},
{
"body": "<h1>Use of types</h1>\n<p>As zzz777 already mentioned, consider making <code>enum</code>s <code>enum class</code>es for extra type safety.</p>\n<p><code>struct datum</code> looks a lot like a simplified version of C++20's <a href=\"https://en.cppreference.com/w/cpp/container/span/span\" rel=\"nofollow noreferrer\"><code>std::span</code></a>. If you can already use C++20, consider just using <code>std::span</code> instead. Otherwise, I recommend copying the interface of <code>std::span</code> as far as you need it, so that in the future you can replace <code>datum</code> with <code>std::span</code> without having to modify any other code.</p>\n<p>Be consistent. The constructors of <code>async_serial</code> take an <code>int port</code> parameter, but <code>enumerate_ports()</code> stores the port number as an <code>uint32_t</code>.</p>\n<h1>Avoid returning values via output parameters</h1>\n<p>Prefer returning values using <code>return</code> than via a pointer or reference parameter. Let <code>enumerate_ports()</code> return the map directly. This way, the caller can do:</p>\n<pre><code>for (auto &[port, name]: async_serial::enumerate_ports()) {\n ...\n}\n</code></pre>\n<p>If you want to return an error code as well, there are several options:</p>\n<ul>\n<li>Return the error code via an optional parameter. This allows the caller to ignore any errors if they can't do anything useful with them anyway.</li>\n<li>Throw exceptions when there is an exceptional error, like failing to query the serial ports.</li>\n<li>Return a <code>struct</code> or some other type holding both the map and the error code. A future version of C++ might get a <code>std::expected</code> type to make this easy, and you can already use that using third party libraries like <a href=\"https://github.com/TartanLlama/expected\" rel=\"nofollow noreferrer\">this one</a>.</li>\n</ul>\n<h1>About your use of the Pimpl pattern</h1>\n<p>The Pimpl pattern is normally used to hide implementation details of a class, so that only the public interface and a single pointer to the implementation is left. However, your <code>pimpl_</code> variable points to a <code>struct serialimpl</code>, which only holds a single <code>HANDLE</code>. If you just want to avoid including <code><Windows.h></code> for the type <code>HANDLE</code>, then this is quite inefficient: <code>HANDLE</code> itself is a pointer, and now you are adding yet another pointer to it. Pointer indirection is quite inefficient on modern CPUs, so I would avoid this. If you want to avoid the <code>#include</code>, just write:</p>\n<pre><code>typedef void* HANDLE;\n</code></pre>\n<p>Note that it is legal to typedef something twice as long as the types match.</p>\n<h1>Avoid calling <code>new</code> and <code>delete</code> manually</h1>\n<p>If you do need to allocate memory yourself, and there isn't already an STL container that fits, then at least use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a>. This avoids you having to worry about deleting the memory. For example, you forgot to call <code>delete[] d.data_</code> in the case where <code>WriteFile()</code> returned immediately and had successfully written all data.</p>\n<h1>Callbacks and error handling</h1>\n<p>Suppose that the application needs to know when a given datum has been sent.\nThat means that for every datum being enqueued, there should always be exactly one callback. However, looking at your code I see that there are paths where multiple <code>on_error()</code> callbacks can be sent for a single datum.</p>\n<p>First, don't call <code>on_error()</code> for recoverable errors.\nSecond, make sure there's always one callback done after a datum has been completely used.\nFinally, it would help if there is some way for the callback function itself to know for which datum it was being called. Most asynchronous I/O solutions allow the caller to specify a <code>void</code> pointer they can freely choose themselves when they enqueue data, and have that pointer returned to them when the callback is called. For C++, instead of using a <code>void *</code>, consider passing a <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow noreferrer\"><code>std::function<void(bool)></code></a>, and call that instead of <code>on_read()</code>, <code>on_write()</code> or <code>on_error()</code>, with the parameter indicating success. This is how it could be used then:</p>\n<pre><code>utl::async_serial serial(...);\nserial.write("Hello, world!\\r\\n", 15, [](bool success) {\n std::cerr << (success ? "Success!\\n" : "Write failed.\\n");\n});\n</code></pre>\n<h1>Consider avoiding the need to copy data</h1>\n<p>Your <code>write()</code> function copies the data provided by the caller to its own buffer that is allocated on the heap. This takes a little bit of time and memory. It might be more efficient to let the caller manage the memory. Perhaps they already had it stored in a heap-allocated buffer of their own, or perhaps they just want to send a <code>static const</code> string. Consider just using the pointer provided by the caller directly, and let the caller take care of cleaning up memory if necessary in the callback it provided.</p>\n<h1>Avoid <code>yield()</code> and <code>sleep_for()</code></h1>\n<p>Your code should work correctly without introducing arbitrary delays. If you need those delays, that means there is a race condition, and your delay is just hiding it, and might still fail if you are unlucky enough. If you don't need them, then you just introduced unnecessary delays.</p>\n<p>If you want to avoid a thread that has nothing to do to use 100% CPU checking if a port is opened or a queue is no longer empty, then there are two solutions to that:</p>\n<ul>\n<li>Don't start the thread until there is actually something to do. I would only start the two threads when the port has been succesfully opened.</li>\n<li>Use <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable\" rel=\"nofollow noreferrer\">condition variables</a> to let a thread sleep until another thread notifies it that there is some work to do.</li>\n</ul>\n<h1>Missing <code>const</code></h1>\n<p><code>get_status_string()</code> can be made <code>const</code>, and it's better to make the parameter <code>data</code> for <code>on_read()</code> <code>const</code> as well, as it's bad form if the callback would start writing into <code>reader_thread_func()</code>'s <code>read_buffer</code>.</p>\n<h1>Unnecessary use of <code>inline</code></h1>\n<p>The function <code>get_status()</code> is marked <a href=\"https://en.cppreference.com/w/cpp/language/inline\" rel=\"nofollow noreferrer\"><code>inline</code></a>, but that doesn't do anything here since functions completely defined in the class definition are implicitly inline already.</p>\n<h1>Avoid using C functions where possible</h1>\n<p>While you might have to call Windows C API functions for the low-level serial port handling, restrict yourself to that, and avoid calling C functions like <code>snprintf()</code>, and instead use C++ functionality where possible.</p>\n<p>In <code>open()</code>, you can write:</p>\n<pre><code>auto portname = "\\\\\\\\.\\\\XCOM" + std::to_string(port_);\nhandle_ = CreateFileA(portname.c_str(), ...);\n</code></pre>\n<p>Instead of <code>mempcy()</code>, consider using <a href=\"https://en.cppreference.com/w/cpp/algorithm/copy\" rel=\"nofollow noreferrer\"><code>std::copy()</code></a>.</p>\n<p>Instead of use <code>malloc()</code> to create an array and <code>realloc()</code> to resize it, just use <code>std::vector</code>:</p>\n<pre><code>std::vector<IWbemClassObject*> wbem_objects(10);\nhr = wbem_enumerate_object->Next(WBEM_INFINITE, wbem_objects.size(), wbem_objects.data(), &numports);\n\nif (SUCCEEDED(hr)) {\n wbem_objects.resize(numports);\n // Note: call wbem_enumerate_object->Next() again if necessary!\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T19:39:05.750",
"Id": "268603",
"ParentId": "215577",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "268603",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T18:38:35.270",
"Id": "215577",
"Score": "15",
"Tags": [
"c++",
"io",
"windows",
"serial-port"
],
"Title": "Asynchronous serial port communications class in C++"
} | 215577 |
<p>I have tried to write a large string (~100-120 Kb of HTML) on an <code>md</code> file, and am pretty sure it's not the fastest method, even though it only has to iterate ~8000-10,000 times and few times per hour.</p>
<p>There is also a low (~1%-2%) probability that the target filename has an old name (<code>previousName</code>), not exactly matched with a new name (<code>newName</code>), because the data flows through an API.</p>
<h3>Key Script: Inside <code>For</code> Loop</h3>
<pre><code> $cn=strtolower(UpdateStocks::slugCompany($s["quote"]["companyName"])); // slug company
$hay=strtolower($arr["quote"]["primaryExchange"]); // exchange market
if(strpos($hay, 'nasdaq')===0){
$mk='nasdaq-us';
$nasdaq++;
}elseif(strpos($hay, 'nyse')===0 || strpos($hay, 'new york')===0){
$mk='nyse-us';
$nyse++;
}elseif(strpos($hay, 'cboe')===0){
$mk='cboe-us';
$cboe++;
}else{
$mk='market-us';
$others++;
}
$sc=str_replace(array(' '), array('-'), strtolower($s["quote"]["sector"])); // slug sector
$enc=UpdateStocks::getEnc($symb,$symb,$symb,self::START_POINT_URL_ENCRYPTION_APPEND, self::LENGTH_URL_ENCRYPTION_APPEND); // simple 4 length encryption output: e.g., 159a
$dir=__DIR__ . self::DIR_FRONT_SYMBOLS_MD_FILES; // symbols front directory
if(!is_dir($dir)){mkdir($dir, 0755,true);} // creates price targets directory if not exist
// symbol in url
$p1=sprintf('%s%s%s',self::SLASH,strtolower($symb),'-');
// company in url
$p2=sprintf('%s%s%s',self::SLASH,strtolower($cn),'-');
// duplication risk
if(strtolower($symb)===strtolower($cn)){
// duplicated name from one symbol
$previousNames=array_reverse(UpdateStocks::searchFilenames(glob($dir."/*"),$p2));
$lurl=$cn . '-' . $sc . '-' . $mk . '-' . $enc;
}else{
// duplicated name from one symbol
$previousNames=array_reverse(UpdateStocks::searchFilenames(glob($dir."/*"),$p1));
$lurl=strtolower($symb) . '-' . $cn . '-' . $sc . '-' . $mk . '-' . $enc;
}
// new md filename
$newName=$dir . self::SLASH . $lurl . self::EXTENSION_MD;
// Replace multiple dashes with single dash: "aa-alcoa-basic-materials-nyse-us-159a"
$newName = preg_replace('/-{2,}/', '-', $newName);
// if file not exist: generate file
if($previousNames==null){
$fh=fopen($newName, 'wb');
fwrite($fh, '');
fclose($fh);
}else{
// if file not exist:
foreach($previousNames as $k=>$previousName){
if($k==0){
// safety: if previous filename not exactly equal to new filename
rename($previousName, $newName);
}else{
// in case multiple files found: unlink
unlink($previousName);
}
}
}
// This method is not review required now.
$mdFileContent=UpdateStocks::getBaseHTML($s,$l,$z); // gets HTML
if(file_exists($newName)){
if(is_writable($newName)){
file_put_contents($newName,$mdFileContent);
echo $symb. " " . self::NEW_LINE;
}else{
echo $symb . " symbol file in front directory is not writable in " . __METHOD__ . " " . self::NEW_LINE;
}
}else{
echo $symb . " file not found in " . __METHOD__ . " " . self::NEW_LINE;
}
}
</code></pre>
<h3>searchFilenames</h3>
<pre><code>/**
*
* @return an array with values of paths of all front md files stored
*/
public static function searchFilenames($array,$re){
$arr= array();
foreach($array as $k=>$str){
$pos=strpos($str, $re);
if($pos!==false){
array_push($arr, $str);
}
}
return $arr;
}
</code></pre>
<h3><code>var_dump($hay)</code></h3>
<pre><code>string(20) "nasdaq global"
string(23) "new york stock exchange"
string(20) "nasdaq global market"
string(20) "nasdaq global select"
string(23) "new york stock exchange"
string(23) "nyse arca"
string(23) "new york stock exchange"
string(23) "nyse"
string(20) "nasdaq"
string(20) "nasdaq global select"
string(23) "new york stock exchange"
string(20) "nasdaq global select"
string(23) "new york stock exchange"
string(23) "cboe"
string(23) "new york stock exchange"
string(20) "nasdaq global select"
string(20) "nasdaq global select"
string(23) "new york stock exchange"
string(23) "new york stock exchange"
...
</code></pre>
<h3>>5% Probability of <code>var_dump($lurl)</code></h3>
<h3>For <code>strtolower($symb)===strtolower($cn)</code></h3>
<pre><code>string(27) "aac-healthcare-nyse-us-e92a"
string(35) "aaon-basic-materials-nasdaq-us-238e"
string(28) "abb-industrials-nyse-us-a407"
string(38) "acnb-financial-services-nasdaq-us-19fa"
</code></pre>
<h3><95% Probability of <code>var_dump($lurl)</code></h3>
<h3>For not <code>strtolower($symb)===strtolower($cn)</code></h3>
<pre><code>string(50) "aadr-advisorshares-dorsey-wright-adr--nyse-us-d842"
string(39) "aal-airlines-industrials-nasdaq-us-29eb"
string(68) "aamc-altisource-asset-management-com-financial-services-nyse-us-b46a"
string(47) "aame-atlantic-financial-services-nasdaq-us-8944"
string(35) "aan-aarons-industrials-nyse-us-d00e"
string(54) "aaoi-applied-optoelectronics-technology-nasdaq-us-1dee"
string(56) "aap-advance-auto-parts-wi-consumer-cyclical-nyse-us-1f60"
string(36) "aapl-apple-technology-nasdaq-us-8f4c"
string(35) "aat-assets-real-estate-nyse-us-3598"
string(49) "aau-almaden-minerals-basic-materials-nyse-us-1c57"
string(51) "aaww-atlas-air-worldwide-industrials-nasdaq-us-69f3"
string(59) "aaxj-ishares-msci-all-country-asia-ex-japan--nasdaq-us-c6c4"
string(47) "aaxn-axon-enterprise-industrials-nasdaq-us-0eef"
string(58) "ab-alliancebernstein-units-financial-services-nyse-us-deb1"
</code></pre>
<h3><code>$symb</code>:</h3>
<p>Is a uppercase string, stands for a "symbol" of an equity, sometimes with dashes.</p>
<pre><code>"AADR"
"AAL"
"AAMC"
"AAME"
"AAN"
"AAOI"
"AAP"
"AAPL"
"AAT"
"AAU"
"AAWW"
"AAXJ"
"AAXN"
"AB"
"GS-A"
"GS-B"
"GS-C"
</code></pre>
<p>Would you be so kind and help me to modify it with a faster/simpler script?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T19:27:26.860",
"Id": "417045",
"Score": "1",
"body": "You could do `substr($hey, 0,2)` once and then check the first two letters instead of multiple `strpos`. Maybe, but I have no idea what `$hey` looks like :) - but than you could switch on that and get rid of the multiple function calls. I don't think it will be much faster, but with enough iterations, who knows, and it may look a bit cleaner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T23:44:28.387",
"Id": "417188",
"Score": "1",
"body": "@Emma I have advice to give, but I don't know what `$symb` is / is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T00:01:13.367",
"Id": "417191",
"Score": "1",
"body": "Do not change your posted question here. Too late now. You'll suffer some wrath if you do. I've got some good stuff to show you on this one. (I already spent a fair amount of time on this one this morning.) What is `$symb`? (If you \"ping\" me on pages where I have not been active, I will not be alerted.)"
}
] | [
{
"body": "<p>This is what I meant in the comments</p>\n\n<blockquote>\n <p>You could do <code>substr($hey,0,2)</code> once and then check the first two letters instead of multiple <code>strpos</code>. Maybe, but I have no idea what $hey looks like :) - but than you could <code>switch</code> on that and get rid of the multiple function calls. I don't think it will be much faster, but with enough iterations, who knows, and it may look a bit cleaner.</p>\n</blockquote>\n\n<pre><code> switch(substr($hay,0,2)){\n case 'na': //nasdaq\n $mk='nasdaq-us';\n $nasdaq++\n break;\n case 'ny': //nyse\n case 'ne': //new york\n $mk='nyse-us';\n $nyse++; \n break;\n case 'cb': //cboe\n $mk='cboe-us';\n $cboe++;\n break;\n default:\n $mk='market-us';\n $others++;\n break;\n }\n</code></pre>\n\n<p>This way your doing 1 function call instead of up to 4.</p>\n\n<p>It looks like your calling <code>strtolower</code> more than 3 times on <code>$cn</code></p>\n\n<pre><code> $cn=strtolower(UpdateStocks::slugCompany($s[\"quote\"][\"companyName\"])); // s\n //...\n $p2=sprintf('%s%s%s',self::SLASH,strtolower($cn),'-');\n //...\n if(strtolower($symb)===strtolower($cn)){\n //------------------ \n $p1=sprintf('%s%s%s',self::SLASH,strtolower($symb),'-');\n\n if(strtolower($symb)===strtolower($cn)){\n</code></pre>\n\n<p>And so forth.</p>\n\n<p>There may be other duplicate calls like this.</p>\n\n<p>Your <code>sprintf</code> seem point less.</p>\n\n<pre><code> // symbol in url\n$p1=sprintf('%s%s%s',self::SLASH,strtolower($symb),'-');\n// company in url\n$p2=sprintf('%s%s%s',self::SLASH,strtolower($cn),'-');\n\n //you could just do this for example\n$p1=self::SLASH.$symb.'-';\n</code></pre>\n\n<p>This whole chunk is suspect:</p>\n\n<pre><code> // symbol in url\n $p1=sprintf('%s%s%s',self::SLASH,strtolower($symb),'-');\n // company in url\n $p2=sprintf('%s%s%s',self::SLASH,strtolower($cn),'-');\n\n // duplication risk\n if(strtolower($symb)===strtolower($cn)){\n // duplicated name from one symbol\n $previousNames=array_reverse(UpdateStocks::searchFilenames(glob($dir.\"/*\"),$p2));\n $lurl=$cn . '-' . $sc . '-' . $mk . '-' . $enc;\n }else{\n // duplicated name from one symbol\n $previousNames=array_reverse(UpdateStocks::searchFilenames(glob($dir.\"/*\"),$p1));\n $lurl=strtolower($symb) . '-' . $cn . '-' . $sc . '-' . $mk . '-' . $enc; \n }\n</code></pre>\n\n<p>For example the only difference is this:</p>\n\n<pre><code>$previousNames=array_reverse(UpdateStocks::searchFilenames(glob($dir.\"/*\"),$p2));\n$previousNames=array_reverse(UpdateStocks::searchFilenames(glob($dir.\"/*\"),$p1));\n //and\n$lurl=$cn . '-' . $sc . '-' . $mk . '-' . $enc;\n$lurl=$symb . '-' . $cn . '-' . $sc . '-' . $mk . '-' . $enc; \n</code></pre>\n\n<p>So if you could change the last argument and prepend <code>$symb</code>, you could maybe eliminate this condition. I have to think about it a bit... lol. But you see what I mean it could be more DRY (Don't repeat yourself). I don't know enough about the data to really say on this one. I was thinking something like this:</p>\n\n<pre><code> if($symb != $cn){\n $p = self::SLASH.$symb.'-';\n $lurl='';\n }else{\n $p = self::SLASH.$cn.'-';\n $lurl= $symb;\n }\n\n $previousNames=array_reverse(UpdateStocks::searchFilenames(glob($dir.\"/*\"),$p));\n $lurl .= \"$cn-$sc-$mk-$enc\";\n</code></pre>\n\n<p>But I am not sure if I got everything strait, lol. So make sure to test it. Kind of hard just working it out in my head. Still need a condition but it's a lot shorter and easier to read.</p>\n\n<p>For this one:</p>\n\n<p><strong>searchFilenames</strong></p>\n\n<pre><code>/**\n * \n * @return an array with values of paths of all front md files stored\n */\npublic static function searchFilenames($array,$re){\n $arr= array();\n foreach($array as $k=>$str){\n $pos=strpos($str, $re);\n if($pos!==false){\n array_push($arr, $str);\n }\n }\n return $arr;\n}\n</code></pre>\n\n<p>You can use <code>preg_grep</code>. For example:</p>\n\n<pre><code> public static function searchFilenames($array,$re){\n return preg_grep('/'.preg_quote($re,'/').'/i',$array);\n } \n //or array_filter\n public static function searchFilenames($array,$re){\n return array_filter($array,function($item)use($re){ return strpos($re)!==false;});\n } \n</code></pre>\n\n<p>Your just finding if <code>$re</code> is contained within each element of <code>$array</code>. <a href=\"http://php.net/manual/en/function.preg-grep.php\" rel=\"nofollow noreferrer\">preg_grep</a> — <code>Return array entries that match the pattern</code>. It's also case insensitive with the <code>i</code> flag. In any case I never use <code>array_push</code> as <code>$arr[]=$str</code> is much faster. It's even better if you can just modify the array, as this is a function it's like a copy anyway as it's not passed by reference.</p>\n\n<p>One thing I find useful is to take and add some example data values in to the code in comments. Then you can visualize what tranforms your doing and if your repeating yourself.</p>\n\n<p>One last thing this one <strong>scares</strong> me a bit:</p>\n\n<pre><code>foreach($previousNames as $k=>$previousName){\n if($k==0){\n // safety: if previous filename not exactly equal to new filename\n rename($previousName, $newName);\n }else{\n // in case multiple files found: unlink\n unlink($previousName);\n }\n}\n</code></pre>\n\n<p>Here your checking that <code>$k</code> or the array key is <code>0</code>, it's very easy to reset array keys when sorting or filtering. So be careful with that, I would think this to be a safer option.</p>\n\n<pre><code>foreach($previousNames as $k=>$previousName){\n if($previousName!=$newName){\n // safety: if previous filename not exactly equal to new filename\n rename($previousName, $newName);\n }else{\n // in case multiple files found: unlink\n unlink($previousName);\n }\n}\n</code></pre>\n\n<p>Not sure if that was a mistake, or maybe I just don't understand that part? It hard without being able to test what the value is. But it warranted mention, once the stuff is deleted its deleted.</p>\n\n<p>Hope it helps you, most of these are minor things, really.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T20:06:31.663",
"Id": "417053",
"Score": "2",
"body": "Well I usually go over my own code at least three times, once to make it work, once to make it readable and clean up, and once for performance and security. It's like a process like writing a paper."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T20:09:16.747",
"Id": "417054",
"Score": "1",
"body": "@Emma - is this part of your code? `UpdateStocks::searchFilenames` you could re-write that or write a another one so that it avoids the array reverse, for example. Any function calls you can avoid will make it faster and simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T20:29:52.570",
"Id": "417058",
"Score": "1",
"body": "Yea it's mostly small things, which are easy to get in there when your trying to get it to work. It's got to work first, then you can go look at the logic and flow of things. And see where you can reduce the complexity. That usually makes it easier to read, faster, and less error prone."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T20:43:16.263",
"Id": "417062",
"Score": "1",
"body": "I type A LOT of code, so I try to type as little as possible, lol."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T19:33:52.280",
"Id": "215579",
"ParentId": "215578",
"Score": "6"
}
},
{
"body": "<p>I am only discovering this question after attending to this associated question from the OP: <a href=\"https://stackoverflow.com/q/55203392/2943403\">Writing and Updating ~8K-10K Iterations of URLs Strings on a Text File (PHP, Performance, CRON)</a></p>\n\n<ol>\n<li><p>I go to great lengths to avoid the use of \"large-battery\" <code>if</code> blocks and <code>switch</code> blocks in my code because they are so verbose. You have some predictable/static exchange codes so you can craft a single lookup array at the start of your class and leverage that for all subsequent processes. Having a single lookup array in an easy-to-find location will make your code more manageable for you and other developers. Once you have your lookup array (I'll call it <code>const EXCHANGE_CODES</code>), you can initiate an array to store the running tally for each market code encountered (I'll call it <code>$exchange_counts</code>); this array should be declared one time before the loop is started. Inside the loop, you can use <code>strpos()</code> and <code>substr()</code> to extract the targeted substrings that you posted in your question. Then simply check if the substring exists as a key in <code>EXCHANGE_CODES</code>, declare the found associated value, and increment the respective exchange count.</p></li>\n<li><p>I see that you are using very few characters in your variable declarations. This requires you to write comments at the end of each line to remind you and other developers what data is held in the variable. This is needlessly inconvenient. Better practice would be to assign meaningful names to your variables.</p></li>\n<li><p>When preparing the sector slug value, you are passing single-element arrays to <code>str_replace()</code> this is unnecessary -- just pass as single strings.</p></li>\n<li><p>Use a single space after commas when writing function parameters, as well as on either side of all <code>=</code>.</p></li>\n<li><p>I don't know if <code>$s</code> and <code>$arr</code> are the same incoming array and it is a typo while posting or if they are separate incoming arrays. Either way, the variable names should be more informative. If your script is always accessing the <code>quote</code> subarray, then you might like to declare <code>$quote = $array['quote'];</code> early in your script to allow for the simpler use of <code>$quote</code>. This isn't a big deal, just something to consider.</p></li>\n<li><p>Changing your current working directory to the new directory will spare you needing to add the variable to the <code>glob()</code> parameter AND it will shorten the strings that are being filtered -- meaning less work for php.</p></li>\n<li><p>You can put <code>glob()</code>'s excellent filtering feature to good use and avoid calling your static method entirely.</p></li>\n</ol>\n\n<p>Finally, as I said in your SO question, you should try to consolidate and minimize total file writes if possible.</p>\n\n<p>Here's some untested code to reflect my advice:</p>\n\n<pre><code>// this can be declared with your other class constants (array declaration available from php5.6+):\nconst EXCHANGE_CODES = [\n \"nasdaq\" => \"nasdaq-us\",\n \"nyse\" => \"nyse-us\",\n \"new york\" => \"nyse-us\",\n \"cboe\" => \"cboe-us\"\n];\n\n// initialize assoc array of counts prior to your loop\n$exchange_counts = array_fill_keys(self::EXCHANGE_CODES + [\"others\"], 0);\n/* makes:\n * array (\n * 'nasdaq-us' => 0,\n * 'nyse-us' => 0,\n * 'cboe-us' => 0,\n * 'others' => 0,\n * )\n */\n\n// start actual processing\n$company_slug = strtolower(UpdateStocks::slugCompany($s[\"quote\"][\"companyName\"]));\n\n$exchange_market = strtolower($arr[\"quote\"][\"primaryExchange\"]);\n\n// lookup market_code using company_name truncated after first encountered space after 4th character\n$leading_text = substr($exchange_market, 0, strpos($exchange_market, ' ', 4));\n$market_code = $exchange_codes[$leading_text] ?? 'others'; // null coalescing operator from php7+)\n++$exchange_counts[$market_code];\n\n$sector_slug = str_replace(' ', '-', strtolower($s[\"quote\"][\"sector\"]));\n\n$random_string = UpdateStocks::getEnc($symb, $symb, $symb, self::START_POINT_URL_ENCRYPTION_APPEND, self::LENGTH_URL_ENCRYPTION_APPEND);\n\n$dir = __DIR__ . self::DIR_FRONT_SYMBOLS_MD_FILES; // symbols front directory\n\n$equity_symbol = strtolower($equity_symbol);\n$slug_start = $company_slug === $equity_symbol ? $company_slug : $equity_symbol;\n\nif (!is_dir($dir)) {\n mkdir($dir, 0755, true); // creates price targets directory if not exist (recursively)\n} else {\n chdir($dir); // change current working directory\n $preexisting_files = glob(\"{$slug_start}-*\"); // separate static method call is avoided entirely (not sure why you are reversing)\n // if you want to eradicate near duplicate files, okay, but tread carefully -- it's permanent.\n}\n\n$new_slug = $slug_start . '-' . $sector_slug . '-' . $market_code . '-' . $random_string;\n\n$new_md_filename = preg_replace('/-{2,}/', '-', $dir . self::SLASH . $new_slug . self::EXTENSION_MD);\n\nif (empty($preexisting_files)) {\n // I don't advise the iterated opening,writing an empty file,closing 10,000x\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T01:58:16.333",
"Id": "417203",
"Score": "1",
"body": "Just occurred to me that you will need to reset the current working directory to the scripts directory after each iteration so that `chdir()` works on the subsequent iterations. (or you can ignore the `chdir()` advice and just pad the strings with `$dir` as you perform your `glob()` and `unlink()` processes)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T05:29:07.497",
"Id": "417212",
"Score": "1",
"body": "On second thought, `$dir` probably takes care of that concern."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T00:36:25.717",
"Id": "215641",
"ParentId": "215578",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215579",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T19:19:18.657",
"Id": "215578",
"Score": "2",
"Tags": [
"performance",
"beginner",
"php",
"strings",
"file-system"
],
"Title": "Writing a ~100Kb HTML string over an MD file (number of iterations ~10K)"
} | 215578 |
<p>I need to generate list of all allowable test combination values of of <code>actor</code>, <code>action</code> and <code>subject</code></p>
<pre><code>{
'actor': ['man', 'woman', 'baby'],
'action': ['play', 'cry'],
'subject': ['mathematica', 'lingvo']
}
</code></pre>
<p>I get <code>itertools.produce</code> and apply restriction that <code>actor=man</code> can't coexist with <code>action</code> and <code>actor=baby</code> can't coexist with <code>subject</code></p>
<pre><code>import itertools
from pprint import pprint
data = {'actor': ['man', 'woman', 'baby'], 'action': ['play', 'cry'], 'subject': ['mathematica', 'lingvo']}
def set_keys(*x):
return tuple(zip(data.keys(), x))
def reduce(*x):
dict_x = dict(x)
if dict_x['actor'] == 'man':
del dict_x['action']
elif dict_x['actor'] == 'baby':
del dict_x['subject']
return tuple(dict_x.items())
def distict(*x):
return dict(x[0])
product = itertools.product(*data.values())
product_with_keys = itertools.starmap(set_keys, product)
print('product_with_keys')
# pprint(list(product_with_keys))
reduced_product_with_keys = itertools.starmap(reduce, product_with_keys)
print('reduced_product_with_keys')
# pprint(list(reduced_product_with_keys))
grouped = itertools.groupby(reduced_product_with_keys)
# pprint(dict(grouped))
distinct = itertools.starmap(distict, grouped)
pprint(list(distinct))
</code></pre>
<p>Here is a result that suits me:</p>
<pre><code>[{'actor': 'man', 'subject': 'mathematica'},
{'actor': 'man', 'subject': 'lingvo'},
{'actor': 'man', 'subject': 'mathematica'},
{'actor': 'man', 'subject': 'lingvo'},
{'action': 'play', 'actor': 'woman', 'subject': 'mathematica'},
{'action': 'play', 'actor': 'woman', 'subject': 'lingvo'},
{'action': 'cry', 'actor': 'woman', 'subject': 'mathematica'},
{'action': 'cry', 'actor': 'woman', 'subject': 'lingvo'},
{'action': 'play', 'actor': 'baby'},
{'action': 'cry', 'actor': 'baby'}]
</code></pre>
<p>I am not very happy with how solved the removal of identical records</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T21:56:24.583",
"Id": "417066",
"Score": "0",
"body": "In general, I would like to create a rules which item from one list can not coexist with another item from another list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T22:07:19.127",
"Id": "417068",
"Score": "5",
"body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T16:54:44.137",
"Id": "417134",
"Score": "0",
"body": "`keys, values = zip(*params.items())` is needlessly computing two lists. Instead you could use `keys = params.keys(); values = params.values()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-18T09:57:35.377",
"Id": "417243",
"Score": "0",
"body": "I provide my solution"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-16T21:35:33.943",
"Id": "215582",
"Score": "1",
"Tags": [
"python",
"combinatorics",
"iterator"
],
"Title": "itertools.produce reduced and filtered"
} | 215582 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.