body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I got some documents (size about <code>300o/doc</code>) that I'd like to insert in my ES index using the python lib, I got huge time difference between the code and using <code>curl</code> it's obvious that it's normal, but I'd like to know if time can be improved (compared to the ratio of time)</p>
<ol>
<li><p><code>curl</code> option takes about <strong>20sec</strong> to insert and whole time <strong>10sec</strong> (for printing ES result but after 20sec data is inserted)</p>
<pre><code>curl -H "Content-Type: application/json" -XPOST
"localhost:9200/contentindex/doc/_bulk?" --data-binary @superfile.bulk.json
</code></pre></li>
<li><p>With <code>python</code> option, I reached <strong>1min20</strong> as minimum, using the setting <code>10000/16/16</code> (<code>chunk/thread/queue</code>)</p>
<pre><code>import codecs
from collections import deque
from elasticsearch import Elasticsearch
from elasticsearch.helpers import parallel_bulk
es = Elasticsearch()
def insert_data(filename, indexname):
with codecs.open(filename, "r", encoding="utf-8", errors="ignore") as fic:
for line in fic:
json_line = {}
json_line["data1"] = "random_foo_bar1"
json_line["data2"] = "random_foo_bar2"
# more fields ...
yield {
"_index": indexname,
"_type": "doc",
"_source": json_line
}
if __name__ == '__main__':
pb = parallel_bulk(es, insert_data("superfile.bulk.json", "contentindex"),
chunk_size=10000, thread_count=16, queue_size=16)
deque(pb, maxlen=0)
</code></pre></li>
</ol>
<hr>
<p><em>Facts</em></p>
<ul>
<li>I got a machine with <em>2 processors xeon 8-core</em> and <em>64GB ram</em></li>
<li>I tried multiple values for each <code>[100-50000]/[2-24]/[2-24]</code></li>
</ul>
<p><em>Questions</em></p>
<ul>
<li><p>Can I still improve the time ? </p></li>
<li><p>If not, should I think of a way to write the data on a file and then use a process for <code>curl</code> command ? </p></li>
</ul>
<p>—————————</p>
<p>If I try only the parse part it takes 15sec :</p>
<pre><code>tm = time.time()
array = []
pb = insert_data("superfile.bulk.json", "contentindex")
for p in pb:
array.append(p)
print(time.time() - tm) # 15
pb = parallel_bulk(es, array, chunk_size=10000, thread_count=16, queue_size=16)
dequeue(pb, maxlen = 0)
print(time.time() - tm) # 90
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T20:41:51.833",
"Id": "214614",
"Score": "1",
"Tags": [
"python",
"performance",
"elasticsearch"
],
"Title": "Can parallel_bulk compete with curl command for insert in ES?"
} | 214614 |
<p>Is there a more optimized solution to solve the stated problem? </p>
<p>Given an array 'arr' of 'N' elements and a number 'M', find the least index 'z' at which the equation gets satisfied. [ ] is considered as floor().</p>
<p><a href="https://i.stack.imgur.com/bDdJJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bDdJJ.png" alt="enter image description here"></a></p>
<p><strong>Code:</strong></p>
<pre><code>counts=0
ans=0
while(ans==0):
s=0
for i in range(counts,len(arr)):
s+=int(arr[i]/(i+1-counts))
if(s>M):
break
if((i+1)==len(arr) and s<=M):
print(counts)
ans=1
counts+=1
</code></pre>
<p><strong>Explanation:</strong></p>
<ol>
<li><p>Check array from left to right. The first index that satisfies the condition is the answer. This is more optimized than considering from right to left.</p></li>
<li><p>If at any time during the calculation, 's' is deemed more than M, break the loop and consider the next. This is more optimized than calculating 's' completely.</p></li>
</ol>
<p><strong>Example:</strong></p>
<p><strong>INPUT:</strong></p>
<p>N=3 M=3</p>
<p>arr=[1 2 3]</p>
<p><strong>OUTPUT:</strong></p>
<p>0</p>
<p>This would give the answer 0 since the 0th index contains the first element to satisfy the given relation.</p>
<p>Thanks in advance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T21:21:35.657",
"Id": "415024",
"Score": "2",
"body": "This would be better as runnable code. Showing a definition of `arr` and `M`, and a corresponding answer would be ideal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T10:47:14.457",
"Id": "415055",
"Score": "2",
"body": "Are the numbers assumed to be *non-negative* integers? Otherwise you could not break the loop if an intermediate sum is larger than M. – Does this come from a programming competition? If yes: could you provide a link to the contest?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T17:23:35.490",
"Id": "415090",
"Score": "1",
"body": "Please, follow [PEP-8](https://www.python.org/dev/peps/pep-0008/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-02T05:27:53.490",
"Id": "437637",
"Score": "0",
"body": "(Was about to comment that you can skip checking indexes where `arr[counts-1]` is negative - would at least need a proof. (Would be easier if the denominators where 1, 2, 4, 2ⁱ.))"
}
] | [
{
"body": "<p>To start, let's fix the PEP8 style errors using any PEP8 checker:</p>\n\n<pre><code>counts = 0\nans = 0\nwhile(ans == 0):\n s = 0\n for i in range(counts, len(arr)):\n s += int(arr[i]/(i+1-counts))\n if(s > M):\n break\n if((i+1) == len(arr) and s <= M):\n print(counts)\n ans = 1\n counts += 1\n</code></pre>\n\n<hr>\n\n<p>The parentheses around the conditions are also not usual Python style:</p>\n\n<pre><code>counts = 0\nans = 0\nwhile ans == 0:\n s = 0\n for i in range(counts, len(arr)):\n s += int(arr[i]/(i+1-counts))\n if s > M:\n break\n if (i+1) == len(arr) and s <= M:\n print(counts)\n ans = 1\n counts += 1\n</code></pre>\n\n<hr>\n\n<p>The inner loop uses <code>break</code>; there's no reason that the outer loop can't also, and that would simplify things slightly:</p>\n\n<pre><code>counts = 0\nwhile True:\n s = 0\n for i in range(counts, len(arr)):\n s += int(arr[i]/(i+1-counts))\n if s > M:\n break\n if (i+1) == len(arr) and s <= M:\n print(counts)\n break\n counts += 1\n</code></pre>\n\n<hr>\n\n<p>When we get to the line</p>\n\n<pre><code> if (i+1) == len(arr) and s <= M:\n</code></pre>\n\n<p>the first part of the condition can only fail because we called <code>break</code> in the inner loop, and in that case the second part of the condition also fails, so we can simplify that line to</p>\n\n<pre><code> if s <= M:\n</code></pre>\n\n<hr>\n\n<p>Python has integer division: it's just that you need to use <code>//</code> instead of <code>/</code>. So</p>\n\n<pre><code> s += int(arr[i]/(i+1-counts))\n</code></pre>\n\n<p>can be changed to</p>\n\n<pre><code> s += arr[i] // (i+1-counts)\n</code></pre>\n\n<p>for readability.</p>\n\n<hr>\n\n<p>It would be more Pythonic to operate on a slice rather than a <code>range</code> of indices. I.e. instead of</p>\n\n<pre><code> for i in range(counts, len(arr)):\n s += arr[i] // (i+1-counts)\n</code></pre>\n\n<p>we would have</p>\n\n<pre><code> for i, z_i in enumerate(arr[counts:]):\n s += z_i // (i+1)\n</code></pre>\n\n<hr>\n\n<p>The outer loop, on the other hand, could perfectly well be a <code>range</code>: it starts at 0 and is incremented once each time round the loop.</p>\n\n<pre><code>for counts in range(len(arr)+1):\n</code></pre>\n\n<hr>\n\n<p>Finally, there's the question of names. <code>arr</code> isn't great, but in context it passes. <code>M</code> comes from the problem statement. <code>counts</code> is, in my opinion, not at all helpful. I would call it <code>offset</code>, <code>start</code>, or something similar. And <code>s</code> is really <code>partial_sum</code> or <code>weighted_sum</code>.</p>\n\n<p>This gives us tidied code:</p>\n\n<pre><code>for offset in range(len(arr)+1):\n partial_sum = 0\n for i, z_i in enumerate(arr[offset:]):\n partial_sum += z_i // (i+1)\n if partial_sum > M:\n break\n if partial_sum <= M:\n print(offset)\n break\n</code></pre>\n\n<hr>\n\n<p>As for speed: flooring discards information, so it's not easy to calculate the partial sum for a given offset any faster by using information from other offsets. Moreover, you can't use binary chop or some similar search because the partial sum is not monotonic in the offset: consider input array</p>\n\n<pre><code>[1000, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1000]\n</code></pre>\n\n<p>So I don't think there's much you can do to speed this up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-01T10:37:09.237",
"Id": "225336",
"ParentId": "214615",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T21:12:04.653",
"Id": "214615",
"Score": "4",
"Tags": [
"python",
"algorithm",
"python-3.x",
"mathematics"
],
"Title": "Faster algorithm to tailor given mathematical expression"
} | 214615 |
<p>I wrote code to (naively) perform automatic memoisation. I tried to write it in a functional programming style, and so did not make use of any global variables.</p>
<h2>My Code</h2>
<pre class="lang-py prettyprint-override"><code>def naive_memoise(caches):
def memoise(f):
nonlocal caches
def mem_f(n):
nonlocal caches, f
if f not in caches:
caches[f] = {}
if n not in caches[f]:
caches[f][n] = f(n)
return caches[f][n]
return mem_f
return memoise
</code></pre>
<h3>Sample Usage</h3>
<pre class="lang-py prettyprint-override"><code>def fib(n):
if n in [0, 1]:
return n
return fib(n - 2) + fib(n - 1)
mem = naive_memoise({})
fib = mem(fib)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T19:05:54.187",
"Id": "415108",
"Score": "0",
"body": "Is there any use case in which you would want to initialize the cache with something other than an empty dict?"
}
] | [
{
"body": "<p>This looks good to me and I have nothing important to add.</p>\n\n<ul>\n<li><p>the <code>nonlocal</code> are not required here</p></li>\n<li><p>in the code sample, you could use the <code>@decorator</code> syntax</p></li>\n<li><p>maybe you could write something more generic than just functions taking a single parameter.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T23:39:15.583",
"Id": "415032",
"Score": "0",
"body": "I could change the parameter of `mem_f` to `*lst` I guess so it could handle functions with multiple arguments. It would requires rewriting the functions that work with it though. Not sure I know a general way to do it without customising the functions to be memoised so they interface well with the memoisation closure."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T23:27:50.223",
"Id": "214620",
"ParentId": "214618",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214620",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T22:58:00.853",
"Id": "214618",
"Score": "1",
"Tags": [
"python",
"beginner",
"functional-programming",
"memoization"
],
"Title": "Naive Implementation of Automatic Memoisation"
} | 214618 |
<p>Path of Exile is a PC game where players can list their items for sale. The game has <a href="https://pathofexile.gamepedia.com/Public_stash_tab_API" rel="nofollow noreferrer">a public API</a> that serves JSON which contains all of these items. My application consumes that JSON and indexes the items in a way that is easily searchable.</p>
<p>Json.NET provides an easy, one-liner method of deserializing JSON to a C# model:</p>
<pre><code>var root = JsonConvert.DeserializeObject<RootObject>(json);
</code></pre>
<p>It was not as fast as I needed it to be. I replaced it with a deserializer that <em>is</em> fast enough, and that code is what I would like to have reviewed.</p>
<h2>Primary Concern</h2>
<p>All feedback is welcome, but what drove me to post is how repetitive the code is. <code>Utf8JsonReader</code> and <code>ReadOnlySpan</code> are ref structs, which means neither can be used as a type arguments. I could not figure out how to write DRY code with that restriction.</p>
<p>For example, the implementations of methods <code>ParseStash()</code>, <code>ParseItem()</code>, <code>ParseSocket()</code>, and <code>ParseProperty()</code> are nearly identical.</p>
<h2>Code</h2>
<p>If you prefer downloading and running it, here is a minimal project on GitHub:
<a href="https://github.com/d2erusher/JsonParserCodeReview" rel="nofollow noreferrer">https://github.com/d2erusher/JsonParserCodeReview</a></p>
<pre><code>public class FastJsonParserService : IJsonParserService
{
public RootObject Parse(string json)
{
ReadOnlySpan<byte> jsonUtf8 = Encoding.UTF8.GetBytes(json);
var reader = new Utf8JsonReader(jsonUtf8, true, default);
return ParseRootObject(ref reader);
}
private static RootObject ParseRootObject(ref Utf8JsonReader reader)
{
var root = new RootObject();
reader.Read();
while (reader.Read()
&& reader.TokenType != JsonTokenType.EndObject)
{
var rootPropertyName = reader.ValueSpan;
reader.Read();
ParseRootObjectProperty(ref reader, rootPropertyName, root);
}
return root;
}
private static void ParseRootObjectProperty(ref Utf8JsonReader reader, ReadOnlySpan<byte> propertyName, RootObject root)
{
if (propertyName.SequenceEqual(PropertyNameBytes.BytesNextChangeId))
{
root.NextChangeId = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesStashes))
{
root.Stashes = ParseStashArray(ref reader);
}
else
{
Skip(ref reader);
}
}
private static List<Stash> ParseStashArray(ref Utf8JsonReader reader)
{
var stashes = new List<Stash>();
while (reader.Read()
&& reader.TokenType != JsonTokenType.EndArray)
{
stashes.Add(ParseStash(ref reader));
}
return stashes;
}
private static Stash ParseStash(ref Utf8JsonReader reader)
{
var stash = new Stash();
while (reader.Read()
&& reader.TokenType != JsonTokenType.EndObject)
{
var stashPropertyName = reader.ValueSpan;
ParseStashProperty(ref reader, stashPropertyName, stash);
}
return stash;
}
private static void ParseStashProperty(ref Utf8JsonReader reader, ReadOnlySpan<byte> propertyName, Stash stash)
{
if (propertyName.SequenceEqual(PropertyNameBytes.BytesAccountName))
{
reader.Read();
if (reader.TokenType == JsonTokenType.String)
stash.AccountName = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesLastCharacterName))
{
reader.Read();
if (reader.TokenType == JsonTokenType.String)
stash.LastCharacterName = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesId))
{
reader.Read();
stash.Id = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesStash))
{
reader.Read();
if (reader.TokenType == JsonTokenType.String)
stash.Name = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesStashType))
{
reader.Read();
stash.StashType = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesItems))
{
stash.Items = ParseItemArray(ref reader);
}
else
{
Skip(ref reader);
}
}
private static List<Item> ParseItemArray(ref Utf8JsonReader reader)
{
reader.Read();
var results = new List<Item>();
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
results.Add(ParseItem(ref reader));
}
return results;
}
private static Item ParseItem(ref Utf8JsonReader reader)
{
var item = new Item();
while (reader.Read()
&& reader.TokenType != JsonTokenType.EndObject)
{
var itemPropertyName = reader.ValueSpan;
ParseItemProperty(ref reader, itemPropertyName, item);
}
return item;
}
private static void ParseItemProperty(ref Utf8JsonReader reader, ReadOnlySpan<byte> propertyName, Item item)
{
if (propertyName.SequenceEqual(PropertyNameBytes.BytesVerified))
{
reader.Read();
item.Verified = reader.GetBoolean();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesW))
{
reader.Read();
item.W = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesH))
{
reader.Read();
item.H = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesIlvl))
{
reader.Read();
item.Ilvl = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesTalismanTier))
{
reader.Read();
item.TalismanTier = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesCorrupted))
{
reader.Read();
item.Corrupted = reader.GetBoolean();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesDuplicated))
{
reader.Read();
item.Duplicated = reader.GetBoolean();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesStackSize))
{
reader.Read();
item.StackSize = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesMaxStackSize))
{
reader.Read();
item.MaxStackSize = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesIcon))
{
reader.Read();
item.Icon = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesArtFilename))
{
reader.Read();
item.ArtFilename = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesLeague))
{
reader.Read();
item.League = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesId))
{
reader.Read();
item.Id = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesSockets))
{
item.Sockets = ParseSocketArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesName))
{
reader.Read();
item.Name = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesSecDescrText))
{
reader.Read();
item.SecDescrText = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesDescrText))
{
reader.Read();
item.DescrText = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesIdentified))
{
reader.Read();
item.Identified = reader.GetBoolean();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesNote))
{
reader.Read();
item.Note = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesProperties))
{
item.Properties = ParsePropertyArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesAdditionalProperties))
{
item.AdditionalProperties = ParsePropertyArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesRequirements))
{
item.Requirements = ParsePropertyArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesNextLevelRequirements))
{
item.NextLevelRequirements = ParsePropertyArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesExplicitMods))
{
reader.Read();
item.ExplicitMods = ParseStringArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesImplicitMods))
{
reader.Read();
item.ImplicitMods = ParseStringArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesUtilityMods))
{
reader.Read();
item.UtilityMods = ParseStringArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesCraftedMods))
{
reader.Read();
item.CraftedMods = ParseStringArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesEnchantMods))
{
reader.Read();
item.EnchantMods = ParseStringArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesFlavourText))
{
reader.Read();
item.FlavourText = ParseStringArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesProphecyText))
{
reader.Read();
item.ProphecyText = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesFrameType))
{
reader.Read();
item.FrameType = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesCategory))
{
item.Category = ParseCategory(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesX))
{
reader.Read();
item.X = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesY))
{
reader.Read();
item.Y = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesInventoryId))
{
reader.Read();
item.InventoryId = reader.GetString();
}
else
{
Skip(ref reader);
}
}
private static List<Socket> ParseSocketArray(ref Utf8JsonReader reader)
{
reader.Read();
var results = new List<Socket>();
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
results.Add(ParseSocket(ref reader));
}
return results;
}
private static Socket ParseSocket(ref Utf8JsonReader reader)
{
var socket = new Socket();
while (reader.Read()
&& reader.TokenType != JsonTokenType.EndObject)
{
var propertyName = reader.ValueSpan;
ParseSocketProperty(ref reader, propertyName, socket);
}
return socket;
}
private static void ParseSocketProperty(ref Utf8JsonReader reader, ReadOnlySpan<byte> propertyName, Socket socket)
{
if (propertyName.SequenceEqual(PropertyNameBytes.BytesAttr))
{
reader.Read();
socket.Attr = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesGroup))
{
reader.Read();
socket.Group = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesSColour))
{
reader.Read();
socket.SColour = reader.GetString();
}
else
{
Skip(ref reader);
}
}
private static List<Property> ParsePropertyArray(ref Utf8JsonReader reader)
{
reader.Read();
var results = new List<Property>();
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
results.Add(ParseProperty(ref reader));
}
return results;
}
private static Property ParseProperty(ref Utf8JsonReader reader)
{
var property = new Property();
while (reader.Read()
&& reader.TokenType != JsonTokenType.EndObject)
{
var propertyName = reader.ValueSpan;
ParsePropertyProperty(ref reader, propertyName, property);
}
return property;
}
private static void ParsePropertyProperty(ref Utf8JsonReader reader, ReadOnlySpan<byte> propertyName, Property property)
{
if (propertyName.SequenceEqual(PropertyNameBytes.BytesDisplayMode))
{
reader.Read();
property.DisplayMode = reader.GetInt32();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesName))
{
reader.Read();
property.Name = reader.GetString();
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesValues))
{
property.Values = ParseStringArrayArray(ref reader);
}
else if (propertyName.SequenceEqual(PropertyNameBytes.BytesType))
{
reader.Read();
property.Type = reader.GetInt32();
}
else
{
Skip(ref reader);
}
}
private static List<List<string>> ParseStringArrayArray(ref Utf8JsonReader reader)
{
reader.Read();
var results = new List<List<string>>();
while (reader.Read()
&& reader.TokenType != JsonTokenType.EndArray)
{
results.Add(ParseStringArray(ref reader));
}
return results;
}
private static List<string> ParseStringArray(ref Utf8JsonReader reader)
{
var results = new List<string>();
reader.Read();
while (reader.TokenType != JsonTokenType.EndArray)
{
var result = reader.TokenType == JsonTokenType.String
? reader.GetString()
: reader.GetInt32().ToString();
results.Add(result);
reader.Read();
}
return results;
}
private static Category ParseCategory(ref Utf8JsonReader reader)
{
var category = new Category();
while (reader.Read()
&& reader.TokenType != JsonTokenType.EndObject)
{
reader.Read();
category.Name = reader.GetString();
reader.Read();
category.Values = ParseStringArray(ref reader);
}
return category;
}
private static void Skip(ref Utf8JsonReader reader)
{
if (reader.TokenType == JsonTokenType.PropertyName)
{
reader.Read();
}
if (reader.TokenType == JsonTokenType.StartObject
|| reader.TokenType == JsonTokenType.StartArray)
{
var depth = reader.CurrentDepth;
while (reader.Read() && depth <= reader.CurrentDepth) { }
}
}
}
</code></pre>
<h2>Sample Input</h2>
<p>I use this 6 KB sample file for correctness testing. Actual payloads are as large as 4 MB decompressed.</p>
<pre><code>{
"next_change_id": "2653-4457-4108-4817-1510",
"stashes": [
{
"id": "6e744b0f76179835e1f681ce81c513ea190cb021b34eaacafe4c3d4f6990395f",
"public": true,
"accountName": "5a4oK",
"lastCharacterName": "Please_remove_volotile",
"stash": "What i need",
"stashType": "PremiumStash",
"items": [
{
"verified": false,
"w": 2,
"h": 4,
"ilvl": 71,
"icon": "http://web.poecdn.com/image/Art/2DItems/Weapons/TwoHandWeapons/Bows/SarkhamsReach.png?scale=1&scaleIndex=0&w=2&h=4&v=f333c2e4005ee20a84270731baa5fa6a3",
"league": "Hardcore",
"id": "176b5e6f7af0a5bb4b48d7fdafa47501a179f4ea095815a58c82c4b5244b3cdb",
"sockets": [
{
"group": 0,
"attr": "D",
"sColour": "G"
}
],
"name": "<<set:MS>><<set:M>><<set:S>>Roth's Reach",
"typeLine": "Recurve Bow",
"identified": true,
"note": "~price 10 exa",
"properties": [
{
"name": "Bow",
"values": [],
"displayMode": 0
},
{
"name": "Attacks per Second",
"values": [
[
"1.31",
1
]
],
"displayMode": 0,
"type": 13
}
],
"requirements": [
{
"name": "Level",
"values": [
[
"18",
0
]
],
"displayMode": 0
},
{
"name": "Dex",
"values": [
[
"65",
0
]
],
"displayMode": 1
}
],
"explicitMods": [
"68% increased Physical Damage",
"5% increased Attack Speed",
"Skills Chain +1 times",
"30% increased Projectile Speed",
"34% increased Elemental Damage with Attack Skills"
],
"flavourText": [
"\"Exiled to the sea; what a joke. \r",
"I'm more free than I've ever been.\"\r",
"- Captain Weylam \"Rot-tooth\" Roth of the Black Crest"
],
"frameType": 3,
"category": {
"weapons": [
"bow"
]
},
"x": 10,
"y": 0,
"inventoryId": "Stash1",
"socketedItems": []
},
{
"verified": false,
"w": 1,
"h": 1,
"ilvl": 0,
"icon": "http://web.poecdn.com/image/Art/2DItems/Gems/LeapSlam.png?scale=1&scaleIndex=0&w=1&h=1&v=73d0b5f9f1c52f0e0e87f74a80a549ab3",
"support": false,
"league": "Hardcore",
"id": "8d84024bd2f99bd467b671e6915bc999f6e26f512c7f7034f54ff182781198e6",
"name": "",
"typeLine": "Leap Slam",
"identified": true,
"properties": [
{
"name": "Attack, AoE, Movement, Melee",
"values": [],
"displayMode": 0
},
{
"name": "Level",
"values": [
[
"1",
0
]
],
"displayMode": 0,
"type": 5
}
],
"additionalProperties": [
{
"name": "Experience",
"values": [
[
"9569/9569",
0
]
],
"displayMode": 2,
"progress": 1
}
],
"requirements": [
{
"name": "Level",
"values": [
[
"10",
0
]
],
"displayMode": 0
},
{
"name": "Str",
"values": [
[
"29",
0
]
],
"displayMode": 1
}
],
"nextLevelRequirements": [
{
"name": "Level",
"values": [
[
"13",
0
]
],
"displayMode": 0
},
{
"name": "Str",
"values": [
[
"35",
0
]
],
"displayMode": 1
}
],
"secDescrText": "Jump into the air, damaging enemies (and knocking back some) with your main hand where you land. Enemies you would land on are pushed out of the way. Requires an axe, mace, sword or staff. Cannot be supported by Multistrike.",
"explicitMods": [
"20% chance to Knock Enemies Back on hit"
],
"descrText": "Place into an item socket of the right colour to gain this skill. Right click to remove from a socket.",
"frameType": 4,
"category": {
"gems": []
},
"x": 0,
"y": 1,
"inventoryId": "Stash2"
}
]
}
]
}
</code></pre>
<h2>Sample Output</h2>
<p>The output is a populated C# model of type <code>RootObject</code>. Below is a unit test that uses the sample input above and verifies that the model was populated correctly.</p>
<pre><code> [TestFixture]
public class JsonParserServiceTests
{
[Test]
public void TestParse_ProducesCorrectValues()
{
// Arrange
var json = File.ReadAllText("TestFiles\\small.json");
var sut = new FastJsonParserService();
// Act
var actual = sut.Parse(json);
// Assert
Assert.AreEqual("2653-4457-4108-4817-1510", actual.NextChangeId);
Assert.AreEqual(1, actual.Stashes.Count);
AssertStash0(actual.Stashes[0]);
}
private static void AssertStash0(Stash stash)
{
Assert.AreEqual("6e744b0f76179835e1f681ce81c513ea190cb021b34eaacafe4c3d4f6990395f", stash.Id);
Assert.AreEqual("5a4oK", stash.AccountName);
Assert.AreEqual("Please_remove_volotile", stash.LastCharacterName);
Assert.AreEqual("What i need", stash.Name);
Assert.AreEqual("PremiumStash", stash.StashType);
Assert.AreEqual(2, stash.Items.Count);
AssertStash0Item0(stash.Items[0]);
}
private static void AssertStash0Item0(Item item)
{
Assert.AreEqual(false, item.Verified);
Assert.AreEqual(2, item.W);
Assert.AreEqual(4, item.H);
Assert.AreEqual(71, item.Ilvl);
Assert.AreEqual("http://web.poecdn.com/image/Art/2DItems/Weapons/TwoHandWeapons/Bows/SarkhamsReach.png?scale=1&scaleIndex=0&w=2&h=4&v=f333c2e4005ee20a84270731baa5fa6a3", item.Icon);
Assert.AreEqual("Hardcore", item.League);
Assert.AreEqual("176b5e6f7af0a5bb4b48d7fdafa47501a179f4ea095815a58c82c4b5244b3cdb", item.Id);
Assert.AreEqual(1, item.Sockets.Count);
AssertStash0Item0Sockets0(item.Sockets[0]);
Assert.AreEqual("<<set:MS>><<set:M>><<set:S>>Roth's Reach", item.Name);
Assert.AreEqual(true, item.Identified);
Assert.AreEqual("~price 10 exa", item.Note);
Assert.AreEqual(2, item.Properties.Count);
AssertStash0Item0Properties0(item.Properties.FirstOrDefault(p => p.Name.Equals("Bow")));
AssertStash0Item0Properties1(item.Properties.FirstOrDefault(p => p.Name.Equals("Attacks per Second")));
Assert.AreEqual(2, item.Requirements.Count);
AssertStash0Item0Requirements0(item.Requirements[0]);
Assert.AreEqual(5, item.ExplicitMods.Count);
Assert.NotNull(item.ExplicitMods.FirstOrDefault(e => e.Equals("68% increased Physical Damage")));
Assert.AreEqual(3, item.FlavourText.Count);
Assert.NotNull(item.FlavourText.FirstOrDefault(e => e.Equals("\"Exiled to the sea; what a joke. \r")));
Assert.AreEqual(3, item.FrameType);
AssertStash0Item0Category(item.Category);
Assert.AreEqual(10, item.X);
Assert.AreEqual(0, item.Y);
Assert.AreEqual("Stash1", item.InventoryId);
}
private static void AssertStash0Item0Sockets0(Socket socket)
{
Assert.AreEqual(0, socket.Group);
Assert.AreEqual("D", socket.Attr);
Assert.AreEqual("G", socket.SColour);
}
private static void AssertStash0Item0Properties0(Property property)
{
CollectionAssert.IsEmpty(property.Values);
Assert.AreEqual(0, property.DisplayMode);
}
private static void AssertStash0Item0Properties1(Property property)
{
Assert.AreEqual("1.31", property.Values[0][0]);
Assert.AreEqual("1", property.Values[0][1]);
Assert.AreEqual(0, property.DisplayMode);
}
private static void AssertStash0Item0Requirements0(Property requirement)
{
Assert.AreEqual("Level", requirement.Name);
Assert.AreEqual(1, requirement.Values.Count);
Assert.AreEqual(2, requirement.Values[0].Count);
Assert.AreEqual("18", requirement.Values[0][0]);
Assert.AreEqual("0", requirement.Values[0][1]);
Assert.AreEqual(0, requirement.DisplayMode);
}
private static void AssertStash0Item0Category((string, List<string>) category)
{
Assert.AreEqual("weapons", category.Item1);
Assert.AreEqual(1, category.Item2.Count);
Assert.AreEqual("bow", category.Item2[0]);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T13:42:21.283",
"Id": "415065",
"Score": "0",
"body": "Just wondering, why not compare your implementation to Json.NET in your tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T19:49:23.667",
"Id": "415114",
"Score": "0",
"body": "@BradM The Json.NET method requires decorating the fields on the models with `[JsonAttribute(\"some_field\")]` attributes. I would have to maintain that even though I'm not using it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T15:15:22.880",
"Id": "415198",
"Score": "0",
"body": "Could you tell me which package I need to install to get the `Utf8JsonReader` - or maybe you have this project on GitHub? You are using the prerelease version of .net-core 3, aren't you? And it's a part of it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T05:29:56.120",
"Id": "415256",
"Score": "1",
"body": "@t3chb0t Sorry it took me so long to respond due to work. I made a minimal project and pushed it to GitHub: https://github.com/d2erusher/JsonParserCodeReview. It has everything you see in the question, plus some models and an additional test. You're right - I am using the pre-release version of .NET Core 3.0, and `Utf8JsonReader` does come with it. I think you need Visual Studio 2019 Preview in order to work with it, but I could be wrong about that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T05:42:45.823",
"Id": "415259",
"Score": "2",
"body": "This is embarrassing. I had already made some progress towards making the code more DRY, and accidentally pushed the improved code to GitHub. I wasn't trying to hide my progress, but I wanted to give the community a chance to post answers before I posted a self-answer. I updated the GitHub repo to have the same version of the code as the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T06:50:43.857",
"Id": "415263",
"Score": "0",
"body": "No need to be sorry - we all have other things to do too ;-] As long as there aren't any answers yet, you can update your question anytime. Thanks for the GitHub link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T09:05:36.453",
"Id": "415281",
"Score": "1",
"body": "You say that you tried the `JsonConvert.DeserializeObject` API, but have you also tried the one that supports streams: `JsonSerializer.Deserialize` - you can pass it a `JsonReader`. This should be significantly faster then loading a file as a string first and then parsing it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T03:25:01.823",
"Id": "415439",
"Score": "1",
"body": "@t3chb0t I hadn't tried it before, but now I have. The benchmark was a 4 MB file, parsed 100 times (with no reusing the file text in between). `JsonSerializer.Deserialize` took 122ms per iteration, `JsonSerializer.DeserializeObject` 131 ms per iteration, and `Utf8JsonReader` 116 ms per iteration. Looks like you're right. The benchmarking code is on the GitHub linked in the question in JsonParserPerformanceBenchmark.cs."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T03:06:43.987",
"Id": "214625",
"Score": "4",
"Tags": [
"c#",
".net",
"json"
],
"Title": "Deserializing JSON with Utf8JsonReader"
} | 214625 |
<p>I have a class called <code>HtmlFile</code> which has a method called <code>generate</code>. This method is responsible for generating an html file from handlebars template and data object provided in the <code>HtmlFile</code> class constructor.</p>
<p>I am confused on what code design should I use for this use case and what variable names to choose.</p>
<pre><code>class HtmlFile {
public file: any = null;
private template: any = null;
private data: any = null;
constructor(templatePath: string, params: any) {
this.template = path.resolve(templatePath);
this.data = params;
}
public async generate() {
try {
const error = this._validate();
if (error) {
throw error;
}
const fileContent = fs.readFileSync(this.template, "utf8");
const html = handlebars.compile(fileContent)(this.data);
return html;
} catch (e) {
throw e;
}
}
private _validate() {
let errStr: any = null;
if (typeof this.template !== "string") {
errStr = `expected template path to be a string, instead got
${typeof this.template}`;
}
if (typeof this.data !== "object") {
errStr = `expected data to be an object, instead got ${typeof
this.data}`;
}
return errStr;
}
}
</code></pre>
<p>And I am using this class in the following manner:</p>
<pre><code>let htmlFile = new HtmlFile("./src/templates/sample.hbs", invoiceOptions);
const html: any = await htmlFile.generate();
return html;
</code></pre>
<p>I also want suggestions on what variable names I should use in place of <code>htmlFile</code> and <code>html</code>.</p>
| [] | [
{
"body": "<p>First things first - syntax:</p>\n\n<p>Why is generate an async function? You should change the way the files are read. Please read the answers to this question: <a href=\"https://stackoverflow.com/questions/46867517/how-to-read-file-with-async-await-properly\">https://stackoverflow.com/questions/46867517/how-to-read-file-with-async-await-properly</a></p>\n\n<p>Logic:</p>\n\n<p>The <code>_validate</code> function checks integrity of your object. All the data it needs is available in the constructor and this is where this function should be called. Never defer throwing an exception if you cannot avoid it.</p>\n\n<p>Structure:</p>\n\n<p>As for what design to use - your class is doing multiple things at the same time. Reading a template file from disk is one thing - and it requires handling an asynchronous operation. Then there is template compilation - which in case of HBS is not asynchronous and there is rendering - not asynchronous again. I'd recommend to restructure the solution a bit:</p>\n\n<ul>\n<li>Use one class to read a file and return you a compiled template object. In case you needed to reuse your template objects - do not read from disk on every template call.</li>\n<li>The returned class (let's call this one <code>HandlebarsTemplate</code>) should take a string as its constructor input and attempt compiling it as HBS. If the template was not correct - you get an exception thrown on object creation.</li>\n<li>Note that <code>HandlebarsTemplate</code> could be reused for templates coming from sources other than files e.g. database or just a string literal in the code.</li>\n<li>The object <code>HandlebarsTemplate</code> should expose a method called <code>generate(data)</code>. This method should attempt rendering <code>data</code> the with the compiled HBS template.</li>\n<li>This way you get reusable template objects</li>\n</ul>\n\n<p>This would be up to you if you want to read the template each time or store a compiled instance in memory. Both approaches have their pros and cons.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-02T20:22:43.070",
"Id": "231751",
"ParentId": "214627",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T05:33:10.593",
"Id": "214627",
"Score": "1",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "Generate HTML file from Handlebars template and data object"
} | 214627 |
<p>I'm a beginner coder, doing it solely for fun, having started coding about two months ago with Python. I have a working piece of code for calculating area and volume of different geometric shapes, using user input of "radius".</p>
<p>As I have said, the code works but I would like to know how I can improve it to be shorter, faster and more efficient. Essentially, I think it would be instructive to compare my rank amateur code to the code that an experienced software developer would produce to accomplish the same result.</p>
<pre><code>from tkinter import *
from tkinter import ttk
import sys
root = Tk()
pi = 3.141
# Option Box
var = StringVar(root)
var.set("Functions")
lbl_title = Label(root, text = "GEOMETRIC SHAPES AND VOLUMES")
lbl_title.grid(row = 0, column = 0, columnspan = 2, padx =5, pady = 10)
lbl_choose = Label(root, text = "Choose a function and hit OK:")
lbl_choose.grid(row = 1, column = 0, padx = 5, pady = 0, sticky = W)
box = ttk.OptionMenu(root, var, "Circle Circumference", "Circle Area", "Sphere Volume",
"Rectangle Area", "Rectangle Prism Volume", "Cone Volume")
box.grid(row = 2, column = 0, padx=5, pady=5, sticky= W)
# Separator
line1 = ttk.Separator(root, orient = HORIZONTAL)
line1.grid(row = 4, column = 0, columnspan = 3, sticky = EW) # Note separator sticky EW!
#txt_data_in = Text(root, height = 1, width = 30, bg = "Light Grey")
#txt_data_in.grid(row = 5, column = 0, padx = 5, sticky = W)
# Functions
def circ_circumf(r):
print("\nThe circumference of the circle is: " + str(2*pi*r) + " units.")
def circ_area(r):
print("\nThe area of the circle is: " + str(pi*r**2) + " units.")
def sphere_vol(r):
print("\nThe volume of the sphere is: " +str(4/3 * pi * r**3) + " units.")
def rect_area(l,w):
pass
def rect_prism_vol(l, w, h):
pass
def cone_vol(r, h):
pass
def exit():
sys.exit()
# Main Function
def main():
if var.get() == "Circle Circumference":
r = int(input("Enter the radius of the circle in the units of your choice: "))
circ_circumf(r)
elif var.get() == "Circle Area":
r = int(input("Enter the radius of the circle in the units of your choice: "))
circ_area(r)
elif var.get() == "Sphere Volume":
r = int(input("Enter the radius of the sphere in the units of your choice: "))
sphere_vol(r)
# Function Button
butt1 = ttk.Button(root, text = "OK", command = main)
butt1.grid(row = 2, column = 1, padx = 5, sticky = W)
# Exit Button
butt2 = ttk.Button(root, text = "Exit", command = exit)
butt2.grid(row = 6, column = 0, padx = 5, pady = 5, sticky = W)
root.mainloop()
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>I think it would be instructive to compare my rank amateur code to the code that an experienced software developer would produce to accomplish the same result.</p>\n</blockquote>\n\n<p>To me, the most obvious differences between experienced and novice programmers are:</p>\n\n<ol>\n<li>consideration of edge cases</li>\n<li>organization of data in a manner that lets the data drive the program's flow</li>\n<li>broadness of their working definition of the word <strong>data</strong></li>\n</ol>\n\n<p>In that light, here are things I'd do differently from what you have done.</p>\n\n<h2>Make the most of the data you've got</h2>\n\n<p>You're silently truncating the user's input with <code>int()</code>. This is bad! Mangling user data is necessary sometimes and to be avoided otherwise. Especially here, where the change will affect the output in surprising and subtle ways.</p>\n\n<p>You're displaying results with maximum \"precision\" but basing them on a value of <code>pi</code> that has only four significant figures. This is misleading. Define <code>pi</code> with more digits, and shorten the result so that it shows the actual precision.</p>\n\n<h2>Separate content from presentation</h2>\n\n<p>A common pattern arises when you create something that's useful to someone (yourself, usually), later it becomes useful to other people, and those people need the output in a different format. Not only do you have to change the code, but it's been months since you looked at it! You won't remember how everything works. Make it easy to affect how output is displayed. Do this by keeping results in a structure that preserves the semantics of the data, and defer formatting to the very end.</p>\n\n<p>Think about the task of using your code to make a web page: it's going to be hairy because your math functions have <code>print</code> statements in them. It's better if those functions return numbers to be printed later by <code>formatter</code> function.</p>\n\n<h2>Separate program logic from UI elements</h2>\n\n<p>This is the same point as the previous one, just applied to input instead of output. Use data structures that group input characteristics together, keeping display values independant from logic-affecting values.</p>\n\n<p>As written, the button labels dictate the program flow (<code>if var.get() == \"Circle Circumference\":</code> etc.). If you translate your program to another language, it won't work anymore. </p>\n\n<h2>Functions can be data</h2>\n\n<p>Each kind of user-selected computation has a formula to go with it. It is natural to group those formulae alongside the other traits of the calculation.</p>\n\n<h2>Example</h2>\n\n<p>Here is one approach to your problem. Observe how the actual code has almost nothing to do with what you're calculating, or how, or what the output will look like. Instead, the data structure dictates how many variables to ask for, how to transform them into an answer, and how to format the answer for display.</p>\n\n<p>From here, you could generalize this in all kinds of ways with few changes to the code. For example, <code>float(input(prompt))</code> is \"hardcoded\" in the logic. This could be another lambda in the data, perhaps attached to each prompt, so that you can configure it to ask for integers or strings instead of just floats.</p>\n\n<pre><code>PI = 3.141592653589793\ncalculations = [\n dict(\n label=\"Circle Circumference\",\n prompt=[\n \"Enter the radius of the circle in the units of your choice: \"\n ],\n result_format=\"\\nThe volume of the sphere is: {0:.4f} units.\",\n formula=lambda r: r*2*PI\n ),\n dict(\n label=\"Sphere Volume\",\n prompt=[\n \"Enter the radius of the sphere in the units of your choice: \"\n ],\n result_format=\"\\nThe volume of the sphere is: {0:.4f} units.\",\n formula=lambda r: r**3 * 4/3 * PI\n ),\n dict(\n label=\"Cone Volume\",\n prompt=[\n \"Enter the radius of the cone in the units of your choice: \",\n \"Enter the height of the cone in those same units: \"\n ],\n result_format=\"\\nThe volume of the cone is: {0:.4f} units.\",\n formula=lambda r,h: r**2 * h * PI / 3\n ),\n # ... etc.\n]\n\n# selected_menu = var.get()\nselected_menu=\"Cone Volume\" # hardcoded for demonstration purposes\n\naction = next( filter(lambda x: x['label'] == selected_menu, calculations) )\n\ninputs = list( map( lambda prompt: float(input(prompt)), action['prompt'] ))\n\nanswer = action['formula'](*inputs)\n\nresult_text = action['result_format'].format(answer)\n\nprint(result_text)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T12:37:42.127",
"Id": "214643",
"ParentId": "214628",
"Score": "4"
}
},
{
"body": "<p>To continue on from <a href=\"https://codereview.stackexchange.com/users/131732/oh-my-goodness\">@OhMyGoodness</a>'s <a href=\"https://codereview.stackexchange.com/a/214643/98493\">excellent answer</a>, one way you can take this is in the direction of Object Oriented Programming. You have objects, shapes, which have properties like an area and a circumference or volume. So make them into classes:</p>\n\n<pre><code>PI = 3.1415926\n\nclass Shape:\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return self.name\n</code></pre>\n\n<p>All other shapes can inherit from this:</p>\n\n<pre><code>class Circle(Shape):\n def __init__(self, radius):\n super().__init__(\"Circle\")\n self.radius = radius\n\n @property\n def area(self):\n return PI * self.radius **2\n\n @property\n def circumference(self):\n return 2* PI * self.radius\n</code></pre>\n\n<p>This has the advantage that for shapes that are special shapes of some other shape you can save a lot of repetition:</p>\n\n<pre><code>class Rectangle(Shape):\n def __init__(self, height, width):\n super().__init__(\"Rectangle\")\n self.height, self.width = height, width\n\n @property\n def area(self):\n return self.height * self.width\n\n @property\n def circumference(self):\n return 2*self.height + 2*self.width\n\nclass Square(Rectangle):\n def __init__(self, width):\n super().__init__(width, width)\n self.name = \"Square\"\n</code></pre>\n\n<p>You can even use elements of a lower dimension for shapes in a higher dimension, where applicable:</p>\n\n<pre><code>class Cone(Shape):\n def __init__(self, radius, height):\n super().__init__(\"Cone\")\n self.radius, self.height = radius, height\n self.base = Circle(radius)\n\n @property\n def area(self):\n return self.base.area + PI * self.radius * sqrt(self.radius**2 + self.height**2)\n\n @property\n def volume(self):\n return self.base.area * self.height / 3\n</code></pre>\n\n<p>And for the menu you can use introspection:</p>\n\n<pre><code># initialize some shape:\nshape = Square(2)\n\n# You could setup buttons with this information instead of printing it:\nprint(\"Available methods:\")\navailable = set(filter(lambda m: not m.startswith(\"__\"), dir(shape)))\nfor x in available:\n print(x)\n\n# Let the user choose (or for you click on the button):\nchoice = None\nwhile choice not in available:\n choice = input()\n\n# print result:\nprint(choice, \"=\", getattr(shape, choice))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T11:14:19.360",
"Id": "214696",
"ParentId": "214628",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214643",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T05:48:58.873",
"Id": "214628",
"Score": "5",
"Tags": [
"python",
"beginner",
"calculator",
"tkinter"
],
"Title": "Area and volume calculator"
} | 214628 |
<h1>Background</h1>
<p>I have a vba solution that I use to ingest investment text reports and reformat them for analysis in Excel. It works, but the macros involve a lot of direct manipulation of Excel objects, and have no unit-testing.</p>
<p>After finding <a href="https://rubberduckvba.wordpress.com/" rel="nofollow noreferrer">RubberDuck</a>, and reading several years' worth of excellent posts from @MathieuGuindon, I've decided to re-write the "brute force"-heavy solution as a way to learn these new concepts and techniques.</p>
<p>When ingesting from a report, I also pull additional attributes from excel tables. I'm beginning my re-write with those lookup tables. The first of which I'm submitting here. </p>
<p>Initial goals:</p>
<ul>
<li>Programming to Interfaces not classes </li>
<li>Making Services and Proxies rather than direct access to Excel sheets and ranges</li>
<li>Using the PredeclaredId attribute to enable a Create method </li>
<li>Thorough unit testing</li>
</ul>
<p>Apart from general review, I also have some specific questions, which I'll post following the code.</p>
<hr>
<h2>Code</h2>
<p><strong><em><code>IAssetTableProxy</code></em></strong> -- abstracts reference to the "physical" excel table's data rows </p>
<pre><code>'@Folder("Services.Interfaces")
Option Explicit
Public Function GetAssetTableData() As Variant()
End Function
</code></pre>
<p><strong><em><code>AssetTableProxy</code></em></strong> -- Implementation</p>
<pre><code>'@Folder("Services.Proxies")
Option Explicit
Implements IAssetTableProxy
Public Function IAssetTableProxy_GetAssetTableData() As Variant()
Dim tblName As String
tblName = "AssetInfoTable"
IAssetTableProxy_GetAssetTableData = Worksheets(Range(tblName).Parent.Name).ListObjects(tblName).DataBodyRange.value
End Function
</code></pre>
<p><strong><em><code>AssetInfo</code></em></strong> -- a class to handle the three values for each row: Desc, Ticker, Type</p>
<pre><code>'@PredeclaredId
'@Folder("Services")
Option Explicit
Private Type TAssetInfo
Desc As String
Ticker As String
AssetType As String
End Type
Private this As TAssetInfo
Public Property Get Desc() As String
Desc = this.Desc
End Property
Friend Property Let Desc(ByVal value As String)
this.Desc = value
End Property
Public Property Get Ticker() As String
Ticker = this.Ticker
End Property
Friend Property Let Ticker(ByVal value As String)
this.Ticker = value
End Property
Public Property Get AssetType() As String
AssetType = this.AssetType
End Property
Friend Property Let AssetType(ByVal value As String)
this.AssetType = value
End Property
Public Property Get Self() As AssetInfo
Set Self = Me
End Property
Public Function Create(ByVal theDesc As String, ByVal theTicker As String, ByVal theAssetType As String) As AssetInfo
With New AssetInfo
.Desc = theDesc
.Ticker = theTicker
.AssetType = theAssetType
Set Create = .Self
End With
End Function
</code></pre>
<p><strong><em><code>IAssetInfoService</code></em></strong> -- holds a collection of AssetInfo objects and
provides the needed lookups to data from AssetTableProxy</p>
<pre><code>'@Folder("Services.Interfaces")
Option Explicit
Public Function Create(ByRef assetTbl As IAssetTableProxy) As IAssetInfoService
End Function
Public Function GetAssetTypeForDesc(ByVal Desc As String) As String
End Function
Public Function GetTickerForDesc(ByVal Desc As String) As String
End Function
</code></pre>
<p><strong><em><code>AssetInfoService</code></em></strong> -- implementation</p>
<pre><code>'@PredeclaredId
'@Folder("Services")
Option Explicit
Option Base 1
Implements IAssetInfoService
Private Type TAssetsTable
AssetColl As Collection
End Type
Private this As TAssetsTable
Friend Property Get Assets() As Collection
Set Assets = this.AssetColl
End Property
Friend Property Set Assets(ByRef coll As Collection)
Set this.AssetColl = coll
End Property
Public Property Get Self() As IAssetInfoService
Set Self = Me
End Property
Public Function IAssetInfoService_Create(ByRef assetTbl As IAssetTableProxy) As IAssetInfoService
Dim twoDArr() As Variant
twoDArr = assetTbl.GetAssetTableData
With New AssetInfoService
Dim tempAsset As AssetInfo
Dim tempColl As Collection
Set tempColl = New Collection
Dim rw As Long
For rw = 1 To UBound(twoDArr, 1)
Set tempAsset = AssetInfo.Create(twoDArr(rw, 1), twoDArr(rw, 2), twoDArr(rw, 3))
tempColl.Add tempAsset, key:=tempAsset.Desc
Next rw
Set .Assets = tempColl
Set IAssetInfoService_Create = .Self
End With
End Function
Public Function IAssetInfoService_GetAssetTypeForDesc(ByVal Desc As String) As String
Dim tempTp As String
If Exists(this.AssetColl, Desc) Then
tempTp = this.AssetColl(Desc).AssetType
Else
tempTp = "Unknown Asset"
End If
IAssetInfoService_GetAssetTypeForDesc = tempTp
End Function
Public Function IAssetInfoService_GetTickerForDesc(ByVal Desc As String) As String
Dim tempTicker As String
If Exists(this.AssetColl, Desc) Then
tempTicker = this.AssetColl(Desc).Ticker
Else
tempTicker = "Unknown Asset"
End If
IAssetInfoService_GetTickerForDesc = tempTicker
End Function
Private Function Exists(ByRef coll As Collection, ByRef key As String) As Boolean
On Error GoTo ErrHandler
coll.Item key
Exists = True
ErrHandler:
End Function
</code></pre>
<hr>
<h2>Unit Testing</h2>
<p><strong><em><code>AssetTableTestProxy</code></em></strong> -- proxy implementation for testing w/o dependency on actual excel table</p>
<pre><code>'@Folder("Services.Proxies")
Option Explicit
Option Base 1
Implements IAssetTableProxy
Public Function IAssetTableProxy_GetAssetTableData() As Variant()
Dim twoDArr(1 To 3, 1 To 3) As Variant
twoDArr(1, 1) = "Asset1"
twoDArr(1, 2) = "Tick1"
twoDArr(1, 3) = "Type1"
twoDArr(2, 1) = "Asset2"
twoDArr(2, 2) = "Tick2"
twoDArr(2, 3) = "Type2"
twoDArr(3, 1) = "Asset3"
twoDArr(3, 2) = "Tick3"
twoDArr(3, 3) = "Type3"
IAssetTableProxy_GetAssetTableData = twoDArr
End Function
</code></pre>
<p><strong><em><code>TestAssetInfoService</code></em></strong> -- Unit tests for Asset Info Service</p>
<pre><code>Option Explicit
Option Private Module
'@TestModule
'@Folder("Tests")
Private Assert As Object
Private Fakes As Object
Private assetTbl As IAssetTableProxy
'@ModuleInitialize
Public Sub ModuleInitialize()
'this method runs once per module.
Set Assert = CreateObject("Rubberduck.AssertClass")
Set Fakes = CreateObject("Rubberduck.FakesProvider")
Set assetTbl = New AssetTableTestProxy
End Sub
'@ModuleCleanup
Public Sub ModuleCleanup()
'this method runs once per module.
Set Assert = Nothing
Set Fakes = Nothing
Set assetTbl = Nothing
End Sub
'@TestInitialize
Public Sub TestInitialize()
'this method runs before every test in the module.
End Sub
'@TestCleanup
Public Sub TestCleanup()
'this method runs after every test in the module.
End Sub
'@TestMethod
Public Sub GivenAssetInTable_GetTicker()
On Error GoTo TestFail
'Arrange:
Dim tbl As IAssetInfoService
Set tbl = AssetInfoService.IAssetInfoService_Create(assetTbl)
'Act:
Dim tick As String
tick = tbl.GetTickerForDesc("Asset2")
'Assert:
Assert.AreEqual "Tick2", tick, "Tick was: " & tick
TestExit:
Exit Sub
TestFail:
Assert.Fail "Test raised an error: #" & Err.Number & " - " & Err.Description
End Sub
'@TestMethod
Public Sub GivenAssetInTable_GetAssetType()
On Error GoTo TestFail
'Arrange:
Dim tbl As IAssetInfoService
Set tbl = AssetInfoService.IAssetInfoService_Create(assetTbl)
'Act:
Dim assetTp As String
assetTp = tbl.GetAssetTypeForDesc("Asset2")
'Assert:
Assert.AreEqual "Type2", assetTp, "AssetTp was: " & assetTp
TestExit:
Exit Sub
TestFail:
Assert.Fail "Test raised an error: #" & Err.Number & " - " & Err.Description
End Sub
'@TestMethod
Public Sub GivenAssetNotInTable_GetUnknownAssetMsg()
On Error GoTo TestFail
'Arrange:
Dim tbl As IAssetInfoService
Set tbl = AssetInfoService.IAssetInfoService_Create(assetTbl)
'Act:
Dim tp As String
tp = tbl.GetAssetTypeForDesc("unsub")
'Assert:
Assert.AreEqual "Unknown Asset", tp
TestExit:
Exit Sub
TestFail:
Assert.Fail "Test raised an error: #" & Err.Number & " - " & Err.Description
End Sub
</code></pre>
<hr>
<p><strong><em><code>Module1</code></em></strong> -- additional sub to play around with functions</p>
<pre><code>Option Explicit
Sub TestAssetInfoTable()
Dim assetTbl As IAssetTableProxy
Dim testAssetTbl As AssetTableTestProxy
Set assetTbl = New AssetTableProxy
Set testAssetTbl = New AssetTableTestProxy
Dim assetSvc As IAssetInfoService
Dim testAssetSvc As IAssetInfoService
Set assetSvc = AssetInfoService.IAssetInfoService_Create(assetTbl)
Set testAssetSvc = AssetInfoService.IAssetInfoService_Create(testAssetTbl)
Dim tp As String
Dim tick As String
tp = assetSvc.GetAssetTypeForDesc("AMAZON COM INC (AMZN)")
tick = assetSvc.GetTickerForDesc("AMAZON COM INC (AMZN)")
MsgBox ("Real Svc: tp=" & tp & "; tick=" & tick)
tp = testAssetSvc.GetAssetTypeForDesc("Asset3")
tick = testAssetSvc.GetTickerForDesc("Asset3")
MsgBox ("Test Svc: tp=" & tp & "; tick=" & tick)
End Sub
</code></pre>
<hr>
<h2>Specific questions:</h2>
<ol>
<li>I initially had the "proxy" logic in the service class. But it felt like I was duplicating too many functions when I created the <code>AssetInfoTestService</code> class. Breaking it out to <code>AssetTableProxy</code> and <code>AssetTableTestProxy</code> allowed me to keep only one version of the service functions. But is this carrying things (abstraction?) too far?</li>
<li><p>Learning about interfaces, I believe I understand the following pieces: </p>
<ul>
<li>the contract created by each Function mentioned in the interface; </li>
<li>the requisite coding of corresponding Interface_Function in the implementing class; </li>
<li>the dimm-ing of class var "as Interface"; and </li>
<li>accessing the functions with <em><code>classVar.Function</code></em>
<ul>
<li>However there seems to be an exception here. In <code>TestAssetInfoTable</code> I dim assetSvc as <code>IAssetInfoService</code>. That interface has a Create function, and in the concrete class, I have <code>IAssetInfoService_Create</code> defined. But when I try to call <code>AssetInfoService.Create(…)</code> I get a compile error that only clears when I change to <code>AssetInfoService.IAssetInfoService_Create</code>. What am I missing there?</li>
</ul></li>
</ul></li>
<li><p>I see the "Option Base 1" thing. Since leave C pointers long ago, I haven't really had a religious belief one way or the other on 0- vs 1-based arrays. I went with it here, because when I began playing with the (extremely handy) <code>multiDimArray = Range</code> I noted the returned arrays are 1-based. And I kept screwing myself up between coding for those, and coding for my own 0-based ones. So I just opted to go all 1-based. Rubberduck Code Inspections do always throw that decision back in my face though, so let me ask here: are compelling reasons to not do that, or work arounds/tips for the <code>multiDimArray = Range</code> 1-based thing?</p></li>
</ol>
| [] | [
{
"body": "<p>First off, nice work overall. It's apparent from the way you set up your interfaces and implementations that you \"get it\". Given that, most? of this can probably be classified as \"nitpicking\". I'm also not going to <em>specifically</em> address your second question, but the answers should be apparent based on the review itself (if not, feel free to ask in the comments). I'm completely ambivalent as to your 1st question (and can't really compare them without seeing the alternative structure), although others may have opinions there.</p>\n\n<hr>\n\n<p><code>AssetInfoService</code>'s internal <code>Collection</code> is not properly encapsulated. You expose it like this...</p>\n\n<blockquote>\n<pre><code>Friend Property Get Assets() As Collection\n Set Assets = this.AssetColl\nEnd Property \n</code></pre>\n</blockquote>\n\n<p>...but that is relying on the caller to hold a reference to its interface instead of a hard reference to prevent a call like <code>AssetInfoService.Assets.Remove</code> or <code>AssetInfoService.Assets.Add</code> from anywhere in the same project. The <code>Friend</code> modifier obviously prevents other <em>projects</em> from doing this, but it isn't clear from the code provided why you would want a caller to be able to mess with the internals of the class like that. If the intention of the <code>IAssetInfoService</code> is to wrap a <code>Collection</code> (as evidenced by the <code>Exists</code> method), then I'd provide a complete wrapper.</p>\n\n<hr>\n\n<p>Related to the above, I'd say it's overkill to provide an internal <code>Type</code> that contains a single member:</p>\n\n<blockquote>\n<pre><code>Private Type TAssetsTable\n AssetColl As Collection\nEnd Type\nPrivate this As TAssetsTable\n</code></pre>\n</blockquote>\n\n<p>Nitpick, but I'd also prefer an empty line after <code>End Type</code> - that makes it more readable.</p>\n\n<hr>\n\n<p>The factory <code>Create</code> methods are much, much clearer in the calling code if you implement them on the base class also. That's why you have to write code like this:</p>\n\n<blockquote>\n<pre><code>Set assetSvc = AssetInfoService.IAssetInfoService_Create(assetTbl)\nSet testAssetSvc = AssetInfoService.IAssetInfoService_Create(testAssetTbl)\n</code></pre>\n</blockquote>\n\n<p>The best way to think of a class's implementation is the same way that it would be viewed in a COM TypeLib - internally, <code>AssetInfoService</code> is more or less treated as an implicit interface (let's call it <code>_AssetInfoService</code> to follow MS convention). Unlike .NET, the implemented interfaces are not aggregated back into the \"base\" interface implicitly - that's why you need to use the explicit interface version when you have an instance of the concrete class. If the intention is to have the procedure accessible from the implementing class, the standard way of doing this in VBA is to wrap the base method with the interface's implementation:</p>\n\n<pre><code>Public Function Create(ByRef assetTbl As IAssetTableProxy) As IAssetInfoService\n Dim twoDArr() As Variant\n\n twoDArr = assetTbl.GetAssetTableData\n\n With New AssetInfoService\n\n '... etc.\nEnd Function\n\nPublic Function IAssetInfoService_Create(ByRef assetTbl As IAssetTableProxy) As IAssetInfoService\n Set IAssetInfoService_Create = Me.Create(assetTbl)\nEnd Function\n</code></pre>\n\n<p>That makes the calling code much more readable:</p>\n\n<pre><code>Set assetSvc = AssetInfoService.Create(assetTbl)\nSet testAssetSvc = AssetInfoService.Create(testAssetTbl)\n</code></pre>\n\n<hr>\n\n<p>I don't see a reason for the <code>Self</code> properties of your factories to be public. If you're only intending to provide access to them via their interfaces, there isn't a reason to expose this on the concrete instances. The reason for this is that there is no restriction on \"up-casting\". This is perfectly legal:</p>\n\n<pre><code>Sub Foo()\n Dim bar As IAssetInfoService\n Set assetSvc = AssetInfoService.IAssetInfoService_Create(assetTbl)\n\n Dim upCast As AssetInfoService\n Set upCast = assetSvc\n With upCast.Self\n 'Uhhhh...\n End With\nEnd Sub\n</code></pre>\n\n<p>The other side of this is related to the discussion of the \"base\" interface above. If for some reason a caller up-casts to <code>AssetTableProxy</code>, they'll find that it has no public members...</p>\n\n<hr>\n\n<p><code>AssetTableProxy</code> has what I would consider to be a bug. This code is implicitly using the ActiveWorkbook and the ActiveSheet:</p>\n\n<blockquote>\n<pre><code>Public Function IAssetTableProxy_GetAssetTableData() As Variant()\n\n Dim tblName As String\n tblName = \"AssetInfoTable\"\n\n IAssetTableProxy_GetAssetTableData = Worksheets(Range(tblName).Parent.Name).ListObjects(tblName).DataBodyRange.value\n\nEnd Function\n</code></pre>\n</blockquote>\n\n<p>If this is always supposed to reference the current workbook, I'd use <code>ThisWorkbook.Worksheets</code> (or the equivalent code name). The unqualified <code>Range</code> will throw if the <code>ActiveSheet</code> isn't a <code>Worksheet</code>, so your method of finding the <code>ListObject</code> this way puts you in kind of a catch 22 because you're <em>only</em> using the name of the table, which means that you need to get its parent worksheet to find... its worksheet? Just skip all of this and use the code name of the sheet directly. Also, <code>tblName</code> is functionally a constant. I'd declare it as one.</p>\n\n<pre><code>Private Const TABLE_NAME As String = \"AssetInfoTable\"\n\nPublic Function IAssetTableProxy_GetAssetTableData() As Variant()\n 'Replace Sheet1 with the actual code name of the worksheet.\n IAssetTableProxy_GetAssetTableData = Sheet1.ListObjects(TABLE_NAME).DataBodyRange.value\nEnd Function\n</code></pre>\n\n<hr>\n\n<p>Nitpick - I would remove the underscores in your test names (i.e. <code>GivenAssetInTable_GetTicker()</code>). The underscore has special meaning in VBA for procedure names - it's treated as kind of an \"interface or event delimiter\". This is probably our fault (as in Rubberduck's - I'm a project contributor) in that the \"Add test module with stubs\" used to do this when it was naming tests. This has been corrected in the current build, and TBH I'd like to see an inspection for use of an underscore in a procedure name that isn't an interface member or event handler (but I digress). The main take-away here is that when you see an underscore in a procedure name, you shouldn't need to ask yourself if it has meaning outside the name.</p>\n\n<hr>\n\n<p>Another nitpick - there's no reason to <code>Set assetTbl = Nothing</code> in <code>ModuleCleanup()</code>. The reason that the <code>Assert</code> and <code>Fakes</code> are explicitly set to <code>Nothing</code> has to do with the internal architecture of Rubberduck's testing engine. In your case it doesn't matter in the least if the reference to your <code>IAssetTableProxy</code> isn't immediately freed.</p>\n\n<hr>\n\n<p>Specifically regarding your third question. The reason Rubberduck suggests not using <code>Option Base 1</code> is that it is a per module option that overrides the default array base of the <em>language</em>. If you specify the lower bound like you do here... </p>\n\n<blockquote>\n<pre><code>Option Explicit\nOption Base 1\nImplements IAssetTableProxy\n\nPublic Function IAssetTableProxy_GetAssetTableData() As Variant()\n\n Dim twoDArr(1 To 3, 1 To 3) As Variant\n\n '...\n\n IAssetTableProxy_GetAssetTableData = twoDArr\n\nEnd Function\n</code></pre>\n</blockquote>\n\n<p>...it is superfluous - you're <em>always</em> creating an array with base 1 and doing it explicitly. You should be doing this anyway if you're using a non-zero base because it's clear that the lower bound is \"non-standard\" without requiring the person looking at the code to scroll all the way to the top of the module and catch the fact that you have a non-standard option defined. I can see it at the point of the declaration.</p>\n\n<p>The other place it appears is in <code>AssetInfoService</code>, but it is completely unneeded there also. The only place you are assigning an array is here...</p>\n\n<blockquote>\n<pre><code>Dim twoDArr() As Variant\n\ntwoDArr = assetTbl.GetAssetTableData\n</code></pre>\n</blockquote>\n\n<p>...and that module doesn't control the actual creation of the array. You can remove <code>Option Base 1</code> everywhere in your code and it will have no effect what-so-ever.</p>\n\n<p>If you're using arrays from an external source (i.e. Excel), you should be using <code>LBound</code> anyway - VBA has a zero default, but a COM <code>SAFEARRAY</code> allows the lower bound to be an arbitrary number. Pedantically, this code... </p>\n\n<blockquote>\n<pre><code> For rw = 1 To UBound(twoDArr, 1) \n</code></pre>\n</blockquote>\n\n<p>...should be: </p>\n\n<pre><code>For rw = LBound(twoDArr, 1) To UBound(twoDArr, 1) \n</code></pre>\n\n<p>That decouples your interface from the representation of the array that is supplied by the <code>IAssetTableProxy</code>. This is just like any other form of coupling in that it makes the implementation \"brittle\" to the extent that it makes assumptions about the form of the data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T18:39:40.750",
"Id": "415103",
"Score": "0",
"body": "Out of interest, what would you suggest for the names of test methods? I noticed Mathieu Guindon's [battleship tests](https://codereview.stackexchange.com/q/202101/146810) use the same convention: `TestName_ExpectedReturnValue`and I was quite taken with it, as it conveys a lot of useful information about the test in a readable fashion. Given that the battleship project is sort of a Rubberduck showcase (IIUC), it would be good to have everyone on the same page; what do you think is a good general format for these tests? Just remove the underscore and leave as is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T19:05:07.070",
"Id": "415107",
"Score": "0",
"body": "@Greedo I'd just omit the underscore: `TestNameExpectedReturnValue`. In cases where I had a ton of identical `TestName`'s, I'd organize that into a module and/or make that the test category instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T21:09:58.153",
"Id": "415223",
"Score": "0",
"body": "Thanks @Comintern. Yes, oops, the coll exposure in `AssetInfoService` doesn't belong. (It's a relic of me figuring things out.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T21:10:21.983",
"Id": "415224",
"Score": "0",
"body": "LBound tip is great. Consistent use of that will likely remove the times I was tripping myself up with 1 v 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T21:11:29.563",
"Id": "415225",
"Score": "0",
"body": "I didn't completely follow the analogy on the interfaces (not really conversant in .NET), but I agree that things are much more readable with the structure you recommend. That gets around the awkward difference/compile error I found in calling implementations of Ixxx_Create versus implementations of all other Ixxx_Functions. (still not sure why it's that way)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T21:17:48.030",
"Id": "415228",
"Score": "0",
"body": "@jdap - Sorry, perhaps a bad example then - in a lot of other languages, when you have a class `Foo` that implements interface `IBar`, `Foo` has both sets of procedures when it's being treated as a `Foo`. That was a long-winded way of explaining that VBA doesn't do that - the \"base interface\" is everything *other than* the explicit implementations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T02:16:20.603",
"Id": "415247",
"Score": "0",
"body": "@Comintern I tried changing the `Assets` property `AssetInfoService` from _Friend_ to _Private_. But I get a compilation error in *Create* where I try to use `.Assets` in the `With New AssetInfoService` block. \"Method or data member not found.\" I guess it wasn't so much an \"oops\" as an \"I don't understand all I need to about Private vs Friend\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T02:23:18.893",
"Id": "415248",
"Score": "0",
"body": "@jdap The point wasn't so much that you should make `Assets` private - the point was that you're allowing external access to the backing `Collection`. If you provide a full wrapper, the `Collection` would get instantiated in the class initializer, and then you'd call the `AssetInfoService.Add` wrapper instead of `Collection.Add`. I'd remove `Assets` entirely."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T18:04:22.567",
"Id": "214658",
"ParentId": "214629",
"Score": "3"
}
},
{
"body": "<p>@comintern, I've implemented most of the rest of your suggestions. <em>Much</em> more readable! Details and revised code below.</p>\n\n<ul>\n<li>Refactored to Base 0 (including the hardcoded twoDArr in <code>AssetTableTestProxy</code>) and using LBound</li>\n<li>Removed Property Get/Set Assets </li>\n<li>Refactored to Property Let AddAsset</li>\n<li>Refactored <code>IAssetInfoService_Create</code> as suggested</li>\n</ul>\n\n<p>Couple points I'm unsure about:</p>\n\n<ul>\n<li><em><code>AddAsset</code></em>: Q) Is there a better way/place to instantiate <code>this.AssetColl</code>? I tried a few other solutions, but could not get things to work. </li>\n<li><em><code>Create</code></em>: Q) The syntax of <code>.AddAsset = ...</code> feels off. The equal sign bothers me as this is not really an <em>assignment</em> operation. Is there a better way to use this property?</li>\n<li>I still struggle a bit with the scoping(?). The working of the PredeclaredId and the, kind of <em>call-within-a-call</em> nature of the <code>With New <object of class I'm already in> ... End With</code> structure takes some thinking. I'm betting that's what's screwing with me on the instantiation of AssetCol. And I'm also certain that's why I have to use Friend instead of Private, though I'm unable to articulate the reason. </li>\n</ul>\n\n<p><strong><em><code>AssetInfoService.cls</code></em></strong></p>\n\n<pre><code>'@PredeclaredId\n'@Folder(\"Services\")\nOption Explicit\nImplements IAssetInfoService\n\nPrivate Type TAssetsTable\n AssetColl As Collection\nEnd Type\nPrivate this As TAssetsTable\n\nFriend Property Get Self() As IAssetInfoService\n Set Self = Me\nEnd Property\n\nFriend Property Let AddAsset(ByRef theAsset As AssetInfo)\n If this.AssetColl Is Nothing Then\n Set this.AssetColl = New Collection\n End If\n this.AssetColl.Add theAsset, key:=theAsset.Desc\nEnd Property\n\nPublic Function IAssetInfoService_Create(ByRef assetTbl As IAssetTableProxy) As IAssetInfoService\n Set IAssetInfoService_Create = Me.Create(assetTbl)\nEnd Function\n\nFriend Function Create(ByRef assetTbl As IAssetTableProxy) As IAssetInfoService\n\n Dim twoDArr() As Variant\n\n twoDArr = assetTbl.GetAssetTableData\n\n With New AssetInfoService\n\n Dim arrBase As Long\n arrBase = LBound(twoDArr) ' need to allow for 0-based in testing, but 1-based when arr populated from Excel range\n\n Dim row As Long\n For row = LBound(twoDArr) To UBound(twoDArr)\n .AddAsset = AssetInfo.Create(twoDArr(row, arrBase), twoDArr(row, arrBase + 1), twoDArr(row, arrBase + 2))\n Next row\n\n Set Create = .Self\n\n End With\n\nEnd Function\n\n\nPublic Function IAssetInfoService_GetAssetTypeForDesc(ByVal Desc As String) As String\n\n Dim tempTp As String\n If Exists(this.AssetColl, Desc) Then\n tempTp = this.AssetColl(Desc).AssetType\n Else\n tempTp = \"Unknown Asset\"\n End If\n IAssetInfoService_GetAssetTypeForDesc = tempTp\n\nEnd Function\n\nPublic Function IAssetInfoService_GetTickerForDesc(ByVal Desc As String) As String\n\n Dim tempTicker As String\n If Exists(this.AssetColl, Desc) Then\n tempTicker = this.AssetColl(Desc).Ticker\n Else\n tempTicker = \"Unknown Asset\"\n End If\n IAssetInfoService_GetTickerForDesc = tempTicker\n\nEnd Function\n\nPrivate Function Exists(ByRef coll As Collection, ByRef key As String) As Boolean\n\n On Error GoTo ErrHandler\n\n coll.Item key\n\n Exists = True\nErrHandler:\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T06:13:32.580",
"Id": "214995",
"ParentId": "214629",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214658",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T05:55:18.333",
"Id": "214629",
"Score": "3",
"Tags": [
"vba",
"excel",
"rubberduck"
],
"Title": "Abstracting and unit testing lookups in Excel table"
} | 214629 |
<p>Since my rather mediocre attempt at making a Space Invaders game, I stumbled on a cache of Visual Basic for Applications games written by Japanese excel wizards. I have even seen someone create Zelda?! What an inspiration! Making complete, beautiful, fun arcade / GameBoy style games inside of an Excel spreadsheet is possible.</p>
<p>This is my first crack at recreating the old game <a href="https://github.com/Evanml2030/Excel-Snake" rel="nofollow noreferrer">Snake</a>.</p>
<p><strong>Classes:</strong></p>
<p><em>Snake Part:</em></p>
<pre><code>Option Explicit
Private Type Properties
row As Long
column As Long
End Type
Private this As Properties
Public Property Let row(ByVal value As Long)
this.row = value
End Property
Public Property Get row() As Long
row = this.row
End Property
Public Property Let column(ByVal value As Long)
this.column = value
End Property
Public Property Get column() As Long
column = this.column
End Property
Public Sub PropertiesSet(ByVal row As Long, ByVal column As Long)
this.row = row
this.column = column
End Sub
</code></pre>
<p><em>TimerWin64:</em></p>
<pre><code>Option Explicit
Private Declare PtrSafe Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LongInteger) As Long
Private Declare PtrSafe Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LongInteger) As Long
Private Type LongInteger
First32Bits As Long
Second32Bits As Long
End Type
Private Type TimerAttributes
CounterInitial As Double
CounterNow As Double
PerformanceFrequency As Double
End Type
Private Const MaxValue_32Bits = 4294967296#
Private this As TimerAttributes
Private Sub Class_Initialize()
PerformanceFrequencyLet
End Sub
Private Sub PerformanceFrequencyLet()
Dim TempFrequency As LongInteger
QueryPerformanceFrequency TempFrequency
this.PerformanceFrequency = ParseLongInteger(TempFrequency)
End Sub
Public Sub TimerSet()
Dim TempCounterIntital As LongInteger
QueryPerformanceCounter TempCounterIntital
this.CounterInitial = ParseLongInteger(TempCounterIntital)
End Sub
Public Function CheckQuarterSecondPassed() As Boolean
CounterNowLet
If ((this.CounterNow - this.CounterInitial) / this.PerformanceFrequency) >= 0.25 Then
CheckQuarterSecondPassed = True
Else
CheckQuarterSecondPassed = False
End If
End Function
Public Function CheckFiveSecondsPassed() As Boolean
CounterNowLet
If ((this.CounterNow - this.CounterInitial) / this.PerformanceFrequency) >= 10 Then
CheckFiveSecondsPassed = True
Else
CheckFiveSecondsPassed = False
End If
End Function
Public Sub PrintTimeElapsed()
CounterNowLet
If CounterInitalIsSet = True Then
Dim TimeElapsed As Double
TimeElapsed = (this.CounterNow - this.CounterInitial) / this.PerformanceFrequency
Debug.Print Format(TimeElapsed, "0.000000"); " seconds elapsed "
Dim TicksElapsed As Double
TicksElapsed = (this.CounterNow - this.CounterInitial)
Debug.Print Format(TicksElapsed, "#,##0"); " ticks"
End If
End Sub
Private Function CounterNowLet()
Dim TempTimeNow As LongInteger
QueryPerformanceCounter TempTimeNow
this.CounterNow = ParseLongInteger(TempTimeNow)
End Function
Private Function CounterInitalIsSet() As Boolean
If this.CounterInitial = 0 Then
MsgBox "Counter Initial Not Set"
CounterInitalIsSet = False
Else
CounterInitalIsSet = True
End If
End Function
Private Function ParseLongInteger(ByRef LongInteger As LongInteger) As Double
Dim First32Bits As Double
First32Bits = LongInteger.First32Bits
Dim Second32Bits As Double
Second32Bits = LongInteger.Second32Bits
If First32Bits < 0 Then First32Bits = First32Bits + MaxValue_32Bits
If Second32Bits < 0 Then Second32Bits = First32Bits + MaxValue_32Bits
ParseLongInteger = First32Bits + (MaxValue_32Bits * Second32Bits)
End Function
</code></pre>
<p><strong>Worksheet Code:</strong></p>
<pre><code>Option Explicit
Public Enum Direction
North = 1
South = 2
East = 3
West = 4
End Enum
Public ws As Worksheet
Public snakeParts As Collection
Public currentRow As Long
Public currentColumn As Long
Public directionSnake As Direction
Sub RunGame()
Set ws = ActiveWorkbook.Sheets("Game")
Set snakeParts = New Collection
Dim gameOver As Boolean
gameOver = False
Dim TimerGame As TimerWin64
Set TimerGame = New TimerWin64
Dim TimerBlueSquare As TimerWin64
Set TimerBlueSquare = New TimerWin64
Dim TimerYellowSquare As TimerWin64
Set TimerYellowSquare = New TimerWin64
Dim SnakePartNew As snakepart
Set SnakePartNew = New snakepart
GameBoardReset
DirectionSnakeInitialize
StartPositionInitalize
StartGameBoardInitalize
TimerGame.TimerSet
TimerBlueSquare.TimerSet
TimerYellowSquare.TimerSet
ws.cells(currentRow, currentColumn).Select
Do While gameOver = False
If TimerGame.CheckQuarterSecondPassed = True Then
CurrentCellUpdate
ws.cells(currentRow, currentColumn).Select
If SnakePartOverlapItself(currentRow, currentColumn) = True Then
gameOver = True
Exit Do
ElseIf SnakePartYellowSquareOverlap = True Then
gameOver = True
Exit Do
ElseIf SnakePartBlueSquareOverlap = True Then
Call SnakePartAdd(currentRow, currentColumn)
Call SnakePartAdd(currentRow, currentColumn)
Call SnakePartAdd(currentRow, currentColumn)
Call SnakePartRemove
ws.cells(currentRow, currentColumn).Select
TimerGame.TimerSet
Else
Call SnakePartAdd(currentRow, currentColumn)
Call SnakePartRemove
ws.cells(currentRow, currentColumn).Select
TimerGame.TimerSet
End If
End If
If TimerBlueSquare.CheckFiveSecondsPassed = True Then
BlueSquareAdd
TimerBlueSquare.TimerSet
End If
If TimerYellowSquare.CheckFiveSecondsPassed = True Then
YellowSquareAdd
TimerYellowSquare.TimerSet
End If
gameOver = OutOfBounds
DoEvents
Loop
End Sub
Private Sub GameBoardReset()
ws.cells.Interior.Color = RGB(300, 300, 300)
End Sub
Private Sub DirectionSnakeInitialize()
directionSnake = East
End Sub
Private Sub StartPositionInitalize()
currentRow = 96
currentColumn = 64
End Sub
Private Sub StartGameBoardInitalize()
Call SnakePartAdd(currentRow, currentColumn - 6)
Call SnakePartAdd(currentRow, currentColumn - 5)
Call SnakePartAdd(currentRow, currentColumn - 4)
Call SnakePartAdd(currentRow, currentColumn - 3)
Call SnakePartAdd(currentRow, currentColumn - 2)
Call SnakePartAdd(currentRow, currentColumn - 1)
Call SnakePartAdd(currentRow, currentColumn)
End Sub
Private Sub SnakePartAdd(ByVal row As Long, ByVal column As Long)
Dim SnakePartNew As snakepart
Set SnakePartNew = New snakepart
SnakePartNew.PropertiesSet row, column
SnakePartAddToCollection SnakePartNew
SnakePartAddToGameBoard SnakePartNew
End Sub
Private Sub SnakePartAddToCollection(ByRef snakepart As snakepart)
snakeParts.add snakepart
End Sub
Private Sub SnakePartAddToGameBoard(ByRef snakepart As snakepart)
ws.cells(snakepart.row, snakepart.column).Interior.Color = RGB(0, 150, 0)
End Sub
Private Sub SnakePartRemove()
SnakePartRemoveFromGameBoard
SnakePartRemoveFromCollection
End Sub
Private Sub SnakePartRemoveFromCollection()
snakeParts.Remove 1
End Sub
Private Sub SnakePartRemoveFromGameBoard()
ws.cells(snakeParts.Item(1).row, snakeParts.Item(1).column).Interior.Color = RGB(300, 300, 300)
End Sub
Private Function OutOfBounds() As Boolean
If currentRow < 9 Or _
currentRow > 189 Or _
currentColumn < 21 Or _
currentColumn > 108 Then
OutOfBounds = True
MsgBox "GameOver"
Else
OutOfBounds = False
End If
End Function
Private Function SnakePartOverlapItself(ByVal row As Long, ByVal column As Long) As Boolean
If ws.cells(row, column).Interior.Color = RGB(0, 150, 0) Then
MsgBox "GameOver"
SnakePartOverlapItself = True
Else
SnakePartOverlapItself = False
End If
End Function
Private Sub BlueSquareAdd()
Dim TopLeftCornerRow As Long
Dim TopLeftCornerColumn As Long
TopLeftCornerRow = Application.WorksheetFunction.RandBetween(9, 189)
TopLeftCornerColumn = Application.WorksheetFunction.RandBetween(21, 108)
ws.cells(TopLeftCornerRow, TopLeftCornerColumn).Interior.Color = RGB(0, 0, 150)
ws.cells(TopLeftCornerRow, TopLeftCornerColumn + 1).Interior.Color = RGB(0, 0, 150)
ws.cells(TopLeftCornerRow + 1, TopLeftCornerColumn).Interior.Color = RGB(0, 0, 150)
ws.cells(TopLeftCornerRow + 1, TopLeftCornerColumn + 1).Interior.Color = RGB(0, 0, 150)
End Sub
Private Function SnakePartBlueSquareOverlap() As Boolean
If ws.cells(currentRow, currentColumn).Interior.Color = RGB(0, 0, 150) Then
SnakePartBlueSquareOverlap = True
Else
SnakePartBlueSquareOverlap = False
End If
End Function
Private Sub YellowSquareAdd()
Dim TopLeftCornerRow As Long
Dim TopLeftCornerColumn As Long
TopLeftCornerRow = Application.WorksheetFunction.RandBetween(9, 189)
TopLeftCornerColumn = Application.WorksheetFunction.RandBetween(21, 108)
ws.cells(TopLeftCornerRow, TopLeftCornerColumn).Interior.Color = RGB(255, 140, 0)
ws.cells(TopLeftCornerRow, TopLeftCornerColumn + 1).Interior.Color = RGB(255, 140, 0)
ws.cells(TopLeftCornerRow + 1, TopLeftCornerColumn).Interior.Color = RGB(255, 140, 0)
ws.cells(TopLeftCornerRow + 1, TopLeftCornerColumn + 1).Interior.Color = RGB(255, 140, 0)
End Sub
Private Function SnakePartYellowSquareOverlap() As Boolean
If ws.cells(currentRow, currentColumn).Interior.Color = RGB(255, 140, 0) Then
MsgBox "GameOver"
SnakePartYellowSquareOverlap = True
Else
SnakePartYellowSquareOverlap = False
End If
End Function
Private Sub CurrentCellUpdate()
Select Case directionSnake
Case Is = Direction.North
currentRow = currentRow - 1
Case Is = Direction.South
currentRow = currentRow + 1
Case Is = Direction.East
currentColumn = currentColumn + 1
Case Is = Direction.West
currentColumn = currentColumn - 1
End Select
End Sub
Private Sub SnakeCollectionUpdate(ByRef snakeParts As Collection)
snakeParts.add currentRow
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'rowSwitch
If directionSnake = East Or directionSnake = West Then
If Target.column = currentColumn Then
If Target.row <> currentRow Then
If Target.row = currentRow - 1 Then
directionSnake = North
ElseIf Target.row = currentRow + 1 Then
directionSnake = South
End If
End If
End If
End If
'columnSwitch
If directionSnake = North Or directionSnake = South Then
If Target.row = currentRow Then
If Target.column <> currentColumn Then
If Target.column = currentColumn + 1 Then
directionSnake = East
ElseIf Target.column = currentColumn - 1 Then
directionSnake = West
End If
End If
End If
End If
End Sub
</code></pre>
| [] | [
{
"body": "<p>I could take this as a not-so-subtle reminder that I need to finish my Excel Tetris implementation... :-P</p>\n\n<p>I am a little curious why you seem to have abandoned the OOP approach since your last game - this code is completely procedural (the presence of classes doesn't mean that it's object oriented).</p>\n\n<p>A discussion of the architecture would basically entail a top-down re-write, so I'll leave that for other reviewers.</p>\n\n<hr>\n\n<h2>Indentation</h2>\n\n<p>This is, well, ...weird. I initially thought it was simply a markdown problem in the question itself, but as I went through the code further, it seems more and more intentional. Why are your procedures creeping to the right? I originally thought that it had something to do with the scope, (<code>Public</code> members indented one level, <code>Private</code> two), but that doesn't jive with this:</p>\n\n<blockquote>\n<pre><code>Private this As TimerAttributes\n\n Private Sub Class_Initialize()\n PerformanceFrequencyLet\n End Sub\n\n Private Sub PerformanceFrequencyLet()\n Dim TempFrequency As LongInteger\n QueryPerformanceFrequency TempFrequency\n this.PerformanceFrequency = ParseLongInteger(TempFrequency)\n End Sub\n\n Public Sub TimerSet()\n Dim TempCounterIntital As LongInteger\n QueryPerformanceCounter TempCounterIntital\n this.CounterInitial = ParseLongInteger(TempCounterIntital)\n End Sub\n</code></pre>\n</blockquote>\n\n<p>This is incredibly distracting, and is completely \"non-standard\" (I've never seen this done in <strong><em>any</em></strong> language). The last thing you want when somebody else is looking at your code is to distract them with the formatting. It's also generally meaningless in that I can just look at the access modifier (assuming it has something to do with scope). My brain is telling me that I'm in a procedure when I'm not, and it was disorienting to the point that I had to run an indenter on this before I continued the review.</p>\n\n<hr>\n\n<h2>API Functions</h2>\n\n<p>Your declarations of <code>QueryPerformanceCounter</code> and <code>QueryPerformanceFrequency</code> are incorrect. From the documentation of <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms644904(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>QueryPerformanceCounter</code></a>, it is defined as:</p>\n\n<pre><code>BOOL WINAPI QueryPerformanceCounter(\n _Out_ LARGE_INTEGER *lpPerformanceCount\n);\n</code></pre>\n\n<p>Furthermore, the documentation states \"On systems that run Windows XP or later, the function will always succeed and will thus never return zero\", so unless you are intending to support pre-XP versions of Windows (which would likely require a pre-compile directive to get rid of the <code>PtrSafe</code> keyword anyway), this can simply be declared as a <code>Sub</code>. The same applies to <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>QueryPerformanceFrequency</code></a>:</p>\n\n<pre><code>BOOL WINAPI QueryPerformanceFrequency(\n _Out_ LARGE_INTEGER *lpFrequency\n);\n</code></pre>\n\n<p>You are also never checking the return value <em>anyway</em>, so if you're using them as <code>Sub</code>'s (discarding the otherwise deterministic return value), declare them as a <code>Sub</code>'s:</p>\n\n<pre><code>Private Declare PtrSafe Sub QueryPerformanceCounter Lib \"kernel32\" (ByRef lpPerformanceCount As LongInteger)\nPrivate Declare PtrSafe Sub QueryPerformanceFrequency Lib \"kernel32\" (ByRef lpFrequency As LongInteger)\n</code></pre>\n\n<p>Note that I've also explicitly declared the parameters <code>ByRef</code>. I'd get in the habit of doing this for out parameters of API declarations because it makes the usage clear without consulting the documentation.</p>\n\n<hr>\n\n<p>Your <code>LongInteger</code> struct is also misleadingly named, in that a \"long int\" has a different meaning when you're thinking in API terms. It means \"<em>at least</em> 32 bits\". This is why the <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_large_integer\" rel=\"nofollow noreferrer\"><code>LARGE_INTEGER</code></a> struct exists (it's technically a union). I'd use the API naming and simply call it a <code>LargeInteger</code> to avoid confusion. I'll propose what I'd consider a better option below.</p>\n\n<hr>\n\n<p>The <code>ParseLongInteger</code> function performs so much work to handle the unsigned low DWORD that makes me wonder if it's really worth using at all for the additional resolution that it provides. The maximum resolution you <em>require</em> is quarter-second accuracy. On top of that, you're performing a fairly dirty cast when you coerce the value into a <code>Double</code> in order to handle the return value on a 32-bit machine (it's a simple <code>LongLong</code> in 64-bit Office). If you intend to support both platforms, I'd suggest going simple and using <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/sysinfoapi/nf-sysinfoapi-gettickcount\" rel=\"nofollow noreferrer\"><code>GetTickCount</code></a> and <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/sysinfoapi/nf-sysinfoapi-gettickcount64\" rel=\"nofollow noreferrer\"><code>GetTickCount64</code></a> (conditionally compiled) instead. Or, you could use a game loop similar to what I suggested on <a href=\"https://codereview.stackexchange.com/a/203218/36565\">your Space Invader Style Game question</a>.</p>\n\n<hr>\n\n<h2>Procedure Signatures</h2>\n\n<p>You have functions with no return values, such as this one:</p>\n\n<pre><code>Private Function CounterNowLet()\n Dim TempTimeNow As LongInteger\n QueryPerformanceCounter TempTimeNow\n this.CounterNow = ParseLongInteger(TempTimeNow)\nEnd Function\n</code></pre>\n\n<p>This always returns <code>Empty</code>, and the \"return value\" is never checked. You're using it like it's a <code>Sub</code>, so declare it as a <code>Sub</code>. As it stands now, it appears to be a bug even though it isn't.</p>\n\n<hr>\n\n<p><code>Sub RunGame()</code> is missing an access modifier. You have them explicitly defined elsewhere, and this is implicitly public. Make it explicit.</p>\n\n<hr>\n\n<p>You're requiring passing module level variables around as arguments all over the place in the worksheet, i.e.</p>\n\n<pre><code>Private Function SnakePartOverlapItself(ByVal row As Long, ByVal column As Long) As Boolean\n</code></pre>\n\n<p>...which is <strong><em>always</em></strong> called with the arguments <code>currentRow</code> and <code>currentColumn</code> - both of which are module level. They can be omitted entirely.</p>\n\n<hr>\n\n<h2>Scope</h2>\n\n<p><code>Direction</code> is not used outside of the worksheet it's declared in (more on that below). It also has no meaning outside of the context of the game and uses a very common word for an identifier - it's not hard to imagine a bunch of other ways it could potentially be used in other projects. Make it <code>Private</code> so it can't create namespace conflicts in no-owned code. In general, you should be declaring things with the smallest possible scope.</p>\n\n<hr>\n\n<p>There is absolutely no reason for these members of the worksheet to be <code>Public</code>:</p>\n\n<pre><code>Public ws As Worksheet\nPublic snakeParts As Collection\nPublic currentRow As Long\nPublic currentColumn As Long\nPublic directionSnake As Direction\n</code></pre>\n\n<p>If they need to be used like class members, make them <code>Private</code> - as it stands now they break encapsulation. </p>\n\n<hr>\n\n<h2>Miscellaneous</h2>\n\n<p>This is a run-time error waiting to happen:</p>\n\n<blockquote>\n<pre><code>Set ws = ActiveWorkbook.Sheets(\"Game\")\n</code></pre>\n</blockquote>\n\n<p>What if the active workbook doesn't contain a worksheet named \"Game\"? What if it contains a chart named \"Game\"? I'd either get rid of this entirely and use the code name of the sheet explicitly <em>or</em> (more likely for this purpose) just create a new worksheet for the game to run on with the understanding that the user will just delete it afterward.</p>\n\n<p>This code likely doesn't belong in a worksheet at all - it looks like it wants to be in its own class with a single public <code>RunGame(target As Worksheet)</code> method. I suspect that it's currently in a worksheet because of the <code>Worksheet_SelectionChange</code> handler, but there's nothing that says a user class can't hold a <code>Worksheet</code> member <code>WithEvents</code>.</p>\n\n<hr>\n\n<p>This is a meaningless assignment:</p>\n\n<blockquote>\n<pre><code>Dim gameOver As Boolean\ngameOver = False\n</code></pre>\n</blockquote>\n\n<p>The default value of a <code>Boolean</code> is <code>False</code>.</p>\n\n<hr>\n\n<p><code>Range.Select</code> should <strong><em>never</em></strong> be used in a loop that calls <code>DoEvents</code> without checking the <code>ActiveWorkbook</code>. If the intention is that it should re-focus the game worksheet if the user selects something else (like sets focus to a different worksheet or workbook), you should handle that with an event handler. If another workbook becomes active, this is pretty much an instant error 1004.</p>\n\n<hr>\n\n<p>The <code>Call</code> keyword is ancient history (and only exists for backward compatibility), and you're using it inconsistently. There is no reason to use it at all, so I'd recommend getting rid of it.</p>\n\n<hr>\n\n<p><code>snakepart</code> might <em>call itself</em> a class, but it's really just a glorified <code>Type</code> used to hold two dimensional coordinates. I'd consider re-architecting this to just store the entire game state in a two dimensional array.</p>\n\n<hr>\n\n<p>The calls to <code>MsgBox \"GameOver\"</code> belong in the <code>RunGame()</code> method instead of sprinkled all over the tests for game ending conditions. Just put a single call after your loop exits - there's no other way to exit the loop, so that seems like the more logical place for it.</p>\n\n<hr>\n\n<p>Related to the above, your flow control within the loop is kind of contorted. Your exit condition is <code>Do While gameOver = False</code>, and you have multiple checks for that condition here:</p>\n\n<blockquote>\n<pre><code> If SnakePartOverlapItself(currentRow, currentColumn) = True Then\n gameOver = True\n Exit Do\n ElseIf SnakePartYellowSquareOverlap = True Then\n gameOver = True\n Exit Do\n</code></pre>\n</blockquote>\n\n<p>So, you're testing for <code>True</code>, then setting your exit flag to <code>True</code>, then explicitly exiting the loop with <code>Exit Do</code>. </p>\n\n<p>I'm also struggling to see the need for 3 separate game timers - they are always initialized one right after the other, so they should only be milliseconds apart (unless you're stepping through with the debugger). The entire loop could be simplified to something more like this:</p>\n\n<pre><code>Do\n If TimerGame.CheckFiveSecondsPassed Then\n BlueSquareAdd\n YellowSquareAdd\n End If\n\n If TimerGame.CheckQuarterSecondPassed Then\n CurrentCellUpdate\n ws.Cells(currentRow, currentColumn).Select\n\n Dim part As Long\n For part = 1 To IIf(SnakePartBlueSquareOverlap, 3, 1)\n SnakePartAdd\n Next\n\n SnakePartRemove\n ws.Cells(currentRow, currentColumn).Select\n TimerGame.TimerSet\n End If\n\n DoEvents\nLoop Until SnakePartOverlapItself Or SnakePartYellowSquareOverlap Or OutOfBounds\n\nMsgBox \"Game Over\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T03:31:01.640",
"Id": "415132",
"Score": "0",
"body": "really appreciate it! going through it now. sometimes things take a passes to stick. thank you for taking time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T03:35:05.300",
"Id": "415133",
"Score": "0",
"body": "i knew that call was not used anymore, but when i take call away from well call to sub SnakePartAdd I get an error message, the IDE expects a return value? maybe a bug?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T03:37:48.537",
"Id": "415134",
"Score": "0",
"body": "laughed at various points during review. a lot of my code is cringe. but wanted to throw something together. next iteration will be PRO. :-p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T03:40:36.527",
"Id": "415136",
"Score": "0",
"body": "@learnAsWeGo - If you remove the `Call` keyword, you also need to remove the parens. That's why you're getting compile errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T03:46:51.047",
"Id": "415137",
"Score": "0",
"body": "-lets out homer simpson doh noise-"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T03:52:30.687",
"Id": "415139",
"Score": "0",
"body": "OK i see now, array rather than collection. private type rather than class. think for a game like this procedural works better. may switch from using worksheet select, activate cell etc to aysnchkeystate calls. want to add sound too!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T03:57:25.187",
"Id": "415140",
"Score": "1",
"body": "LOL - looking forward to seeing your sound implementation. Just do the world a favor and don't use the [`Beep` statement](https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/beep-statement)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T20:57:53.760",
"Id": "214666",
"ParentId": "214630",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "214666",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T06:05:40.230",
"Id": "214630",
"Score": "6",
"Tags": [
"beginner",
"game",
"vba",
"excel"
],
"Title": "Snake Game - within worksheet - cells as pixels"
} | 214630 |
<p><strong>Context:</strong></p>
<p>I have some C code that uses a lot of bit-flags. The flag-sets may have a couple of hundred members. Currently these flags are defined as a 32-bit mask that must be applied to a specific element.</p>
<pre><code>/* Flags: */
#define OF1_RESIST_FIRE 0x00000001L
#define OF1_RESIST_COLD 0x00000002L
#define OF1_RESIST_ACID 0x00000004L
...
#define OF2_SUSTAIN_STRENGTH 0x00000001L
...
#define OF9_AGGRAVATES_CATS 0x00000004L
/* Bitset: */
uint32_t oflags1;
uint32_t oflags2;
...
</code></pre>
<p>To make this easier to manage, I'm hoping to change the flags to be defined as bit indices instead, and consolidate the flags into an array, e.g.:</p>
<pre><code>/* Flags: */
enum object_flags {
RESIST_FIRE,
RESIST_COLD,
RESIST_ACID,
...
SUSTAIN_STRENGTH,
...
AGGRAVATES_CATS,
...
MAX_OBJECT_FLAGS,
};
/* Bitset: */
BITSET_DECLARE(oflags, MAX_OBJECT_FLAGS); // uint32_t oflags[9];
</code></pre>
<p>(note: above code is illustrative for context, not for review).</p>
<hr>
<p><strong>Code:</strong></p>
<p>For this purpose, I've created some macros to help manipulate the bitset array, based on <a href="http://c-faq.com/misc/bitsets.html" rel="nofollow noreferrer">this comp.lang.c faq item</a> (<em>bflags.h</em>):</p>
<pre><code>#pragma once
#include <stdint.h>
#include <limits.h>
/*
* Macros to simplify creating and using bit flags.
*
* Flags are stored in an array of uint32_t, the size of which
* is determined by the required number of bits.
*
* Any bits after the required size may change during operation.
*/
/* The underlying type of the array */
#define BFLAGS_WORD_T uint32_t
/* The number of bits in the underlying type */
#define BFLAGS_WORD_BIT_SIZE (sizeof(BFLAGS_WORD_T) * CHAR_BIT)
/* The number of elements in the array */
#define BFLAGS_ARRAY_SIZE(bits) \
(((bits) + BFLAGS_WORD_BIT_SIZE - 1) / BFLAGS_WORD_BIT_SIZE)
/* Get the array element containing this bit */
#define BFLAGS_WORD_INDEX(bit) ((bit) / BFLAGS_WORD_BIT_SIZE)
/* Create a mask for this bit in the array element that contains it */
#define BFLAGS_WORD_MASK(bit) (1 << ((bit) % BFLAGS_WORD_BIT_SIZE))
/* Declare a bit flag array containing enough elements to
* store the requested number of bits. */
#define BFLAGS_DECLARE(bflags, bits) \
BFLAGS_WORD_T bflags[BFLAGS_ARRAY_SIZE(bits)]
/* As BFLAGS_DECLARE, but also zeros the array contents.
* Prefer to use this where possible. */
#define BFLAGS_DECLARE_ZERO(bflags, bits) \
BFLAGS_WORD_T bflags[BFLAGS_ARRAY_SIZE(bits)] = { 0 }
/* Set all bits in the array to 0 */
#define BFLAGS_ZERO(bflags, bits) \
do { \
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(bits); ++i) \
(bflags)[i] = (BFLAGS_WORD_T)0; \
} while (false)
/* Set all bits in the array to 1 */
#define BFLAGS_FILL(bflags, bits) \
do { \
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(bits); ++i) \
(bflags)[i] = ~(BFLAGS_WORD_T)0; \
} while (false)
/* Copy to another array */
#define BFLAGS_COPY(bflags_out, bflags_a, bits) \
do { \
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(bits); ++i) \
(bflags_out)[i] = (bflags_a)[i]; \
} while (false)
/* Test two arrays for equality.
* Bits of the last array element may differ after the last bit
* so we mask them out before comparing. */
#define BFLAGS_EQ(eq_out, bflags_a, bflags_b, bits) \
do { \
eq_out = true; \
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(bits) - 1; ++i) \
eq_out &= ((bflags_a)[i] == (bflags_b)[i]); \
BFLAGS_WORD_T mask = (~(BFLAGS_WORD_T)0) >> ((BFLAGS_WORD_BIT_SIZE - ((bits) % BFLAGS_WORD_BIT_SIZE)) % BFLAGS_WORD_BIT_SIZE); \
eq_out &= (((bflags_a)[BFLAGS_ARRAY_SIZE(bits) - 1] & mask) == ((bflags_b)[BFLAGS_ARRAY_SIZE(bits) - 1] & mask)); \
} while (false)
/* Set the specified bit to 1 */
#define BFLAGS_SET(bflags, bit) ((bflags)[BFLAGS_WORD_INDEX(bit)] |= BFLAGS_WORD_MASK(bit))
/* Set the specified bit to 0 */
#define BFLAGS_CLEAR(bflags, bit) ((bflags)[BFLAGS_WORD_INDEX(bit)] &= ~BFLAGS_WORD_MASK(bit))
/* Toggle the specified bit */
#define BFLAGS_FLIP(bflags, bit) ((bflags)[BFLAGS_WORD_INDEX(bit)] ^= BFLAGS_WORD_MASK(bit))
/* Check the value of the specified bit */
#define BFLAGS_TEST(bflags, bit) (((bflags)[BFLAGS_WORD_INDEX(bit)] & BFLAGS_WORD_MASK(bit)) != 0)
/* Do a bitwise-and of the specified bit flag arrays and put the result
* in bflags_out. All the flag sets should contain the same number of bits. */
#define BFLAGS_AND(bflags_out, bflags_a, bflags_b, bits) \
do { \
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(bits); ++i) \
(bflags_out)[i] = (bflags_a)[i] & (bflags_b)[i]; \
} while (false)
/* Do a bitwise-or of the specified bit flag arrays and put the result
* in bflags_out. All the flag sets should contain the same number of bits. */
#define BFLAGS_OR(bflags_out, bflags_a, bflags_b, bits) \
do { \
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(bits); ++i) \
(bflags_out)[i] = (bflags_a)[i] | (bflags_b)[i]; \
} while (false)
/* Do a bitwise-xor of the specified bit flag arrays and put the result
* in bflags_out. All the flag sets should contain the same number of bits. */
#define BFLAGS_XOR(bflags_out, bflags_a, bflags_b, bits) \
do { \
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(bits); ++i) \
(bflags_out)[i] = (bflags_a)[i] ^ (bflags_b)[i]; \
} while (false)
/* Do a bitwise-not of the specified bit flag array and put the result
* in bflags_out. Both the flag sets should contain the same number of bits. */
#define BFLAGS_NOT(bflags_out, bflags_a, bits) \
do { \
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(bits); ++i) \
(bflags_out)[i] = ~(bflags_a)[i]; \
} while (false)
</code></pre>
<p>Any feedback is welcome, but especially about:</p>
<ul>
<li>Macro safety (missing parentheses? extra parentheses? anything else?)</li>
<li>Is there perhaps a way to "return" the result of <code>BFLAGS_EQ</code> from the macro, instead of passing it in?</li>
</ul>
<p>Unit tests:</p>
<pre><code>#include "bflags.h"
#include <assert.h>
#include <stdio.h>
#include <stdbool.h>
#define UNUSED(x) __attribute((unused)) x
#define mu_assert(test) do { if (!(test)) return #test; } while (0)
#define mu_run_test(test) do { char *message = test(); tests_run++; if (message) return message; } while (0)
extern int tests_run;
static char* bflags_test_declare()
{
{
//BFLAGS_DECLARE(bflags, 0); // won't compile (size 0 array)
}
{
BFLAGS_DECLARE(bflags, 1);
static_assert(sizeof(bflags) / sizeof(bflags[0]) == 1, "");
}
{
BFLAGS_DECLARE(bflags, 32);
static_assert(sizeof(bflags) / sizeof(bflags[0]) == 1, "");
}
{
BFLAGS_DECLARE(bflags, 33);
static_assert(sizeof(bflags) / sizeof(bflags[0]) == 2, "");
}
return NULL;
}
static char* bflags_test_declare_zero()
{
{
BFLAGS_DECLARE_ZERO(bflags, 1);
mu_assert(bflags[0] == 0);
}
{
BFLAGS_DECLARE_ZERO(bflags, 320);
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(320); ++i)
mu_assert(bflags[i] == 0);
}
return NULL;
}
static char* bflags_zero()
{
{
BFLAGS_DECLARE(bflags, 32);
bflags[0] = 0xffffffff;
BFLAGS_ZERO(bflags, 32);
mu_assert(bflags[0] == 0);
}
{
BFLAGS_DECLARE(bflags, 321);
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(321); ++i)
bflags[i] = (BFLAGS_WORD_T)i;
mu_assert(bflags[1] == 1);
BFLAGS_ZERO(bflags, 321);
for (size_t i = 0; i != BFLAGS_ARRAY_SIZE(321); ++i)
mu_assert(bflags[i] == 0);
}
return NULL;
}
static char* bflags_fill()
{
{
BFLAGS_DECLARE_ZERO(bflags, 32);
BFLAGS_FILL(bflags, 32);
mu_assert(bflags[0] == 0xffffffff);
}
{
BFLAGS_DECLARE_ZERO(bflags, 35);
BFLAGS_FILL(bflags, 35);
mu_assert(bflags[0] == 0xffffffff);
// values above bit size are also set, but we shouldn't depend on it!
for (size_t i = 0; i != 35; ++i)
mu_assert(BFLAGS_TEST(bflags, i) != 0);
}
return NULL;
}
static char* bflags_copy()
{
{
BFLAGS_DECLARE_ZERO(bflags_a, 59);
for (size_t i = 0; i != 59; ++i)
if (i % 6 == 0)
BFLAGS_SET(bflags_a, i);
BFLAGS_DECLARE_ZERO(bflags_b, 59);
BFLAGS_COPY(bflags_b, bflags_a, 59);
for (size_t i = 0; i != 59; ++i)
if (i % 6 == 0)
mu_assert(BFLAGS_TEST(bflags_b, i));
else
mu_assert(!BFLAGS_TEST(bflags_b, i));
}
return NULL;
}
static char* bflags_eq()
{
{
BFLAGS_DECLARE_ZERO(bflags_a, 32);
BFLAGS_DECLARE_ZERO(bflags_b, 32);
{
bool eq = false;
BFLAGS_EQ(eq, bflags_a, bflags_b, 32);
mu_assert(eq);
}
BFLAGS_SET(bflags_a, 25);
{
bool eq = false;
BFLAGS_EQ(eq, bflags_a, bflags_b, 32);
mu_assert(!eq);
}
}
{
BFLAGS_DECLARE_ZERO(bflags_a, 59);
for (size_t i = 0; i != 59; ++i)
if (i % 6 == 0)
BFLAGS_SET(bflags_a, i);
BFLAGS_DECLARE_ZERO(bflags_b, 59);
BFLAGS_COPY(bflags_b, bflags_a, 59);
{
bool eq = false;
BFLAGS_EQ(eq, bflags_a, bflags_b, 59);
mu_assert(eq);
}
BFLAGS_SET(bflags_a, 60); // set a bit after the end...
{
bool eq = false;
BFLAGS_EQ(eq, bflags_a, bflags_b, 59);
mu_assert(eq);
}
}
return NULL;
}
static char* bflags_set()
{
{
BFLAGS_DECLARE_ZERO(bflags, 32);
BFLAGS_SET(bflags, 0);
mu_assert(bflags[0] == (1 << 0));
BFLAGS_SET(bflags, 5);
mu_assert(bflags[0] == ((1 << 0) | (1 << 5)));
BFLAGS_SET(bflags, 31);
mu_assert(bflags[0] == ((1 << 0) | (1 << 5) | (1 << 31)));
}
{
BFLAGS_DECLARE_ZERO(bflags, 64);
BFLAGS_SET(bflags, 0);
mu_assert(bflags[0] == (1 << 0));
BFLAGS_SET(bflags, 63);
mu_assert(bflags[1] == (1 << 31));
}
{
BFLAGS_DECLARE_ZERO(bflags, 32);
BFLAGS_SET(bflags, 12);
mu_assert(bflags[0] == (1 << 12));
BFLAGS_SET(bflags, 12);
mu_assert(bflags[0] == (1 << 12));
}
return NULL;
}
static char* bflags_clear()
{
{
BFLAGS_DECLARE_ZERO(bflags, 32);
BFLAGS_FILL(bflags, 32);
BFLAGS_CLEAR(bflags, 5);
mu_assert(bflags[0] == ~(1 << 5));
BFLAGS_CLEAR(bflags, 0);
mu_assert(bflags[0] == ~((1 << 0) | (1 << 5)));
}
{
BFLAGS_DECLARE_ZERO(bflags, 35);
BFLAGS_FILL(bflags, 35);
mu_assert(BFLAGS_TEST(bflags, 31));
mu_assert(BFLAGS_TEST(bflags, 32));
BFLAGS_CLEAR(bflags, 32);
mu_assert(!BFLAGS_TEST(bflags, 32));
mu_assert(bflags[0] == ~(BFLAGS_WORD_T)0);
BFLAGS_CLEAR(bflags, 33);
mu_assert(!BFLAGS_TEST(bflags, 33));
mu_assert(bflags[0] == ~(BFLAGS_WORD_T)0);
}
{
BFLAGS_DECLARE_ZERO(bflags, 32);
BFLAGS_FILL(bflags, 32);
BFLAGS_CLEAR(bflags, 16);
mu_assert(bflags[0] == ~(1 << 16));
BFLAGS_CLEAR(bflags, 16);
mu_assert(!BFLAGS_TEST(bflags, 16));
}
return NULL;
}
static char* bflags_flip()
{
{
BFLAGS_DECLARE_ZERO(bflags, 32);
BFLAGS_FLIP(bflags, 13);
mu_assert(bflags[0] == (1 << 13));
BFLAGS_FLIP(bflags, 13);
mu_assert(bflags[0] == 0);
}
{
BFLAGS_DECLARE_ZERO(bflags, 72);
BFLAGS_FLIP(bflags, 68);
mu_assert(bflags[0] == 0 && bflags[1] == 0);
mu_assert(BFLAGS_TEST(bflags, 68));
}
return NULL;
}
static char* bflags_test()
{
{
BFLAGS_DECLARE_ZERO(bflags, 128);
mu_assert(!BFLAGS_TEST(bflags, 53));
mu_assert(!BFLAGS_TEST(bflags, 125));
BFLAGS_FLIP(bflags, 53);
BFLAGS_FLIP(bflags, 125);
mu_assert(BFLAGS_TEST(bflags, 53));
mu_assert(BFLAGS_TEST(bflags, 125));
}
return NULL;
}
static char* bflags_and()
{
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_b, 64);
BFLAGS_DECLARE_ZERO(bflags_c, 64);
BFLAGS_FILL(bflags_a, 64);
BFLAGS_AND(bflags_c, bflags_a, bflags_b, 64);
for (size_t i = 0; i != 64; ++i)
mu_assert(!BFLAGS_TEST(bflags_c, i));
}
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_c, 64);
BFLAGS_FILL(bflags_a, 64);
BFLAGS_AND(bflags_c, bflags_a, bflags_a, 64);
for (size_t i = 0; i != 64; ++i)
mu_assert(BFLAGS_TEST(bflags_c, i));
}
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_b, 64);
BFLAGS_DECLARE_ZERO(bflags_c, 64);
for (size_t i = 0; i != 64; ++i)
if (i % 2 == 0)
BFLAGS_SET(bflags_a, i);
for (size_t i = 0; i != 64; ++i)
if (i % 2 != 0)
BFLAGS_SET(bflags_b, i);
BFLAGS_AND(bflags_c, bflags_a, bflags_b, 64);
for (size_t i = 0; i != 64; ++i)
mu_assert(!BFLAGS_TEST(bflags_c, i));
}
return NULL;
}
static char* bflags_or()
{
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_b, 64);
BFLAGS_DECLARE_ZERO(bflags_c, 64);
BFLAGS_FILL(bflags_a, 64);
BFLAGS_OR(bflags_c, bflags_a, bflags_b, 64);
for (size_t i = 0; i != 64; ++i)
mu_assert(BFLAGS_TEST(bflags_c, i));
}
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_c, 64);
BFLAGS_FILL(bflags_a, 64);
BFLAGS_OR(bflags_c, bflags_a, bflags_a, 64);
for (size_t i = 0; i != 64; ++i)
mu_assert(BFLAGS_TEST(bflags_c, i));
}
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_b, 64);
BFLAGS_DECLARE_ZERO(bflags_c, 64);
for (size_t i = 0; i != 64; ++i)
if (i % 2 == 0)
BFLAGS_SET(bflags_a, i);
for (size_t i = 0; i != 64; ++i)
if (i % 2 != 0)
BFLAGS_SET(bflags_b, i);
BFLAGS_OR(bflags_c, bflags_a, bflags_b, 64);
for (size_t i = 0; i != 64; ++i)
mu_assert(BFLAGS_TEST(bflags_c, i));
}
return NULL;
}
static char* bflags_xor()
{
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_b, 64);
BFLAGS_DECLARE_ZERO(bflags_c, 64);
BFLAGS_FILL(bflags_a, 64);
BFLAGS_XOR(bflags_c, bflags_a, bflags_b, 64);
for (size_t i = 0; i != 64; ++i)
mu_assert(BFLAGS_TEST(bflags_c, i));
}
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_c, 64);
BFLAGS_FILL(bflags_a, 64);
BFLAGS_XOR(bflags_c, bflags_a, bflags_a, 64);
for (size_t i = 0; i != 64; ++i)
mu_assert(!BFLAGS_TEST(bflags_c, i));
}
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_b, 64);
BFLAGS_DECLARE_ZERO(bflags_c, 64);
for (size_t i = 0; i != 64; ++i)
if (i % 2 == 0)
BFLAGS_SET(bflags_a, i);
for (size_t i = 0; i != 64; ++i)
if (i % 2 != 0)
BFLAGS_SET(bflags_b, i);
BFLAGS_XOR(bflags_c, bflags_a, bflags_b, 64);
for (size_t i = 0; i != 64; ++i)
mu_assert(BFLAGS_TEST(bflags_c, i));
}
return NULL;
}
static char* bflags_not()
{
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
BFLAGS_DECLARE_ZERO(bflags_b, 64);
for (size_t i = 0; i != 64; ++i)
if (i % 2 == 0)
BFLAGS_SET(bflags_a, i);
BFLAGS_NOT(bflags_b, bflags_a, 64);
for (size_t i = 0; i != 64; ++i)
if (i % 2 == 0)
mu_assert(!BFLAGS_TEST(bflags_b, i));
else
mu_assert(BFLAGS_TEST(bflags_b, i));
}
{
BFLAGS_DECLARE_ZERO(bflags_a, 64);
for (size_t i = 0; i != 64; ++i)
if (i % 2 == 0)
BFLAGS_SET(bflags_a, i);
BFLAGS_NOT(bflags_a, bflags_a, 64);
for (size_t i = 0; i != 64; ++i)
if (i % 2 == 0)
mu_assert(!BFLAGS_TEST(bflags_a, i));
else
mu_assert(BFLAGS_TEST(bflags_a, i));
}
return NULL;
}
static char* run_all_tests()
{
mu_run_test(bflags_test_declare);
mu_run_test(bflags_test_declare_zero);
mu_run_test(bflags_zero);
mu_run_test(bflags_fill);
mu_run_test(bflags_copy);
mu_run_test(bflags_eq);
mu_run_test(bflags_set);
mu_run_test(bflags_clear);
mu_run_test(bflags_flip);
mu_run_test(bflags_test);
mu_run_test(bflags_and);
mu_run_test(bflags_or);
mu_run_test(bflags_xor);
mu_run_test(bflags_not);
return NULL;
}
int tests_run = 0;
int main(int UNUSED(argc), char** UNUSED(argv))
{
char* result = run_all_tests();
if (result)
printf("TEST FAILED: %s\n", result);
else
printf("PASS\n");
printf("\ndone! %d tests run\n", tests_run);
return (result != NULL);
}
</code></pre>
<p><a href="https://repl.it/@user673679/bflags" rel="nofollow noreferrer">An online version can be found here</a>.</p>
<p>Thanks!</p>
| [] | [
{
"body": "<p>Small portability bug: if we're using <code>false</code> in the macros, then <code>bflags.h</code> should include <code><stdbool.h></code>. Or use <code>0</code> instead of <code>false</code>.</p>\n\n<p>Definite portability bug: we shift a (signed) <code>int</code> before promoting:</p>\n\n<blockquote>\n<pre><code>#define BFLAGS_WORD_MASK(bit) (1 << ((bit) % BFLAGS_WORD_BIT_SIZE))\n</code></pre>\n</blockquote>\n\n<p>I think we need the <code>1</code> there to be of the appropriate type first:</p>\n\n<pre><code>#define BFLAGS_WORD_MASK(bit) ((BFLAGS_WORD_T)1 << ((bit) % BFLAGS_WORD_BIT_SIZE))\n</code></pre>\n\n<p>Similarly, this test:</p>\n\n<blockquote>\n<pre><code> BFLAGS_SET(bflags, 31);\n mu_assert(bflags[0] == ((1 << 0) | (1 << 5) | (1 << 31)));\n</code></pre>\n</blockquote>\n\n<p>needs</p>\n\n<pre><code> BFLAGS_SET(bflags, 31);\n mu_assert(bflags[0] == ((1 << 0) | (1 << 5) | (1ul << 31)));\n</code></pre>\n\n<p>There's quite a few more that I picked up with <code>gcc -Wall -Wextra</code> and are easily fixed.</p>\n\n<p>Also, let's be good about <code>const char*</code> - all the test results should be pointer to const string, and it doesn't hurt to fix that.</p>\n\n<p>The final compilation warning I see is from <code>char** UNUSED(argv)</code> - easily fixed by changing it to <code>UNUSED(char** argv)</code>. But since we're ignoring both arguments, we can use the other legal signature: <code>int main(void)</code>.</p>\n\n<hr>\n\n<p>Style-wise, we could use a <code>typedef</code> instead of #define for <code>BFLAGS_WORD_T</code>. Instead of the optional fixed-width type, we should probably use <code>uint_fast32_t</code>, as we don't really mind if <code>uint32_t</code> doesn't exist (on some exotic or ancient architecture). In fact, we might prefer plain <code>unsigned int</code>, as that's supposed to be the hardware's \"natural\" (most efficient) integer size. Everything in the code appears to adapt suitably, except for some of the tests that hard-code the 32-bit assumption.</p>\n\n<p>BTW, if using a typedef, remember that names ending in <code>_t</code> are reserved for the library.</p>\n\n<p>I do have reservations about the use of macros (rather than functions) when users may pass plain <code>int</code> rather than unsigned types as arguments - for example, we get unnecessary promotion in <code>BFLAGS_ARRAY_SIZE()</code> if we add a signed <code>bits</code> to unsigned <code>BFLAGS_WORD_BIT_SIZE</code>. Perhaps these should be simple (inlinable) functions to give us strong typing?</p>\n\n<hr>\n\n<p>We can reduce repetition here:</p>\n\n<blockquote>\n<pre><code>#define BFLAGS_DECLARE(bflags, bits) \\\n BFLAGS_WORD_T bflags[BFLAGS_ARRAY_SIZE(bits)]\n\n#define BFLAGS_DECLARE_ZERO(bflags, bits) \\\n BFLAGS_WORD_T bflags[BFLAGS_ARRAY_SIZE(bits)] = { 0 }\n</code></pre>\n</blockquote>\n\n<p>like this:</p>\n\n<pre><code>#define BFLAGS_DECLARE_ZERO(bflags, bits) \\\n BFLAGS_DECLARE(bflags, bits) = { 0 }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T12:22:39.347",
"Id": "214702",
"ParentId": "214634",
"Score": "5"
}
},
{
"body": "<p>Most severe issue:</p>\n\n<ul>\n<li><p>Never invent secret macro languages! This is about the single-worst thing a C programmer can ever do, all categories. </p>\n\n<p>You are perfectly free to assume that any C programmer will understand what <code>1<<bit</code> means. You cannot assume that they will understand what <code>BFLAGS_WORD_MASK</code> means. It's nothing but obfuscation of what would otherwise have been clear code.</p>\n\n<p>Therefore I would strongly recommend you to drop this whole idea. Many before you have tried this exact thing and it has always ended badly.</p></li>\n</ul>\n\n<p>Big picture issues:</p>\n\n<ul>\n<li><p><code>0x00000001L</code> creates a signed integer constant of type <code>long</code>. You should never use signed type for bitwise operations. Change this to <code>0x00000001UL</code>.</p>\n\n<p>The danger is that signed types may invoke undefined behavior bugs when sign bits are accidentally set. And there's almost never a reason to use bitwise operators on signed types.</p>\n\n<p>In addition, it is dangerous to type out all zeroes of hex constants, because they actually don't have any significance and don't make the number 32 bits as expected. You can get real nasty bugs this way. For example, lets say we have a 16 bit system and type this:</p>\n\n<pre><code>#define BLIP 0x00007FFF // this is type signed int 16 bit\n#define BLOP 0x00008000 // this is type unsigned int 16 bit\n#define BLUP 0x00010000 // this is type long 32 bit\n</code></pre>\n\n<p>You can get extremely subtle bugs this way. Been there, very hard to track down. Suffix all such hex constants with <code>UL</code>.</p></li>\n<li><p>For the same reason, enums should never be used for bitwise operations, because an enumeration constant is <em>always</em> <code>int</code> and the compiler cannot change the type without violating the C standard. Therefore you should not use enum for this.</p>\n\n<p>And you should not store <code>long</code> or <code>unsigned long</code> constants in an enum, because they will get converted to <code>int</code> which is wrong and bad.</p></li>\n</ul>\n\n<p>The above means your whole code must be rewritten from scratch.</p>\n\n<p>Other problems:</p>\n\n<ul>\n<li><p>Avoid bit-shifting <code>1</code> since it is of type <code>int</code> and can give the same problems as mentioned above. Use <code>1u</code> instead.</p></li>\n<li><p>Don't declare functions in C as <code>static char* bflags_or()</code> but use <code>static char* bflags_or (void)</code>. The empty parenthesis <code>()</code> means \"accept any type\", which is not what you want. This style has been flagged as obsolete in the C standard and can be removed at any point.</p></li>\n<li><p>There is no reason to use non-standard <code>int UNUSED(argc)</code>. Instead write this:</p>\n\n<pre><code>int main (int argc, char** argv)\n{\n (void)argc;\n (void)argv;\n</code></pre>\n\n<p>This is 100% portable and standard, achieving the same thing as non-standard UNUSED.</p></li>\n<li><p>Don't use non-standard <code>#pragma once</code>, use classic header guards <code>#ifndef SOMETHING_H #define SOMETHING_H ... #endif</code>. 100% portable and standard. Avoid pragmas in general.</p></li>\n</ul>\n\n<p>Style remarks:</p>\n\n<ul>\n<li>It is good practice to always use compound statements <code>{}</code> after <code>if</code> and loops, regardless of how many lines that the body contains. This reduces the amount of indention and maintenance related bugs. And as a bonus you don't have to use <code>do-while(0)</code> macro tricks any longer, if you don't allow selection/loop statements without <code>{}</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T13:14:50.017",
"Id": "215031",
"ParentId": "214634",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "214702",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T10:32:53.707",
"Id": "214634",
"Score": "4",
"Tags": [
"c",
"macros",
"bitset"
],
"Title": "Macros for bitsets / bit-flags in C"
} | 214634 |
<p>I have a price as a <code>Double</code>, which I should format it as a <code>String</code>.</p>
<p>Should I use an extension instead of classical class to encapsulate "formater", "serializers", etc? Or is there an even better alternative?</p>
<p><strong>Using Class</strong></p>
<pre><code>class PriceFormatter{
let value:Double
init(_ value:Double){
self.value = value
}
func format()->String{
let strValue = "\(value)"
let subStrings = strValue.split(separator: ".")
let money = subStrings[0]
var cents = "00"
if subStrings.count > 1{
cents = String(subStrings[1])
if(cents.count == 1){
cents = "0\(cents)"
}
}
return "$\(money).\(cents)"
}
}
</code></pre>
<p><strong>Using Extension</strong></p>
<pre><code>extension Double {
var priceFormatted:String{
let strValue = "\(self)"
let subStrings = strValue.split(separator: ".")
let money = subStrings[0]
var cents = "00"
if subStrings.count > 1{
cents = String(subStrings[1])
if(cents.count == 1){
cents = "0\(cents)"
}
}
return "$\(money).\(cents)"
}
}
</code></pre>
<p><strong>Implementation</strong></p>
<pre><code>let input:Double = 5.0
let priceFromClass = PriceFormatter(input).format()
let priceFromExtension = input.priceFormatted
</code></pre>
| [] | [
{
"body": "<h2>Correctness</h2>\n\n<ul>\n<li>Your code supposes that the decimal separator is <code>.</code>, which is not correct for all locales;</li>\n<li>You are ignoring the grouping separator for thousands and so on: <code>\"$1000000.00\"</code> instead of <code>\"$1,000,000.00\"</code>;</li>\n<li>Negative amounts are not well formatted: <code>\"$-100.00\"</code> instead of <code>\"-$100.00\"</code>;</li>\n<li><p>Other than being slow, String interpolation represents really large amounts using the scientific notation :</p>\n\n<pre><code>let input: Double = 10_000_000_000_000_000\n</code></pre></li>\n</ul>\n\n<p>Which would yield <code>\"$1e+16.00\"</code> but the right format is <code>\"$10,000,000,000,000,000.00\"</code> .</p>\n\n<h2>Alternative Solution</h2>\n\n<ul>\n<li>A <code>PriceFormatter</code> shouldn't own 1 value. Its job is to format, not be linked to a certain value. </li>\n<li>There is no need to pollute the <code>Double</code> type with that extension. A number is a number. </li>\n</ul>\n\n<p>Converting a number that represents an amount of money, in a certain currency, in a given locale, into a String, is the job of <code>NumberFormatter</code> :</p>\n\n<pre><code>let cf = NumberFormatter()\ncf.numberStyle = .currency\n</code></pre>\n\n<p>Other properties can be set to your liking :</p>\n\n<pre><code>cf.maximumFractionDigits = 2\ncf.minimumFractionDigits = 2\ncf.locale = Locale(identifier: \"en_US\")\ncf.decimalSeparator = \".\"\ncf.groupingSeparator = \",\"\n</code></pre>\n\n<p>And use it like so:</p>\n\n<pre><code>let input: Double = 100_000_000\n\nif let s = cf.string(for: input) {\n print(s) //$100,000,000.00\n}\n</code></pre>\n\n<p>To avoid creating new <code>NumberFormatter</code>s whenever you need them, you could define a static property on <code>NumberFormatter</code> or <code>Formatter</code> (since <code>string(for:)</code> is defined on <code>Formatter</code>) :</p>\n\n<pre><code>extension Formatter {\n static var currencyFormatter: NumberFormatter {\n let cf = NumberFormatter()\n cf.numberStyle = .currency\n return cf\n }\n}\n</code></pre>\n\n<p>And use it like so :</p>\n\n<pre><code>let str = Formatter.currencyFormatter.string(for: input)\n\nif let s = str {\n print(s) //$100,000,000.00\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T17:36:25.527",
"Id": "415365",
"Score": "1",
"body": "Thank you. Your explanation about Formatter was so helpfull, because that I will improve my question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T17:04:53.037",
"Id": "214655",
"ParentId": "214635",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>Should I use an extension instead of classical class to encapsulate \"formatter\", \"serializers\", etc? </p>\n</blockquote>\n\n<p>No, it should not be an extension to the numeric type. </p>\n\n<p>A couple of observations:</p>\n\n<ul>\n<li><p>This formatter should really work with a variety of types (<code>Double</code>, <code>Float</code>, <code>Decimal</code>, etc.), so burying it inside a particular numeric type’s definition isn’t right. Theoretically you could consider an extension to a protocol, e.g. <code>Numeric</code>, instead, but attaching it to a particular type is certainly not right.</p></li>\n<li><p>Formatters often have properties of their own. E.g. for a currency formatter, you’d probably have a locale for number formatting, currency symbol, preferred decimal places for that currency, etc., so that speaks to having the formatter as a type, itself, not just some computed property for the numeric type that is being displayed. It also affords the idea of having a single instance of a formatter that you use repeatedly for every underlying object that needs to be displayed.</p></li>\n<li><p>Note, once you realize that you’re likely to want to configure a formatter once and use it repeatedly, it no longer makes sense to make the value a property of this formatter type. It should be a parameter that we pass to our method for creating a string representation.</p></li>\n<li><p>By the way, formatters are not just “represent this object as a string”, but also “parse this string into an object” (and sometimes even “is this a valid substring for this type” which you might use to validate input as the user enters it). Once you consider formatters in this context, the notion of burying this in the underlying numeric types starts to run afoul of the “single responsibility principle”. A formatter is, effectively, an object for translating model objects to and from presentations in the UI.</p></li>\n<li><p>For all of the aforementioned reasons, Foundation has a long tradition of separating data types and their formatters. See <a href=\"https://developer.apple.com/documentation/foundation/formatter\" rel=\"nofollow noreferrer\"><code>Formatter</code></a>. And there are a <a href=\"https://developer.apple.com/documentation/foundation/data_formatting\" rel=\"nofollow noreferrer\">litany of existing formatters</a>. You should have a fairly compelling reason before deviating from this well established pattern.</p></li>\n<li><p>Needless to say, I wouldn’t advise writing your own currency formatter at all when there are existing formatters that do the job very well. As Apple says:</p>\n\n<blockquote>\n <p>Before you decide to create a custom formatter, make sure that you cannot configure the public subclasses to satisfy your requirements.</p>\n</blockquote>\n\n<p>I’d suggest just using <code>NumberFormatter</code> with a <code>numberStyle</code> of one of the currency types (e.g. <code>.currency</code>, <code>.currencyAccounting</code>, etc.).</p>\n\n<p>But I assume this is for illustrative purposes only.</p></li>\n<li><p>While your code snippet was a “formatter”, you mention serialization.</p>\n\n<p>That’s a different situation where you are often serializing objects with multiple properties of different types. And the serialization is often being handled by an existing serializer objects (e.g., for encoding, <code>JSONEncoder</code> and <code>PropertyListEncoder</code>, etc.). To support serialization for your custom types, you define your type to conform to the <code>Codable</code> protocol.</p></li>\n<li><p>While presentation and parsing of values in the UI is often handled by separate formatter objects, it’s worth noting that there are a few string representations that we might add to our custom types for debugging purposes. For example, we might conform to <a href=\"https://developer.apple.com/documentation/swift/customstringconvertible\" rel=\"nofollow noreferrer\"><code>CustomStringConvertible</code></a> so that we can <code>print</code> our values. Value types (<code>struct</code>) have a decent default string representation, but especially for reference types (<code>class</code>) it can be nice to customize this. </p>\n\n<p>But don’t be tempted to use <code>description</code> as a backdoor for formatting strings in your UI. As <a href=\"https://developer.apple.com/documentation/swift/customstringconvertible\" rel=\"nofollow noreferrer\">Apple says</a>, </p>\n\n<blockquote>\n <p>Accessing a type’s <code>description</code> property directly or using <code>CustomStringConvertible</code> as a generic constraint is discouraged.</p>\n</blockquote>\n\n<p>But for diagnostic purposes, this can be useful. Also see <a href=\"https://developer.apple.com/documentation/swift/customdebugstringconvertible\" rel=\"nofollow noreferrer\"><code>CustomDebugStringConvertible</code></a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T20:09:31.413",
"Id": "214725",
"ParentId": "214635",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "214725",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T11:03:19.913",
"Id": "214635",
"Score": "2",
"Tags": [
"object-oriented",
"comparative-review",
"swift",
"formatting",
"extension-methods"
],
"Title": "Formatting a price in Swift using an extension vs. a class"
} | 214635 |
<p>I just dipped my toes in Java today (coming from C++) and made a few things to learn it. The standard stuff like Atari Breakout, Tic Tac Toe and this calculator. This has been done so many times before!</p>
<p><a href="https://i.stack.imgur.com/A9rbz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A9rbz.png" alt="Screenshot"></a></p>
<p><strong>Calculator.java</strong></p>
<pre><code>import java.math.*;
public class Calculator {
private static final int MAX_DIGITS = 10;
private static final MathContext ARITH_ROUND = new MathContext(
MAX_DIGITS * 2, RoundingMode.HALF_EVEN
);
private static final MathContext SCREEN_ROUND = new MathContext(
MAX_DIGITS, RoundingMode.HALF_EVEN
);
public enum Operation {
NONE, ADD, SUB, MUL, DIV, EQUALS
}
private Operation prevOp;
private BigDecimal prevNumber;
private String currNumberStr;
private boolean error = false;
public Calculator() {
prevOp = Operation.NONE;
prevNumber = null;
currNumberStr = new String();
}
public void appendDigit(char digit) {
if (currNumberStr.length() >= MAX_DIGITS) {
return;
}
if (digit == '.') {
if (currNumberStr.indexOf('.') != -1) {
return;
}
if (currNumberStr.isEmpty()) {
currNumberStr += '0';
}
} else if (digit == '0') {
if (currNumberStr.isEmpty() || currNumberStr.equals("0")) {
return;
}
}
currNumberStr += digit;
}
private BigDecimal applyOp(Operation op, BigDecimal a, BigDecimal b) {
switch (op) {
case NONE:
assert false;
break;
case ADD:
return a.add(b, ARITH_ROUND);
case SUB:
return a.subtract(b, ARITH_ROUND);
case MUL:
return a.multiply(b, ARITH_ROUND);
case DIV:
return a.divide(b, ARITH_ROUND);
case EQUALS:
return a;
}
return null;
}
private BigDecimal parseCurrNumber() {
if (currNumberStr.isEmpty()) {
return new BigDecimal("0");
} else {
return new BigDecimal(currNumberStr);
}
}
public void applyOp(Operation op) {
BigDecimal currNumber = null;
if (prevOp == Operation.NONE) {
if (prevNumber == null) {
currNumber = parseCurrNumber();
} else {
currNumber = prevNumber;
}
} else if (error) {
currNumber = parseCurrNumber();
error = false;
} else {
try {
currNumber = applyOp(prevOp, prevNumber, parseCurrNumber());
error = false;
} catch (ArithmeticException e) {
currNumber = null;
error = true;
op = Operation.NONE;
}
}
prevNumber = currNumber;
currNumberStr = "";
prevOp = op;
}
public void clear() {
error = false;
if (currNumberStr.isEmpty()) {
prevNumber = null;
prevOp = Operation.NONE;
} else {
currNumberStr = "";
}
}
private static String numToString(BigDecimal num) {
return num.round(SCREEN_ROUND).toString();
}
private interface UnaryOp {
public BigDecimal apply(BigDecimal num);
}
private void applyUnaryOp(UnaryOp op) {
if (currNumberStr.isEmpty()) {
if (prevNumber != null) {
prevNumber = op.apply(prevNumber);
if (prevNumber == null) {
error = true;
}
}
} else {
BigDecimal currNumber = new BigDecimal(currNumberStr);
currNumber = op.apply(currNumber);
if (currNumber == null) {
error = true;
currNumberStr = "";
} else {
currNumberStr = numToString(currNumber);
}
}
}
public void negate() {
applyUnaryOp((BigDecimal n) -> n.negate(ARITH_ROUND));
}
public void root() {
applyUnaryOp((BigDecimal n) -> {
double val = n.doubleValue();
if (val < 0.0) {
return null;
} else {
return new BigDecimal(Math.sqrt(val));
}
});
}
public String screen() {
if (currNumberStr.isEmpty()) {
if (error) {
return "Error";
} else if (prevNumber == null) {
return "0";
} else {
return numToString(prevNumber);
}
} else {
return currNumberStr;
}
}
}
</code></pre>
<p><strong>Frame.java</strong></p>
<pre><code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ButtonColorListener extends MouseAdapter {
public static final Color DOWN_COLOR = Color.GRAY;
public static final Color UP_COLOR = Color.DARK_GRAY;
private JButton button;
public ButtonColorListener(JButton newButton) {
button = newButton;
}
@Override public void mousePressed(MouseEvent e) {
button.setBackground(DOWN_COLOR);
}
@Override public void mouseReleased(MouseEvent e) {
button.setBackground(UP_COLOR);
}
}
public class Frame extends JFrame {
private Calculator calc;
private JLabel screen;
private void updateScreen() {
screen.setText(calc.screen());
}
private static final Font BUTTON_FONT = new Font(Font.MONOSPACED, Font.PLAIN, 40);
private static final Font SCREEN_FONT = new Font(Font.MONOSPACED, Font.PLAIN, 32);
// Is there a shorthand for this?
// (so that I don't have to declare an interface?)
private interface CalcAction {
public void apply();
}
private void addButton(int x, int y, int w, int h, String name, CalcAction action) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
c.gridwidth = w;
c.gridheight = h;
// top, left, bottom, right
c.insets = new Insets(1, x != 0 ? 1 : 0, 0, 0);
c.fill = GridBagConstraints.BOTH;
JButton button = new JButton(name);
button.setFocusable(false);
button.setPreferredSize(new Dimension(64 * w, 64 * h));
button.setBorder(null);
button.setBackground(ButtonColorListener.UP_COLOR);
button.setForeground(Color.WHITE);
button.setOpaque(true);
button.setFont(BUTTON_FONT);
button.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
action.apply();
updateScreen();
}
});
button.addMouseListener(new ButtonColorListener(button));
getContentPane().add(button, c);
}
private void addButton(int x, int y, String name, CalcAction action) {
addButton(x, y, 1, 1, name, action);
}
private void addScreen() {
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
c.anchor = GridBagConstraints.EAST;
screen = new JLabel();
screen.setBackground(Color.BLACK);
screen.setForeground(Color.WHITE);
screen.setOpaque(true);
screen.setFont(SCREEN_FONT);
getContentPane().add(screen, c);
}
public Frame() {
super("Calculator");
calc = new Calculator();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridBagLayout());
getContentPane().setBackground(Color.BLACK);
addScreen();
updateScreen();
addButton(0, 1, "C", () -> calc.clear());
// Do I need to treat non-ascii characters differently?
// It seems to work as-is
addButton(1, 1, "±", () -> calc.negate());
addButton(2, 1, "√", () -> calc.root());
addButton(3, 1, "÷", () -> calc.applyOp(Calculator.Operation.DIV));
addButton(0, 2, "7", () -> calc.appendDigit('7'));
addButton(1, 2, "8", () -> calc.appendDigit('8'));
addButton(2, 2, "9", () -> calc.appendDigit('9'));
addButton(3, 2, "×", () -> calc.applyOp(Calculator.Operation.MUL));
addButton(0, 3, "4", () -> calc.appendDigit('4'));
addButton(1, 3, "5", () -> calc.appendDigit('5'));
addButton(2, 3, "6", () -> calc.appendDigit('6'));
addButton(3, 3, "-", () -> calc.applyOp(Calculator.Operation.SUB));
addButton(0, 4, "1", () -> calc.appendDigit('1'));
addButton(1, 4, "2", () -> calc.appendDigit('2'));
addButton(2, 4, "3", () -> calc.appendDigit('3'));
addButton(3, 4, "+", () -> calc.applyOp(Calculator.Operation.ADD));
addButton(0, 5, 2, 1, "0", () -> calc.appendDigit('0'));
addButton(2, 5, ".", () -> calc.appendDigit('.'));
addButton(3, 5, "=", () -> calc.applyOp(Calculator.Operation.EQUALS));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
// this feels strange
new Frame();
}
}
</code></pre>
<p>The main reason the implementation of <code>Calculator</code> is so messy is that I tried my very best to replicate the behaviour of the calculator the comes with macOS. I am aware of two minor details where the two differ but life is too short to worry about these things.</p>
<p><code>Calculator.prevNumber</code> may or may not be <code>null</code>. <code>Calculator.currNumberStr</code> may or may not be empty. <code>Calculator.error</code> may or may not be <code>true</code>. I'm not looking for a review that tells me that I should split these 8 states (minus the invalid ones) into an enum or separate classes. My main concern is style, naming conventions and the way that I use the language and standard library. I want to know if I'm using a feature strangely or if I should be using a different feature. I'm looking for Java specific feedback, not language agnostic "use a better algorithm" feedback.</p>
<p><strong>I want to write Java like a Java programmer.</strong></p>
| [] | [
{
"body": "<p>Starting with your questions.</p>\n\n<pre><code>// Is there a shorthand for this?\n// (so that I don't have to declare an interface?)\nprivate interface CalcAction {\n public void apply();\n}\n</code></pre>\n\n<p>If you don't want to declare such interface you can yust use one from the standard library such as <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html\" rel=\"nofollow noreferrer\">Runnable</a>. The only difference would be that its method is called run instead of apply. Also when defining an interface all its methods are by definition <strong><code>public abstract</code></strong>. You don't have to type that explicitly.</p>\n\n<pre><code>// Do I need to treat non-ascii characters differently?\n// It seems to work as-is\n</code></pre>\n\n<p>No need as long as you are using proper encoding such as UTF-8.</p>\n\n<pre><code>public static void main(String[] args) {\n // this feels strange\n new Frame();\n}\n</code></pre>\n\n<p>Correct. There are two problems with this code.</p>\n\n<ul>\n<li>Class should not be responsible for construction of its dependencies. It should just declare what it needs to function and let the caller deal with it. This is just application of <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">Dependency Inversion Principle</a> (One of <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID Principles</a>). I.E. Having configurable dependencies.</li>\n<li>Constructor should not do any work except initialization of the new object. Having code in the constructor prevents you from properly using composition and would make point above very painful.</li>\n</ul>\n\n<p>With these two points applied the main method might look something like this.</p>\n\n<pre><code>public static void main(String[] args) {\n new Frame(\n new JLabel(),\n new Calculator()\n ).start();\n}\n</code></pre>\n\n<p><strong>Minor remarks</strong></p>\n\n<p>When you need empty string just use literal <strong><code>\"\"</code></strong> no need for <code>new String()</code>.</p>\n\n<p>Instead of simple anonymous classes such as.</p>\n\n<pre><code>button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n action.apply();\n updateScreen();\n }\n});\n</code></pre>\n\n<p>Just use lambda.</p>\n\n<pre><code>button.addActionListener(e -> {\n action.apply();\n updateScreen();\n});\n</code></pre>\n\n<p>Assertions are turned off by default and they have to be anabled explicitly. When you have a state that is wrong, invalid or for whatever reason exceptional, throw exception.</p>\n\n<pre><code>private BigDecimal applyOp(Operation op, BigDecimal a, BigDecimal b) {\n switch (op) {\n case NONE:\n throw new IllegalStateException(\"NONE cannot be applied!\");\n case ADD:\n return a.add(b, ARITH_ROUND);\n case SUB:\n return a.subtract(b, ARITH_ROUND);\n case MUL:\n return a.multiply(b, ARITH_ROUND);\n case DIV:\n return a.divide(b, ARITH_ROUND);\n case EQUALS:\n return a;\n }\n return null;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T13:39:17.453",
"Id": "214647",
"ParentId": "214638",
"Score": "4"
}
},
{
"body": "<h1>The Switch</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>private BigDecimal applyOp(Operation op, BigDecimal a, BigDecimal b) {\n switch (op) {\n case NONE:\n assert false;\n break;\n case ADD:\n return a.add(b, ARITH_ROUND);\n case SUB:\n return a.subtract(b, ARITH_ROUND);\n case MUL:\n return a.multiply(b, ARITH_ROUND);\n case DIV:\n return a.divide(b, ARITH_ROUND);\n case EQUALS:\n return a;\n }\n return null;\n}\n</code></pre>\n</blockquote>\n\n<h2>The Default Section</h2>\n\n<p>The statement <code>return null</code> can be replaced by a <code>default</code>-section. From <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html\" rel=\"noreferrer\">oracles <code>switch</code> tutorial</a> </p>\n\n<blockquote>\n <p>The default section handles all values that are not explicitly handled by one of the case sections</p>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>private BigDecimal applyOp(Operation op, BigDecimal a, BigDecimal b) {\n switch (op) {\n // ..\n case EQUALS:\n return a;\n default: \n return null;\n }\n}\n</code></pre>\n\n<h2>Polymorphism</h2>\n\n<p>Currently the switch tries to express: \"<em>Let's have a look, what the concrete type of <code>op</code> is and <strong>let me</strong> execute the correct logic for it</em>\"</p>\n\n<p>This can be rewritten to: \"Let <code>op</code> execute the correct logic.\"</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private BigDecimal applyOp(Operation op, BigDecimal a, BigDecimal b) {\n return op.calculate(a, b);\n}\n</code></pre>\n\n<p>For that we need to change the enum <code>Operation</code>. But before we change it, you need to know from <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"noreferrer\">Oracles Enum Tutorial</a></p>\n\n<blockquote>\n <p>Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. [...]</p>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>public enum Operation {\n NONE((a, b) -> null),\n ADD((a, b) -> a.add(b, ARITH_ROUND)), \n // ...\n EQUALS((a, b) -> a);\n\n BiFunction<BigDecimal, BigDecimal, BigDecimal> calculation;\n\n Operation(BiFunction<BigDecimal, BigDecimal, BigDecimal> calculation) {\n this.calculation = calculation;\n }\n\n BigDecimal calculate(BigDecimal a, BigDecimal b) {\n return calculation.apply(a, b);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T10:38:09.643",
"Id": "415158",
"Score": "0",
"body": "Interesting! Java enums are quite a bit more flexible than C++ enums. Although, this fancy stuff can be done in C++ by declaring a class instead of an enum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T10:47:44.960",
"Id": "415161",
"Score": "0",
"body": "Java's enums are sort of a multiton pattern supported out of the box. You are guaranteed to only end up with a set number of instances (enum values)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T10:24:00.620",
"Id": "214692",
"ParentId": "214638",
"Score": "5"
}
},
{
"body": "<p>You've a nice little calculator. The other answers have made excellent points. Here are some more to make it even better. ;-)</p>\n\n<hr>\n\n<h1>Calculator</h1>\n\n<h2>Constructor</h2>\n\n<p>You are initializing 3 members in your constructor, and a fourth member <code>error</code> using a declaration initialization. You could do all 4 initializations at the declaration, in which case your constructor would be empty ... and could be omitted entirely.</p>\n\n<pre><code>private Operation prevOp = Operation.NONE;\nprivate BigDecimal prevNumber = null;\nprivate String currNumberStr = \"\"; // or new String()\nprivate boolean error = false;\n</code></pre>\n\n<h2>currNumberStr</h2>\n\n<p>You are using <code>String</code> concatenation to build up a string of characters representing a number. It most cases, <code>String</code> concatenation should be avoided in favour of using a <a href=\"https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\"><code>StringBuilder</code></a>, which is more efficient. Given there will be hundreds of milliseconds between adding characters to the <code>currNumberStr</code>, this is probably a pointless optimization. But it might be worth the practice.</p>\n\n<pre><code>final StringBuilder currNumberStr = new StringBuilder(MAX_DIGITS);\n</code></pre>\n\n<p>Notice that we can reuse the <code>StringBuilder</code> over and over, so it can be made <code>final</code>. Use <code>currNumberStr.append(digit)</code> to add characters to the buffer, <code>currNumberStr.setLength(0)</code> to clear it, and <code>currNumberStr.toString()</code> to convert it into a <code>String</code> for parsing or display.</p>\n\n<h2>interface UnaryOp</h2>\n\n<p>You can remove this interface, and replace uses of it with <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/function/UnaryOperator.html\" rel=\"nofollow noreferrer\"><code>UnaryOperator<BigDecimal></code></a>.</p>\n\n<hr>\n\n<h1>Frame</h1>\n\n<h2>ButtonColorListener</h2>\n\n<p>You create 19 <code>ButtonColorListener</code> objects, which is about 18 too many. They all do the same thing; change the button's background colour. The only difference is which button they change the background colour of...</p>\n\n<p><a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/EventObject.html#getSource()\" rel=\"nofollow noreferrer\"><code>MouseEvent.getSource()</code></a> will return the <code>Object</code> the mouse event occurs on ... which will be the button that was pressed/released.</p>\n\n<pre><code>class ButtonColorListener extends MouseAdapter {\n public static final Color DOWN_COLOR = Color.GRAY;\n public static final Color UP_COLOR = Color.DARK_GRAY;\n\n @Override public void mousePressed(MouseEvent e) {\n JButton button = (JButton) e.getSource();\n button.setBackground(DOWN_COLOR);\n }\n\n @Override public void mouseReleased(MouseEvent e) {\n JButton button = (JButton) e.getSource();\n button.setBackground(UP_COLOR);\n }\n}\n</code></pre>\n\n<p>With this change, you only need to create one <code>ButtonColorListener</code>, and add it to all of the buttons, instead of creating one per button.</p>\n\n<pre><code>private final static ButtonColorListener btnClrListener = new ButtonColorListener();\n\nprivate void addButton(int x, int y, int w, int h, String name, CalcAction action) {\n // ...\n button.addMouseListener(btnClrListener);\n // ...\n}\n</code></pre>\n\n<h2>addButton</h2>\n\n<p>This method gives you way too much flexibility. You are creating buttons, and adding them to the <code>contentPane()</code> in order, left to right, top to bottom. Let the computer do the counting for you!</p>\n\n<pre><code>private final static int MAX_WIDTH = 4;\nprivate int row = 1, column = 0;\n\nprivate void addButton(String name, CalcAction action) {\n addButton(name, action, 1);\n} \n\nprivate void addButton(String name, CalcAction action, int width) {\n // ...\n c.gridx = column;\n c.gridy = row;\n c.gridwidth = width;\n\n column += width;\n if (column >= MAX_WIDTH) {\n column = 0;\n row++;\n }\n // ...\n}\n</code></pre>\n\n<h2>Creating the Button Grid</h2>\n\n<p>With the above <code>addButton</code> method keeping track of the locations, you just need to add the buttons in the correct order (which you were doing anyway).</p>\n\n<pre><code>addButton(\"C\", calc::clear); // We can use method references for these first few!\naddButton(\"±\", calc::negate);\naddButton(\"√\", calc::root);\naddButton(\"÷\", () -> calc.applyOp(Calculator.Operation.DIV));\naddButton(\"7\", () -> calc.appendDigit('7'));\n// ...\n</code></pre>\n\n<p>Since some of the methods take no arguments, we can simply use a method reference. And as mentioned in another answer, <code>CalcAction</code> can be replaced by <code>Runnable</code>.</p>\n\n<h2>main</h2>\n\n<p>Swing Application must do UI interactions on Swing's Event Dispatching Thread (EDT). Creating the UI can be an exception, since the UI is not shown until <code>frame.setVisible(true);</code> is called, but this is risky behaviour. It is better to simply switch to the EDT to create and display the UI.</p>\n\n<pre><code>public static void main(String[] args) {\n SwingUtilities.invokeLater(Frame::new);\n}\n</code></pre>\n\n<p>That may feel even stranger, but it is better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T04:21:08.877",
"Id": "415550",
"Score": "0",
"body": "This is a fantastic answer! In each case, you told me something I didn't know about Java. This is precisely what I was looking for when I asked this question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T03:32:20.093",
"Id": "214887",
"ParentId": "214638",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214887",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T11:35:57.250",
"Id": "214638",
"Score": "3",
"Tags": [
"java",
"calculator",
"swing"
],
"Title": "Writing a calculator in idiomatic Java"
} | 214638 |
<p>Isn't there a better way to create my constants that I can use elsewhere in my code ?</p>
<pre><code>export default class AppConstants {
}
Object.defineProperty(AppConstants, 'APP_NAME', { value: 'iVoc'})
/*
*...
*Other constants
*/
</code></pre>
| [] | [
{
"body": "<p>Class syntax should not be used for single instance (static) objects (really class should never be used). Use an <code>Object</code> literal and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"nofollow noreferrer\"><code>freeze</code></a> it.</p>\n\n<pre><code>const AppConstants = Object.freeze({\n NAME : \"iVoc\",\n VERSION : \"0.1B\",\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T13:13:19.780",
"Id": "214646",
"ParentId": "214642",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T12:18:06.773",
"Id": "214642",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Is there a better way to create constants in javascript?"
} | 214642 |
<h3>Problem</h3>
<p>I have <span class="math-container">\$N\$</span> words. For each valid <span class="math-container">\$i\$</span>, word <span class="math-container">\$i\$</span> is described by a string <span class="math-container">\$D_i\$</span> containing only lowercase vowels, i.e. characters 'a', 'e', 'i', 'o', 'u'. </p>
<p>We check the number of strings <span class="math-container">\$D_i\$</span> and <span class="math-container">\$D_j\$</span> which, when concatenated into a new string <span class="math-container">\$M\$</span>, contain all 5 vowels. What is the total number of (unordered) pairs of words such that when concatenated, they contain all the vowels?</p>
<h3>Input</h3>
<ul>
<li>The first line of the input contains a single integer <span class="math-container">\$T\$</span> denoting the number of test cases. The description of <span class="math-container">\$T\$</span> test cases follows.</li>
<li>The first line of each test case contains a single integer <span class="math-container">\$N\$</span>.</li>
<li><span class="math-container">\$N\$</span> lines follow. For each valid <span class="math-container">\$i\$</span>, the <span class="math-container">\$i^{th}\$</span> of these lines contains a single string <span class="math-container">\$D_i\$</span>.</li>
</ul>
<h3>Output</h3>
<p>For each test case, print a single line containing one integer - the number of concatenated words that contain all vowels.</p>
<h3>Test Case</h3>
<pre><code>3
aaooaoaooa
uiieieiieieuuu
aeioooeeiiaiei
</code></pre>
<h3>Output</h3>
<pre><code>2
</code></pre>
<h3>Constraints</h3>
<ul>
<li><span class="math-container">\$1≤T≤1,000\$</span></li>
<li><span class="math-container">\$1≤N≤10^5\$</span></li>
<li><span class="math-container">\$1≤|D_i|≤1,000\$</span> for each valid <span class="math-container">\$i\$</span></li>
<li>the sum of all |<span class="math-container">\$D_i\$</span>| over all test cases does not exceed <span class="math-container">\$3⋅10^7\$</span></li>
</ul>
<p>I have written some code but I want to optimize it:</p>
<pre><code>#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
vector<string> v;
long long con_s[n];
for(int i=0;i<n;i++)
{
string s;
cin>>s;
con_s[i]=0;
for(int j=0;j<s.length();j++)
{
con_s[i] = con_s[i] | (1<<(s[j]-'a'));
}
}
long long complete = 0;
complete = (1<<('a'-'a')) | (1<<('e'-'a')) | (1<<('i'-'a')) | (1<<('o'-'a')) | (1<<('u'-'a'));
// cout<<complete;
int count = 0;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if((con_s[i] | con_s[j])==complete)count++;
}
}
cout<<count<<"\n";
}
return 0;
}
</code></pre>
<p>Can you please suggest a more optimized solution...</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T14:17:38.060",
"Id": "415070",
"Score": "0",
"body": "Welcome! As it's written, your code is a little difficult to understand, particularly with the bit shifting. My suggestion is to use more informative variable names. Short one-letter variable names are good for loops and writing quick code, but they make it very difficult for others (even yourself) to review your code later on. I'd also recommend moving some of the code out of main and into functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T17:01:43.433",
"Id": "415085",
"Score": "0",
"body": "Is the \"T\" variable the number of tests, or something else? I don't see it mentioned in the description of the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T17:07:34.890",
"Id": "415086",
"Score": "0",
"body": "@AustinHastings yes, T is the number of testcases. Can you help me solve this ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T19:01:29.193",
"Id": "415106",
"Score": "1",
"body": "@AleksandrH Please put all suggestions for improvements in answers, not comments."
}
] | [
{
"body": "<p>I'm no C++ guru, but some things jump out at me:</p>\n\n<ol>\n<li><p>Your coding style is very dense, which makes it hard to read and review. I'd suggest that you switch to a style that doesn't make you pay for each time you add a space. Code like this:</p>\n\n<pre><code>cin>>t;\nwhile(t--)\n</code></pre>\n\n<p>Just isn't as easy to read as code like this:</p>\n\n<pre><code>cin >> t;\nwhile (t--)\n</code></pre>\n\n<p>The little things make a difference! And even if you're in some kind of \"shortest code\" context, I think you should still write it long, and then compress it once you have it working.</p></li>\n<li><p>The first <code>for</code> loop in your <code>while</code> loop is concerned with reading and parsing the input strings. I believe you should break that into a separate function. What's more, I think you should make a slight change to your data storage as @Deduplicator suggested: instead of just using the bits located at <code>(1 << (vowel - 'a'))</code>, at some point you should compress the bits down into the range <code>1<<0 .. 1<<4</code>.</p></li>\n<li><p>I believe that the description says \"(unordered) pairs\" and means that if two strings, A and B, can be concatenated to meet the requirements, they only count once, as in <code>set{A, B}</code> and not twice, as in <code>pair(A,B), pair(B,A)</code>. So, as @Deduplicator suggested, if you \"bin\" your words - that is, categorize them according to the trait \"which vowels are present\", then you can represent a bin with just an integer (how many words are in the bin). So you would then cross-match every bin with every other bin to determine whether the binned words can successfully pair, and add an appropriate number to the count.</p></li>\n</ol>\n\n<p>With that in mind, a successful solution would look something like this:</p>\n\n<pre><code>for each input word:\n scan the word for vowels, recording which vowels were found\n classify the found vowels into a small integer with bits 0..4 set\n use the small integer as the \"bin\" number for that word\n increment the count for that bin#\n</code></pre>\n\n<p>This should be <span class=\"math-container\">\\$O(n \\cdot s)\\$</span> on the number of words, <em>n,</em> and the length of the words, <em>s,</em> in time. The only optimization would be to break out of the scanning loop if you match every single vowel, since further scanning gains you nothing. The code will require storage for the input, but compiles everything down to a single bin number, so the storage will be from <span class=\"math-container\">\\$O(1)\\$</span> to <span class=\"math-container\">\\$O(s)\\$</span> depending on how you implement the code. The bin numbers are members of a fixed set, so their counts will be <span class=\"math-container\">\\$O(2^5)\\$</span> regardless, which simplifies to <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n\n<p>Now since matched pairs of words only count one time, you can loop \"upwards\" when generating combinations:</p>\n\n<pre><code>for each bin 0 .. 2^5 - 1\n for each higher bin (looping upwards here):\n if the two bins match\n the count of word pairs is # in bin-1 * # in bin-2\n add the count to the total count of matchable pairs\n</code></pre>\n\n<p>This should be <span class=\"math-container\">\\$O(n^2)\\$</span> on the number of <em>bins</em> (not words!), which is a constant. You can't optimize much, except that bins with counts of zero won't contribute anything so can be skipped. </p>\n\n<p>At this point you have your answer and just need to print it out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T17:31:39.340",
"Id": "214657",
"ParentId": "214644",
"Score": "4"
}
},
{
"body": "<h1>Your Code:</h1>\n\n<ol>\n<li><p>Don't use <code><bits/stdc++.h></code>, it's unportable and inefficient. See \"<em><a href=\"https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h\">Why should I not #include <bits/stdc++.h>?</a></em>\" for the details.</p></li>\n<li><p>Don't use <code>using namespace std;</code>, that namespace just isn't designed for it. See \"<em><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std” considered bad practice?</a></em>\" for more background.</p></li>\n<li><p>Invest in some better names. Being too parsimonious there hurts, even though brevity is a virtue.</p></li>\n<li><p>Format your code consistentently.</p>\n\n<ul>\n<li>Sometimes you have space around binary operators (other than comma, which only should be followed by a space), sometimes you forget.</li>\n<li>Add a space after <code>;</code> when it isn't followed by the next line, meaning a loop's head.</li>\n<li>Also add a space after <code>#include</code>, <code>for</code>, <code>if</code>, and <code>while</code>.</li>\n<li>You don't have to use a block for single statements, but please don't put them on the same line, at the least separate them with a space.</li>\n</ul></li>\n<li><p><a href=\"https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard\">C++ does not have VLAs.</a> Just use a <code>std::vector</code> instead.</p></li>\n<li><p>While in general, keeping the scope of a variable minimal is a good idea, there are exceptions. One of them is efficiency. Always spinning up a new <code>std::string</code> means being unable to re-use the buffer. Not that you really need the whole string at once, anyway.</p></li>\n<li><p>One reason you should minimise a variables scope, is that it allows you to initialise it to the proper value, instead of leaving it uninitialised or, horrors of horrors, adding a spurious dummy-initialisation.<br>\nThat also allows you to avoid writing the type (<a href=\"https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/\" rel=\"noreferrer\">Almost Always <code>auto</code></a>), and making it <code>const</code> or even <code>constexpr</code>.</p></li>\n<li><p>There are <a href=\"https://en.cppreference.com/w/cpp/language/operator_assignment\" rel=\"noreferrer\">compound-assignment-operators for most binary operators</a>. Like <code>a |= b</code> for <code>a = a | b</code>. Using them leads to shorter, more readable code.</p></li>\n<li><p>When you want to output a single character, why not use a character-literal? It's potentially even slightly more efficient.</p></li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code>. Take it or leave it, but be aware.</p></li>\n</ol>\n\n<h1>The Algorithm:</h1>\n\n<p>Your algorithm uses <span class=\"math-container\">\\$O(\\#characters+\\#words^2)\\$</span> time and <span class=\"math-container\">\\$O(max\\_word\\_length + \\#words)\\$</span> space.</p>\n\n<p>An optimal algorithm only needs <span class=\"math-container\">\\$O(\\#characters+2^{\\#vowels})\\$</span> time and <span class=\"math-container\">\\$O(2^{\\#vowels})\\$</span> space:</p>\n\n<ol>\n<li>For every word:\n\n<ol>\n<li>Set the bits for all the vowels contained.</li>\n<li>Increment the count on the indicated bin.</li>\n</ol></li>\n<li>For every vowel:\n\n<ol>\n<li>Iterate the bins containing words with that vowel.</li>\n<li>Add the count to the respective bin without that vowel.</li>\n</ol></li>\n<li>For all bins:\nMultiply the count in the bin with the count in the complementary bin, and add that.</li>\n<li>Subtract twice the count in the bin for words containing all vowels. Those account for all self-pairings.</li>\n<li>The answer is half the calculated number, as we counted double.</li>\n</ol>\n\n<p>Exercise for the attentive reader: Save half the multiplications this algorithm uses.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T08:38:12.810",
"Id": "415985",
"Score": "0",
"body": "The optimal algorithm is only optimal for a very small number of vowels. As soon as you combine multiple alphabets (Latin, Cyrillic, Hangul, Latin with accented letters), \\$2^v\\$ quickly becomes quite large and inefficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T10:44:52.847",
"Id": "415994",
"Score": "0",
"body": "@RolandIllig Sure, unicode has a ginormous repertoire."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T18:44:44.197",
"Id": "214661",
"ParentId": "214644",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T12:39:38.553",
"Id": "214644",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Count number of pairs of strings which on joining contain all vowels"
} | 214644 |
<p>I have written some code that takes two integers and returns the numbers of numbers that are both a square and a cube. I would like to know if there is a more efficient way to write this. I have only just started learning Java so any feedback would be greatly appreciated.</p>
<pre><code>Scanner input=new Scanner(System.in);
double a=input.nextInt();
double b=input.nextInt();
int coolnumbers=0; //counter for the # of numbers that are a square and cube
for(double i=a; i<=b; i++){
for(double j=1; j<=b; j++){
if(i==Math.pow(j,6)){
coolnumbers++;
break;
}
}
}
System.out.println(coolnumbers);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T08:37:05.850",
"Id": "415147",
"Score": "0",
"body": "I would have meaningful variable names for a start. Not for the loop control variables, but six months from now will it be clear to you what `a` and `b` are doing?"
}
] | [
{
"body": "<p>@JellybeanNewbie, and welcome to code review. </p>\n\n<p>You ask about efficiency, and there are a few changes that jump out to me as possibilities for speeding things up. I'll make a few comments about other aspects of your code first, and then walk through the efficiency things. </p>\n\n<hr>\n\n<pre><code>double b=input.nextInt();\n</code></pre>\n\n<p>There are actually three little concerns on this line. </p>\n\n<p>First is that <code>b</code> is not a very descriptive variable name. The code would be clearer if it were named something else, like <code>upperBound</code>. </p>\n\n<p>Second, it is always worth being careful about what types your variables have. It's a bit of a red flag when you are getting an <code>int</code> and putting it into a <code>double</code> variable. There are good reasons to use doubles sometimes, but they can cause subtle bugs often associated with rounding error. If you definitely want to work with an integer it's usually worth keeping things as <code>int</code>. If not, perhaps you should be using something like <code>nextDouble</code>.</p>\n\n<p>Third is that this is information that is coming from the user. As a general rule, it's worth checking all information that comes from the user, just to make sure that it makes sense. For example, it may be worth making sure that <code>b</code> is actually a number. It's also worth checking that <code>b</code> is bigger than <code>a</code>. Likewise if there's anything else that could make the code fall over, it is usually worth checking that they haven't used such an input as soon as possible.</p>\n\n<hr>\n\n<pre><code>for(double j=1; j<=b; j++){\n</code></pre>\n\n<p>This line is actually hiding a subtle bug. Suppose that your input for <code>a</code> is 0 and <code>b</code> is 2, which seems like a perfectly sensible pair of inputs. There are then two answers: both 0 and 1 are both squares and cubes. However your <code>for</code> loop starts at 1, which means it will skip right over considering 0. Now this bug will actually disappear completely with some of my efficiency suggestions, but I wanted to draw attention to it because it highlights an important lesson in testing code. That is, always remember to think about and test the edge cases, which are the biggest or smallest things that a bit of code can work with. </p>\n\n<hr>\n\n<p>Now, for the efficiency bit. There is a useful proverb for getting code to go faster: \"The fastest code is the code that isn't run.\" </p>\n\n<p>Look again at the <code>for</code> loop with <code>j</code> in it. That loop is counting upwards, from 1 to <code>b</code>. For each number between 1 and <code>b</code>, it checks whether <code>j</code> to the power of 6 is exactly <code>i</code>. Now, let's suppose that <code>b</code> is a big sort of number, perhaps a million, so you're doing that check a million times. However, as soon a <code>j</code> to the power of 6 is greater than <code>i</code>, it's clear that none of the rest of those possible <code>j</code> values can be the number you want. After all, <code>j</code> keeps getting bigger, so <code>j</code> to the power of 6 will get bigger, and it's already too big. Once you notice that, you'll see that instead of checking a million possible values of <code>j</code> we only have to check ten. </p>\n\n<p>That's a big improvement, but there is room do do better. Instead of checking possible values of <code>j</code> and seeing whether <code>j</code> to the power of 6 is <code>i</code>, you can just check the sixth root of <code>i</code>. (For example using <code>Math.pow(i, 1.0/6.0)</code> or <code>Math.sqrt(Math.cbrt(i))</code>). If that is an integer, then you've found a special number. And in the process, you can completely delete the second <code>for</code> loop. </p>\n\n<p>There's a couple of tricks that I've used here. Think about the sixth root rather than counting up the sixth powers. Think about what happens as you start to count up. I'll end on a challenge. Can you find a way to use the same sorts of tricks to make the that first <code>for</code> loop shorter, and then disappear? I think you can solve this problem without any looping at all!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T15:11:02.923",
"Id": "214651",
"ParentId": "214649",
"Score": "20"
}
},
{
"body": "<p>Let's say a = 1, b = 1,000,000. Your code is a nested loop, each loop iterating a million times, for a total of one trillion tests. And I tell, out of my head, that the result is 10 and the numbers are 1, 2^6, 3^6, 4^6, 5^6, 6^6, 7^6, 8^6, 9^6 and 10^6. </p>\n\n<p>The numbers that are both 2nd and 3rd powers are exactly the sixth powers of integers. So you can just iterate for i = 0, 1, 2, 3 etc., calculate j = i^6, then if j >= a and j <= b increase the counter, and if j > b then exit the loop. The time needed is proportional to the sixth root of b. </p>\n\n<p>Even faster, if b was <em>extremely</em> large, calculate A = sixth root of a, round up to the nearest integer, and B = sixth root of b, rounded down to the nearest integer. The numbers from a to b that are sixth powers are exactly the sixth powers of the numbers from A to B, and there are B - A + 1 of them. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T09:13:00.930",
"Id": "415150",
"Score": "1",
"body": "the even faster bit should be the heart of the answer, and developed further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T14:59:02.897",
"Id": "415194",
"Score": "0",
"body": "@UmNyobe: Calculating a 6th root is more optional, maybe, but also more complicated. Brute force is your friend!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T18:10:30.470",
"Id": "214659",
"ParentId": "214649",
"Score": "25"
}
},
{
"body": "<p>Welcoem JellybeanNewbie!</p>\n\n<p>The first thing I noticed (I'm not a Java programmer) is that you have no way of knowing that <code>b</code> is greater than <code>a</code>. I would add a check in there to make sure you're going from smaller to bigger in your loops.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T20:59:41.690",
"Id": "415220",
"Score": "0",
"body": "Conveniently, negative numbers are actually fine. The code won't find any examples among them, and which is correct because there are no negative squares of integers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T17:36:56.473",
"Id": "415366",
"Score": "1",
"body": "Alright, removed that bit. Thanks for the feedback"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T17:53:35.407",
"Id": "214715",
"ParentId": "214649",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "214659",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T14:16:40.503",
"Id": "214649",
"Score": "9",
"Tags": [
"java"
],
"Title": "Finding the number of integers that are a square and a cube at the same time"
} | 214649 |
<p>I have below code, which is basically handling inbound emails in my application, save the actual email content (text + attachments) to my database, and further save the actual attachment file on my server.</p>
<p>In my <code>Email.php</code> model, I have below function that handles the incoming email. The <code>$token</code> is the first string of the email. For example, my <code>To:</code> email can look like this: <code>avdksokiell@myapp.com</code> where <code>avdksokiell</code> is my token.</p>
<p>So as you can see, I fire off the <code>Email</code> model as below:</p>
<pre><code>Mailbox::to('{token}@myapp.com', Email::class);
</code></pre>
<p>When above condition is met, below will be run:</p>
<pre><code>public function __invoke(InboundEmail $email, $token)
{
//Get the correct stream.
$stream = Stream::where('token', $token)->firstOrFail();
//Persist the token to the database. {token}@in.myapp.com
$email->stream_id = $stream->id;
//Save the email.
$email->save();
//If any attachments, persist them to the database.
$this->storeAttachments($stream, $email);
}
</code></pre>
<p>Above works, because I have a relationship set up between <code>Stream</code> and <code>Email</code>:</p>
<p><code>Stream.php</code>:</p>
<pre><code>/**
* A stream can have many e-mails
*/
public function emails()
{
return $this->hasMany(Email::class);
}
</code></pre>
<p><code>Email.php</code>:</p>
<pre><code>/**
* An email belongs to a Stream.
*/
public function stream()
{
return $this->belongsTo(Stream::class);
}
</code></pre>
<p>Furthermore, in order to save the actual attachment from the mail, I have created a method called <code>storeAttachments(Stream $stream, InboundEmail $email)</code> function in <code>Email</code> that looks like below:</p>
<pre><code>/**
* A method to store incoming attachments from email.
*
*/
public function storeAttachments(Stream $stream, InboundEmail $email)
{
$attributes = [];
foreach ($email->attachments() as $attachment) {
//Set an unique filename
$filename = uniqid() . '.' . File::extension($attachment->getFilename());
//Store the file on the server
$store = Storage::put($stream->token . '/' . $filename, $attachment->getContent());
//Add file information, so we can persist it to the database.
$attributes['name'] = $attachment->getFilename();
$attributes['path'] = $stream->token . '/' . $filename;
//Persist it to the database.
$stream->addDocuments($attributes);
}
}
</code></pre>
<p>Because my users can choose to:</p>
<ol>
<li>Upload files from a web frontend</li>
<li>Send files by email into my app</li>
</ol>
<p>I also have a <code>Document</code> model, that stores all the files:</p>
<p>I also have a relationship set up here:</p>
<p><code>Stream.php</code>:</p>
<pre><code>/**
* A stream can have many documents
*/
public function documents()
{
return $this->hasMany(Document::class);
}
</code></pre>
<p><code>Document.php</code>:</p>
<pre><code>//A document belongs to a Stream.
public function stream()
{
return $this->belongsTo(Stream::class);
}
</code></pre>
<p>Now, for handling the saving files to the database, I have below method in my <code>Stream</code> model:</p>
<pre><code>/**
* Add document(s) to the stream
*
* @return Illuminate\Database\Eloquent\Model
*/
public function addDocuments(array $attributes)
{
return $this->documents()->create($attributes);
}
</code></pre>
<p>I am a bit unsure if above design/methodology is correct and seen as <em>"best practice"</em>. </p>
<p>One thing I notice is, that whenever I handle an incoming mail in the <code>__invoke</code> function, I run a query to get the <code>stream_id</code> by looking up the <code>token</code>, because the relationships is using <code>stream_id</code>.</p>
<p>Hope someone can help me shed some light if above is OK or if anything can be improved.</p>
<p>I'll be happy to share more code if needed.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T16:42:21.640",
"Id": "214654",
"Score": "2",
"Tags": [
"php",
"email",
"laravel"
],
"Title": "PHP - Saving inbound email and its attachment"
} | 214654 |
<p>I’m learning F# and trying to find a more ‘functional’ way to code a simple program that retrieves the price of BTC and calculates the EUR value of an amount of Bitcoin.</p>
<pre><code>open System
open System.Net
open Newtonsoft.Json.Linq
let myBTC = 0.1234567
let client = new WebClient()
client.UseDefaultCredentials = true
let priceInfo = client.DownloadString("https://blockchain.info/ticker")
let jPrice = JObject.Parse priceInfo
let eurPrice = float (jPrice.["EUR"].["buy"] :?> JValue)
let calcWorth = myBTC * eurPrice
printfn "%s" calcWorth.ToString("N")
</code></pre>
| [] | [
{
"body": "<p>My take is that there is no harm in adding a few named functions. Also it is probably better to ignore the result of setting a standard .net property.</p>\n\n<pre><code>open System\nopen System.Net\nopen Newtonsoft.Json.Linq\n\nlet downloadPriceInfo () =\n let client = new WebClient()\n client.DownloadString(\"https://blockchain.info/ticker\")\n\nlet getPriceOfEuro (price: JObject) = float (price.[\"EUR\"].[\"buy\"] :?> JValue)\n\nlet euroToBtc euro = 0.1234567 * euro\n\nlet btcOfEuro = \n downloadPriceInfo () \n |> JObject.Parse\n |> getPriceOfEuro \n |> euroToBtc\n\nprintfn \"%s\" (btcOfEuro.ToString(\"N\"))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T14:27:46.210",
"Id": "416496",
"Score": "1",
"body": "Some suggestions, which may or may not be useful...\n\n`|> parseJObject` is equivalent to `|> JObject.Parse`.\n\n `jPrice` might better be named `price` since the type definition is fully specified here. \n\n`euroPrice` might be better named `euro` since the function is `EuroToBtc`. \n\nI'm pretty sure `client.UseDefaultCredentials = true` doesn't actually do anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T16:29:14.527",
"Id": "416523",
"Score": "0",
"body": "@VoronoiPotato - You make some good points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-15T15:31:07.030",
"Id": "416864",
"Score": "0",
"body": "always happy to help :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T22:54:47.310",
"Id": "214671",
"ParentId": "214660",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "214671",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T18:11:53.137",
"Id": "214660",
"Score": "3",
"Tags": [
"beginner",
"json",
"f#",
"unit-conversion",
"cryptocurrency"
],
"Title": "Convert bitcoin value based on exchange rate from JSON API"
} | 214660 |
<p>This was my assignment.</p>
<blockquote>
<p>Write a C++ program that reads in a series of test scores. If the test score is >= 90 && , <= 100; print the letter grade 'A'. If the score is >= 80 but < 90, print the letter grade 'B'. if the test score is >= 70 and < 80, print the letter grade 'C'. If the test score is >= 60 but < 70 print the letter grade 'D' If the test score is < 60 print the letter grade 'F'. Print the score and the corresponding grade. Determine and print the max score, the min score, the average score, and the number of tests. Terminate on a negative test score.</p>
</blockquote>
<p>My code works fine but I feel like there's a better way to do it. I talked to a friend and he said since I was reading from a file a array would be better. How would I got about that?</p>
<pre><code>#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
int Score, MaxScore, MinScore, AvgScore, NumTests, TotalScore, Num;
string Grade;
NumTests = 0;
TotalScore = 0;
MaxScore = 0;
MinScore = 100;
inFile.open("indata6.txt");
if (!inFile)
{
cout << "Failed to find inFile." << endl;
return 1;
}
cout << "Test Scores & Grades" << endl;
cout << "--------------------" << endl;
while ( inFile >> Score)
{
NumTests = NumTests + 1; // Setting number of tests
TotalScore = TotalScore + Score; // Adding the Total score for the Avg equation
if ( Score > MaxScore) // If statements to find Max score
{
MaxScore = Score;
if ( Score >= 90 && Score <= 100) // If statements to find letter Grades
{
Grade = "A";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 80)
{
Grade = "B";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 70)
{
Grade = "C";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 60)
{
Grade = "D";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 0)
{
Grade = "F";
cout << Score << " " << Grade << endl;
}
else
{
cout << "Invalid Test Score:" << Score << endl;
return 2;
}
}
else if ( Score < MinScore) // If statement to find Min score
{
MinScore = Score;
if ( Score >= 90 && Score <= 100) // If statements to find letter grades
{
Grade = "A";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 80)
{
Grade = "B";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 70)
{
Grade = "C";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 60)
{
Grade = "D";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 0)
{
Grade = "F";
cout << Score << " " << Grade << endl;
}
else
{
cout << "Invalid Test Score:" << Score << endl;
return 2;
}
}
else // When a score isnt Max or Min
{
if ( Score >= 90 && Score <= 100) // More if statements to find letter grade
{
Grade = "A";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 80)
{
Grade = "B";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 70)
{
Grade = "C";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 60)
{
Grade = "D";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 0)
{
Grade = "F";
cout << Score << " " << Grade << endl;
}
else
{
cout << "Invalid Test Score:" << Score << endl;
return 2;
}
}
}
AvgScore = TotalScore / NumTests; // Finding the avg test score
cout << "Max Score: " << MaxScore << endl; // Printing Max score
cout << "Min Score: " << MinScore << endl; // Printing Min score
cout << "Avg Score: " << AvgScore << endl; // Printing Avg score
cout << "Number of Tests: " << NumTests << endl; // Printing Number of Tests
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>There are many places where you can improve on your code.</p>\n\n<ul>\n<li><p>In C++, you try to introduce variables as <em>late</em> as possible. So don't define all those <code>int</code> types in the beginning of your main program. It's only confusing and in general will lead to low maintainability and low performance. In fact, you will end up not needing them at all.</p></li>\n<li><p>You don't need <code><iomanip></code> or <code><string></code> for anything, so don't include them.</p></li>\n<li><p>Avoid doing <code>using namespace std</code> - this has been raised in many questions on the site. Similarly, you usually want to print <code>'\\n'</code> instead of <code>std::endl</code>, which flushes the buffer. For more, see <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">here</a>.</p></li>\n<li><p>Don't force the user of your program to know the internals of your program. If you can't open the file, consider printing something other than \"Failed to find inFile\". Sure, at least the author of the source code knows what <code>inFile</code> is (that's the name of a variable!), but maybe it would make more sense for the user to say \"input file\" (but OK, this is nitpicking :-)).</p></li>\n<li><p>If your data set was huge, it would make a lot of sense to count the number of scores and to accumulate the score while reading. In this case, it might be a better idea to just read all the scores into a suitable container (<code>std::vector</code>) and then to process that. In addition, the if-else statements are a mess, as you would probably agree. It's hard to read, difficult to understand, and not easy to modify. So whenever you see a big cluster of if-else statements, ask yourself whether a data driven approach would make sense.</p></li>\n<li><p>A line of code can't be any clearer than <code>cout << \"Max Score: \" << MaxScore << endl;</code>. Thus, a comment like <code>// Printing Max score</code> is just too verbose. Prefer comments that answer the question \"how\" and not \"what\". Good code explains itself via e.g., good naming conventions.</p></li>\n</ul>\n\n<p>I'd rewrite your program as follows:</p>\n\n<pre><code>#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <map>\n#include <functional>\n#include <algorithm>\n#include <numeric>\n#include <iterator>\n\nint main()\n{\n std::ifstream inFile(\"indata6.txt\");\n\n if (!inFile)\n {\n std::cout << \"Failed to find input file\\n\";\n return EXIT_FAILURE;\n }\n\n const std::map<int, char, std::greater<int> > grades = \n { \n { 90, 'A' },{ 80, 'B' },{ 70, 'C' },{ 60, 'D' } \n };\n\n std::vector<int> scores { \n std::istream_iterator<int>(inFile), \n std::istream_iterator<int>{} };\n\n std::cout << \"Test Scores & Grades\\n\";\n std::cout << \"--------------------\\n\";\n\n for(auto s : scores)\n {\n auto it = grades.lower_bound(s);\n std::cout << s << \" \";\n\n if (it == grades.cend())\n {\n std::cout << \"F\\n\";\n }\n else\n {\n std::cout << it->second << \"\\n\";\n }\n }\n\n const auto minmax = std::minmax_element(scores.cbegin(), scores.cend());\n\n std::cout << \"Max Score: \" << *(minmax.second) << \"\\n\"; \n std::cout << \"Min Score: \" << *(minmax.first) << \"\\n\";\n std::cout << \"Avg Score: \" << (std::accumulate(scores.cbegin(), scores.cend(), 0.0) / scores.size()) << \"\\n\";\n std::cout << \"Number of Tests: \" << scores.size() << \"\\n\";\n}\n</code></pre>\n\n<p>A few points from this program:</p>\n\n<ul>\n<li><p>Notice we first try to open the file. If it succeeds, great. If it doesn't, we exit early (with a proper exit code) and avoid possibly allocating memory etc. for variables we never ended up needing.</p></li>\n<li><p>Instead of an if-else mess, we take a data-driven approach powered by <code>std::map</code>. In this way, we just initialize the map to hold the point thresholds for various grades, and then later on do suitable searches into this data structure. It's much easier to maintain!</p></li>\n<li><p>We only read the scores once into a dynamic array (<code>std::vector</code>). This guy holds all the scores and allows us to iterate over it and use standard algorithms on it. Clean and nice.</p></li>\n<li><p>At the end, we do just this: <a href=\"https://en.cppreference.com/w/cpp/algorithm/minmax_element\" rel=\"nofollow noreferrer\"><code>std::minmax_element</code></a> gives us the smallest and largest element of a range. Similarly, <a href=\"https://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow noreferrer\"><code>std::accumulate</code></a> sums over all the elements, which we just divide by the number of elements, conveniently given to us by the <code>size()</code> method of the vector. </p></li>\n<li><p>I would also encourage you to look at functions. You could further separate pieces of the logic into functions. For instance, a natural function would be one that reads an input file into a vector and spits that out.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T09:42:46.397",
"Id": "214688",
"ParentId": "214663",
"Score": "3"
}
},
{
"body": "<p>Points additional to <a href=\"/a/214688\">Juho's review</a>:</p>\n\n<ul>\n<li><p>Instead of reading from a compiled-in filename, allow the user to specify the file to read (e.g. as a command argument). Even better, just accept input on <code>std::cin</code>; that gives much greater flexibility (e.g. will allow us to filter or combine sets of scores to pass to our program in a pipeline).</p></li>\n<li><p>Be careful with <code>TotalScore</code>, which is an <code>int</code>, and so could overflow when accumulating relatively few results (e.g. on platforms where <code>int</code> is 16 bits, at just 328 top marks as input). Using <code>unsigned int</code> will double that range; a longer type (such as <code>std::uint32_t</code>) will allow you to accumulate millions of results. For really large input sets, you'll want to keep an incremental mean rather than adding all the inputs - see <a href=\"http://people.ds.cam.ac.uk/fanf2/hermes/doc/antiforgery/stats.pdf\" rel=\"nofollow noreferrer\">Incremental calculation of weighted mean and variance</a> by Tony Finch for a good introduction to the method.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T10:09:55.440",
"Id": "415155",
"Score": "1",
"body": "Great additional points! I believe that one possible implementation for all kinds of incremental statistics is [Boost.Accumulators](https://www.boost.org/doc/libs/1_69_0/doc/html/accumulators.html)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T10:01:15.453",
"Id": "214691",
"ParentId": "214663",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T19:20:18.807",
"Id": "214663",
"Score": "4",
"Tags": [
"c++",
"performance",
"beginner"
],
"Title": "Reads a inFile and grades tests scores and finds max, min, and avg"
} | 214663 |
<p>Sentiment words behave very differently when under the semantic scope of negation. I want to use a slightly modified version of <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.202.6418&rep=rep1&type=pdf" rel="nofollow noreferrer">Das and Chen (2001)</a> They detect words such as <em>no, not,</em> and <em>never</em> and then append a "neg"-suffix to every word appearing between a negation and a clause-level punctuation mark. This method is very static and I want to create something a little bit more dynamic with the help of dependency parsing from spaCy.</p>
<p>This is an example of a tweet that I will process:</p>
<pre><code>RT @trader $AAPL 2012 is ooopen to Talk about patents with GOOG definitely not the treatment Samsung got heh someURL
</code></pre>
<p><a href="https://explosion.ai/demos/displacy?text=RT%20%40trader%20%24AAPL%202012%20is%20ooopen%20to%20Talk%20about%20patents%20with%20GOOG%20definitely%20not%20the%20treatment%20Samsung%20got%20heh%20http%3A%2F%2Ft.co%2FbFPm3CJ3&model=en_core_web_sm&cpu=1&cph=1" rel="nofollow noreferrer">See here</a> the visualized dependency parser in action on my string.
I am able to identify <em>not</em> as negation modifier of <em>got</em> with the following:</p>
<pre><code>negation_tokens = [tok for tok in doc if tok.dep_ == 'neg']
</code></pre>
<p>Next, I want define the scope of the negation: </p>
<pre><code>negation_head_tokens = [token.head for token in negation_tokens]
for token in negation_head_tokens:
end = token.i
start = token.head.i + 1
negated_tokens = doc[start:end]
print(negated_tokens)
# ooopen to Talk about patents with GOOG definitely not the treatment Samsung
</code></pre>
<p>Now I have defined the scope, I want to add "not" to certain words conditional on their POS-tag:</p>
<pre><code>list = ['ADJ', 'ADV', 'AUX', 'VERB']
for token in negated_tokens:
for i in list:
if token.pos_ == i:
print('not'+token.text)
# notooopen, notTalk, notdefinitely, notnot
</code></pre>
<p>Logically, I want to exclude <em>notnot</em> from the string. </p>
<p><strong>Full script</strong></p>
<pre><code>import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp(u'RT @trader $AAPL 2012 is ooopen to Talk about patents with GOOG definitely not the treatment Samsung got heh someURL', disable=['ner'])
pos_list = ['ADJ', 'ADV', 'AUX', 'VERB']
def negation(doc):
negation_tokens = [tok for tok in doc if tok.dep_ == 'neg']
negation_cue = [token.text for token in negation_tokens]
if not negation_tokens: # no negation token(s) present in the string
return doc
else:
negation_head_tokens = [token.head for token in negation_tokens]
new_doc = []
for token in negation_head_tokens:
end = token.i
start = token.head.i + 1
negated_tokens = doc[start:end]
for token in doc:
if token.text not in negation_cue:
if token in negated_tokens:
if token.pos_ in pos_list:
new_doc.append('not'+token.text)
continue
else:
pass
new_doc.append(token.text)
return new_doc
negated_doc = negation(doc)
print(negated_doc)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>['RT', '@trader', '$', 'AAPL', '2012', 'is', 'notooopen', 'to', 'notTalk', 'about', 'patents', 'with', 'GOOG', 'notdefinitely', 'the', 'treatment', 'Samsung', 'got', 'heh', 'someURL']
</code></pre>
<p><strong>Questions</strong></p>
<p>Q1: Is it possible to use a direct route instead of the creating a list with</p>
<pre><code>negation_cue = [token.text for token in negation_tokens]
</code></pre>
<p>and then check </p>
<pre><code>if token.text not in negation_cue:
</code></pre>
<p>Q2: Is it maybe faster to remove the <code>negation_cue</code> token at the end of the script from the returned doc?</p>
<p>Q3 / Most important question: Do you see any speed-improvements in my script</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T20:14:18.083",
"Id": "214665",
"Score": "2",
"Tags": [
"python",
"natural-language-processing"
],
"Title": "Define the scope of negation with the Dependency Parser of spaCy"
} | 214665 |
<p>This config has 3 main features but there seems to be a lot of duplication and I wonder if I could improve it.</p>
<p>1 Detect all pngs and jpgs in static/img and try a webp version if the requesting browser supports it</p>
<p>2 Detect non-ES6 supporting browsers and serve site.babel.js, otherwise serve site.js which is un-babelified</p>
<p>3 Proxy all other requests to a node app running on port 3000</p>
<pre><code>upstream node_upstream {
server node:3000;
keepalive 64;
}
#Required since SSL termination is higher up at the AWS load balancer
map $http_x_forwarded_proto $is_https {
default off;
https on;
}
map $http_accept $webp_suffix {
default "";
"~*webp" ".webp";
}
map $http_user_agent $script_file {
default "site.js";
"~MSIE" "site.babel.js";
"~Trident" "site.babel.js";
"~Opera.*Version/[0-9]\." "site.babel.js";
"~Opera.*Version/[0-1][0-9]\." "site.babel.js";
"~Opera.*Version/2[0-1]\." "site.babel.js";
"~AppleWebKit.*Version/[0-9]\..*Safari" "site.babel.js";
"~Chrome/[0-9]\." "site.babel.js";
"~Chrome/[0-2][0-9]\." "site.babel.js";
"~Chrome/3[0-3]\." "site.babel.js";
"~Chrome/4[0-3]\." "site.babel.js";
"~Edge/1[0-3]\." "site.babel.js";
}
server {
root /var/www/html/src;
gzip on;
# AWS traffic will come via a load balancer with the original protocol stored in http_x_forwarded_proto
# If this is set to http then we need to redirect any request onto https equivalent
# Should be ignored in non AWS environment as http_x_forwarded_proto should not be set
if ($http_x_forwarded_proto = "http") {
rewrite ^(.*)$ https://$http_host$1 permanent;
}
location = /static/site.js {
root /var/www/html/src;
expires 1y;
access_log off;
add_header Cache-Control "public";
try_files /static/$script_file =404;
}
location ~* ^/static/img/.+\.(png|jpg)$ {
root /var/www/html/src;
add_header Vary Accept;
expires 1y;
access_log off;
add_header Cache-Control "public";
try_files $uri$webp_suffix $uri =404;
}
location ~* ^/static/.*$
{
root /var/www/html/src;
expires 1y;
access_log off;
add_header Cache-Control "public";
}
location / {
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_pass http://node_upstream;
}
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
}
</code></pre>
| [] | [
{
"body": "<h2>root</h2>\n\n<p>The <code>root</code> directive is inherited. You have the same statement in the <code>server</code> block, and repeated in a number of <code>location</code> blocks. Only the first statement is necessary. See <a href=\"http://nginx.org/en/docs/http/ngx_http_core_module.html#root\" rel=\"nofollow noreferrer\">this document</a> for details.</p>\n\n<h2>location ~* ^/static/.*$</h2>\n\n<p>This can be replaced by the prefix location:</p>\n\n<pre><code>location /static/ { ... }\n</code></pre>\n\n<p>The prefix location is more efficient than the regular expression location. The precedence order is different, but that does not affect your current configuration. See <a href=\"http://nginx.org/en/docs/http/ngx_http_core_module.html#location\" rel=\"nofollow noreferrer\">this document</a> for details.</p>\n\n<h2>rewrite ^(.*)$ https://$http_host$1 permanent;</h2>\n\n<p>You can replace this with a <code>return</code> statement, thus eliminating a regular expression.</p>\n\n<pre><code>return 301 https://$http_host$request_uri;\n</code></pre>\n\n<h2>Nested location blocks</h2>\n\n<p>A number of statements are common to three <code>location</code> blocks, all of which represent URIs that begin with <code>/static/</code>. The <code>expires</code>, <code>access_log</code> and <code>add_header</code> directives are inherited.</p>\n\n<p>You could restructure your locations as follows:</p>\n\n<pre><code>location /static/ {\n root /var/www/html/src;\n expires 1y;\n access_log off;\n add_header Cache-Control \"public\";\n\n location = /static/site.js {\n try_files /static/$script_file =404;\n }\n location ~* ^/static/img/.+\\.(png|jpg)$ {\n add_header Vary Accept;\n add_header Cache-Control \"public\";\n try_files $uri$webp_suffix $uri =404;\n }\n}\nlocation / {\n ...\n}\n</code></pre>\n\n<p>This would improve efficiency as URIs which do not begin with <code>/static/</code> will not need to be checked against the regular expressions.</p>\n\n<p>The <code>add_header</code> directive has an additional inheritance rule. See <a href=\"http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header\" rel=\"nofollow noreferrer\">this document</a> for details.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T22:59:51.167",
"Id": "415117",
"Score": "0",
"body": "Thanks, nested location blocks is exactly the kind of thing i was looking for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T22:43:46.853",
"Id": "214670",
"ParentId": "214667",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214670",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T21:12:48.880",
"Id": "214667",
"Score": "2",
"Tags": [
"nginx"
],
"Title": "Nginx config with some conditionals"
} | 214667 |
<p>I have implemented a simple dynamic vector library in C. It is a header-only library.</p>
<p>Full library listing -
<code>void_vector.h:</code></p>
<pre><code>#ifndef VOID_VECTOR_H
#define VOID_VECTOR_H
typedef enum {
VV_SUCCESS,
VV_MALLOC_FAILURE
} vv_err;
typedef struct vv {
size_t length;
size_t size;
void *data[];
} void_vector;
void_vector* new_void_vector(size_t size);
vv_err vv_push(void_vector **vv, void *el);
void *vv_pop(void_vector *vv);
const void* vv_read_index(void_vector *vv, size_t index);
void delete_void_vector(void_vector *vv, void (del_el)(void*));
#ifdef VOID_VECTOR_IMPL
#undef VOID_VECTOR_IMPL
#include <stdlib.h>
#define defualt_size 16ul
void_vector*
new_void_vector(size_t size)
{
if (!size) size = defualt_size;
void_vector* vv = malloc(sizeof(void_vector) + sizeof(void*) * size);
if (vv) {
vv->size = size;
vv->length = 0;
}
return vv;
}
vv_err
vv_push(void_vector **vv, void *el)
{
if ((*vv)->length >= (*vv)->size) {
void_vector *new_vv = realloc((*vv), sizeof(void_vector)
+ sizeof(void*) * (*vv)->size * 2);
if (!new_vv) return VV_MALLOC_FAILURE;
(*vv) = new_vv;
(*vv)->size *= 2;
}
(*vv)->data[(*vv)->length] = el;
(*vv)->length++;
return VV_SUCCESS;
}
void*
vv_pop(void_vector *vv)
{
if(vv->length == 0) return NULL;
vv->length--;
return vv->data[vv->length];
}
const void*
vv_read_index(void_vector *vv, size_t index)
{
if (index > vv->length) return NULL;
return (vv->data[index]);
}
void
delete_void_vector(void_vector *vv, void (del_el)(void*))
{
if (!del_el) del_el = &free;
for (int i = vv->length; i; i--) {
del_el(vv->data[i-1]);
}
free(vv);
}
#endif /* VOID_VECTOR_IMPL */
#endif /* VOID_VECTOR_H */
</code></pre>
<p>I am using this as test bench - <code>void_vector_tb.c</code></p>
<pre><code>#include <stdio.h>
#define VOID_VECTOR_IMPL
#include "void_vector.h"
int
main (int argc, char **argv)
{
void_vector* vv = new_void_vector(4);
char *strings[10];
for (int i = 0; i < 10; i++) {
strings[i] = malloc(32);
snprintf(strings[i], 32, "This is String: %d", i);
}
for (int i = 0; i < 10; i++) {
vv_push(&vv, strings[i]);
}
for (int i = 0; i < vv->length; i++) {
printf("%d:\t%s\n", i+1, vv_read_index(vv, i));
}
char *s;
while(s = (char*) vv_pop(vv)) {
printf("%s\n", s);
}
for (int i = 0; i < 10; i++) {
vv_push(&vv, strings[i]);
}
delete_void_vector(vv, NULL);
}
</code></pre>
<p>I am not using a make file. Compilation is performed by <code>gcc -ggdb void_vector_tb.c -o void_vector_tb</code> </p>
<p>I would greatly appreciate your time and any comments but I'm particularly interested in the following points:</p>
<ul>
<li>Am I doing anything dangerous in this?</li>
<li>Is the code clear, what can I do to make it easier to follow?</li>
<li>Is there an obvious way to greatly improve the efficiency?</li>
<li>General style comments</li>
<li>I'm not overly concerned about the contents of <code>void_vector_tb.c</code>.</li>
</ul>
<p>I ran this through valgrind and got the following output:</p>
<pre><code>==7009== HEAP SUMMARY:
==7009== in use at exit: 0 bytes in 0 blocks
==7009== total heap usage: 14 allocs, 14 frees, 1,616 bytes allocated
==7009==
==7009== All heap blocks were freed -- no leaks are possible
==7009==
==7009== For counts of detected and suppressed errors, rerun with: -v
==7009== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code></pre>
<p>I am trying to minimize use of external libraries (although I don't think it would be possible to avoid stdlib.h). </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T12:27:31.087",
"Id": "415773",
"Score": "0",
"body": "\"Am I doing anything dangerous in this?\" Yeah you are using void pointers :) They tend to kill type safety and there are many better ways of generic programming."
}
] | [
{
"body": "<p>Overall, fairly good.</p>\n\n<blockquote>\n <p>Am I doing anything dangerous in this?</p>\n</blockquote>\n\n<p><strong>Lack of comments</strong></p>\n\n<p>I'd expect at least some commentary about the roll of the functions and how to use them near the function declaration section.</p>\n\n<p>Assume a user will read the header and not delve into implementation.</p>\n\n<p><strong>Unexpected type change</strong></p>\n\n<p>The stored ellement is a <code>void *</code>, changing the return type to <code>const</code> is not good.</p>\n\n<pre><code>// const void* vv_read_index(void_vector *vv, size_t index)\nvoid* vv_read_index(void_vector *vv, size_t index)\n</code></pre>\n\n<p><strong>Overuse of <code>NULL</code></strong></p>\n\n<p><code>vv_pop(), vv_read_index()</code> return <code>NULL</code> as an error indicator and can return <code>NULL</code> as a valid return. If <code>NULL</code> is not to be allowed (which I think is a bad idea) as a storable <code>void *</code>, <code>vv_push(&vv, NULL)</code> should error.</p>\n\n<p>I'd re-work calls to return an error code on <code>vv_pop()</code>, like <code>vv_err vv_pop(void_vector **vv, void **el)</code>.</p>\n\n<p>It seems odd to have 2 forms of error signaling: error codes and <code>NULL</code>.</p>\n\n<p><strong>\"default size\"</strong></p>\n\n<p>I see no real value in a default size of 16. Suggest setting aside <code>size == 0</code> as something special and allow an initial vector size of 0. Add code to handle doubling array size when size is 0. </p>\n\n<p>Create a <code>VV_DEFAULT_SIZE 16u</code> if desired for the user to call with <code>new_void_vector(VV_DEFAULT_SIZE)</code>.</p>\n\n<p><strong>Overflow</strong></p>\n\n<p>I'd detect overflow in size computations.</p>\n\n<p><strong>Tolerate freeing <code>NULL</code></strong></p>\n\n<p><code>free(NULL)</code> is well defined. I'd expect the same with <code>delete_void_vector(NULL, foo)</code>. Currently code dies on this.</p>\n\n<blockquote>\n <p>Is the code clear, what can I do to make it easier to follow?</p>\n</blockquote>\n\n<p><strong>Naming convention</strong></p>\n\n<p>Recommend to use the same one prefix with all external types, names and functions. </p>\n\n<pre><code>// void_vector.h\nvv.h\n\n// VOID_VECTOR_H\nVV_H\n\n// void_vector* new_void_vector(size_t size);\nvoid_vector* vv_new(size_t size);\n</code></pre>\n\n<p>Or use <code>void_vector</code> instead of <code>vv</code> throughout, not both.</p>\n\n<p><strong>Allocate to the size of the object, not type</strong></p>\n\n<p>Allocating to the size of the referenced object is 1) less error prone, 2) easier to review 3) easier to maintain than allocating to the type.</p>\n\n<pre><code>// void_vector* vv = malloc(sizeof(void_vector) + sizeof(void*) * size);\nvoid_vector* vv = malloc(sizeof *vv + sizeof *vv->data * size);\n</code></pre>\n\n<p><strong>Avoid unnecessary suffixes</strong></p>\n\n<p>An <code>L</code>, <code>l</code>, <code>LL</code>, <code>ll</code> is needed a lot less than one thinks. In the following case, <code>L</code> certainty not needed. The <code>u</code> <em>is</em> useful though. I am curios as to why OP thought is was needed - what issue was of concern?</p>\n\n<pre><code>/// #define defualt_size 16ul\n#define defualt_size 16u\n</code></pre>\n\n<p><strong>Use <code>const</code></strong></p>\n\n<p><code>const</code> would help convey that the function is not altering <code>*vv</code></p>\n\n<pre><code>// vv_read_index(void_vector *vv ...\nvv_read_index(const void_vector *vv ...\n</code></pre>\n\n<blockquote>\n <p>Is there an obvious way to greatly improve the efficiency?</p>\n</blockquote>\n\n<p>Allocations only increase as <code>vv_pop()</code> does not reduce things. This can make for an inefficiency of memory usage.</p>\n\n<p>IMO, a more advanced scheme could decrease by 1/2 when size needed falls below 25% or 33%.</p>\n\n<blockquote>\n <p>General style comments</p>\n</blockquote>\n\n<p><strong>Spell check</strong></p>\n\n<pre><code>// #define defualt_size 16ul\n#define default_size 16ul\n</code></pre>\n\n<p><strong><code>!</code> vs. <code>></code></strong></p>\n\n<p>Minor: With arithmetic concerns, <code>></code> is more readily understood that <code>!</code> negation.</p>\n\n<pre><code>// if (!size)\nif (size > 0)\n</code></pre>\n\n<blockquote>\n <p>I'm not overly concerned about the contents of void_vector_tb.c.</p>\n</blockquote>\n\n<p><strong>Avoid naked magic numbers</strong></p>\n\n<p>Replace <code>10</code> with <code>#define VV_STR_N 10</code>, <code>32</code> with <code>#define VV_STR_SZ 3</code>2,</p>\n\n<p><strong>Cast not needed</strong></p>\n\n<pre><code>// while(s = (char*) vv_pop(vv)) {\nwhile(s = vv_pop(vv)) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T08:00:16.990",
"Id": "415146",
"Score": "1",
"body": "First off thank you for the detailed and extended review. I will make your recommended changes this evening. I have a single follow up question. Currently the function `const void* vv_read_index(vv, i)` returns a `const void*` and you are recommending it should return `void*`.Originally I did this as I considered the returned value to \"belong\" to the the vector and did not want the user changing it. Is there a better way to achieve this without confusing types or do I just trust the user not to corrupt the data store?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T13:32:17.300",
"Id": "415186",
"Score": "0",
"body": "@eternalnewbie `vv` stores a _pointer_. Returning `const void *` or `void *` does not allow the use to change the _pointer_ stored in `vv`. Returning `const void *` does not allow the use to change what the pointer points to. That is not `vv` concern so `vv_read_index()` should return what it was given, a `void *`. It sounds like to are thinking about returning the address of the pointer: `const void**\nvv_index_address(void_vector *vv, size_t index)\n{\n if (index > vv->length) return NULL;\n return (&vv->data[index]);\n}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T18:59:07.260",
"Id": "415210",
"Score": "0",
"body": "I was trying to avoid a situation where the user would call `p = vv_read_index(vv, i);` then `free(p);` finally followed by `delete_vv(vv);`. This would cause double a free() which would be UB. I tried this out and it works and it works fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T20:58:04.800",
"Id": "415219",
"Score": "0",
"body": "I think my best option is to take your advice and return void*. But also note in the usage comments and readme about the potential UB."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T02:45:02.253",
"Id": "415249",
"Score": "0",
"body": "I now see _why_ you coded a return of `const`. Yet the memory management of the `void*` pointers is not really the concern of `vv`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T02:46:29.623",
"Id": "415250",
"Score": "0",
"body": "@eternal newbie Another oops. `for (int i = vv->length; i; i--) {` --> `for (size_t i = vv->length; i; i--) {`. This implies you (and I) did not compile with all warnings on. Save time enable all warnings."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T02:01:49.287",
"Id": "214676",
"ParentId": "214668",
"Score": "5"
}
},
{
"body": "<p>I have two things to add to @chux's comments.</p>\n\n<p>The <code>vv_read_index</code> function can read past the end of the vector if <code>index</code> is equal to <code>vv->length</code>. If <code>vv->length == vv->size</code>, this will read past the end of allocated memory.</p>\n\n<p>While the cast in <code>while(s = (void *) vv_pop(vv))</code> is not needed, the use of an assignment within a conditional test can be misread as a typo. (Some compilers will issue a warning when you do this.) To clarify the intent, you can use</p>\n\n<pre><code>while((s = vv_pop(vv)) != NULL)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T06:20:30.017",
"Id": "214681",
"ParentId": "214668",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "214676",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T21:19:53.433",
"Id": "214668",
"Score": "12",
"Tags": [
"c",
"vectors"
],
"Title": "Dynamic vector of void* in C"
} | 214668 |
<p><strong>Description</strong></p>
<blockquote>
<p>A robot lands on Mars, which happens to be a cartesian grid; assuming that we hand the robot these instructions, such as LFFFRFFFRRFFF, where "L" is a "turn 90 degrees left", "R" is a "turn 90 degrees right", and "F" is "go forward one space, please write control code for the robot such that it ends up at the appropriate-and-correct destination, and include unit tests.</p>
</blockquote>
<p>Here is an example output with command "FF":</p>
<p>[0, 2]</p>
<p><strong>Code</strong></p>
<pre><code>class Robot {
private int x;
private int y;
private int currentDirection;
Robot() {
this(0, 0);
}
Robot(int x, int y) {
this.x = x;
this.y = y;
currentDirection = 0;
}
public void move(String moves) {
for (char ch : moves.toCharArray()) {
if (ch == 'R') currentDirection += 1;
if (ch == 'L') currentDirection -= 1;
currentDirection = currentDirection % 4;
if (ch != 'F') continue;
System.out.println(currentDirection);
if (currentDirection == 0) {
y += 1;
} if (currentDirection == 1) {
x += 1;
} if (currentDirection == 2) {
y -= 1;
} if (currentDirection == 3) {
x -= 1;
}
}
}
public void reset() {
x = 0;
y = 0;
currentDirection = 0;
}
public String position() {
return x + ":" + y;
}
}
class Main {
public static void main(String[] args) {
Robot robot = new Robot();
robot.move("FF");
System.out.println(robot.position()); // 0,2
robot.reset();
System.out.println(robot.position()); // 0,0
robot.move("FFRF");
System.out.println(robot.position()); // 1,2
robot.reset();
robot.move("FFRRRFF");
System.out.println(robot.position()); // -2,2
}
}
</code></pre>
<p>How can I make this code more object oriented?</p>
| [] | [
{
"body": "<p>I would consider refactoring direction into an enum, instead of a magic number. This would allow to encapsulate the related logic in this type.</p>\n\n<p>It might look like that:</p>\n\n<pre><code> enum Direction {\n UP(0, 1),\n RIGHT(1, 0),\n DOWN(0, -1),\n LEFT(-1, 0);\n\n final int xVector;\n final int yVector;\n\n private final Direction FIRST = Direction.values()[0];\n private final Direction LAST = Direction.values()[Direction.values().length];\n\n Direction(int xVector, int yVector) {\n this.xVector = xVector;\n this.yVector = yVector;\n }\n\n Direction rotatedLeft() {\n return this == FIRST\n ? LAST // cycle complete\n : Direction.values()[ordinal() - 1]; // previous value\n }\n\n Direction rotatedRight() {\n return this == LAST\n ? FIRST // cycle complete\n : Direction.values()[ordinal() + 1]; // next value\n }\n }\n</code></pre>\n\n<p>And then the <code>Robot</code> code becomes (including some subjective clean up, unrelated to the object-oriented aspect itself):</p>\n\n<pre><code>class Robot {\n private int x;\n private int y;\n private Direction currentDirection;\n\n Robot() {\n this(0, 0);\n }\n\n Robot(int x, int y) {\n this.x = x;\n this.y = y;\n currentDirection = Direction.UP;\n }\n\n public void move(String moves) {\n for (char code : moves.toCharArray()) {\n // a matter of taste, I like to extract logic \n // out of looping constructs for clarity\n move(code);\n }\n }\n\n private void move(char code) {\n switch (code) {\n case 'R': {\n currentDirection = currentDirection.rotatedRight();\n break;\n }\n case 'L': {\n currentDirection = currentDirection.rotatedLeft();\n break;\n }\n case 'F': {\n // you'd call the println thing here.\n // as it's not part of the requirements I assumed it to be a debugging artifact\n this.x += currentDirection.xVector;\n this.y += currentDirection.yVector;\n break;\n }\n }\n }\n\n public void reset() {\n x = 0;\n y = 0;\n currentDirection = Direction.UP;\n }\n\n public String position() {\n return x + \":\" + y;\n }\n}\n</code></pre>\n\n<p>I think this is more object-oriented, and also an improvement. </p>\n\n<p>You could take it one step further and encapsulate the <code>x</code> and <code>y</code> coordinates in a little standalone class (<code>Position</code>). Like so:</p>\n\n<pre><code> class Position {\n static final Position DEFAULT = new Position(0, 0);\n\n final int x;\n final int y;\n\n public Position(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public Position movedInto(Direction direction) {\n return new Position(x + direction.xVector, y + direction.yVector);\n }\n\n @Override\n public String toString() {\n return x + \":\" + y;\n }\n }\n</code></pre>\n\n<p>Then in the <code>Robot</code> class you replace <code>x</code> and <code>y</code> fields with <code>Position position</code>, and you no longer recalculate the position in the <code>Robot</code> class, as you can simply go:</p>\n\n<pre><code>case 'F': {\n position = position.movedInto(currentDirection);\n break;\n}\n</code></pre>\n\n<p>in the <code>move</code> method.</p>\n\n<p>Plus:</p>\n\n<pre><code> public void reset() {\n position = Position.DEFAULT;\n currentDirection = Direction.UP;\n }\n\n public String position() {\n return position.toString();\n }\n</code></pre>\n\n<p>Yet another idea would be to encapsulate the move codes themselves into a class or classes. It's sometimes hard to say where to draw the line, as making code more and more OO comes at the cost of more boilerplate, and can be a form of overengineering.</p>\n\n<p>I admit I haven't tested my refactored version, I only approached the question in terms of code design.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T23:11:51.783",
"Id": "415118",
"Score": "0",
"body": "Since this is a programming-challenge, I like the `Direction` enum refactoring (+1), but for a future-friendly robot, I think `enum Direction` is a bad idea. (See my answer.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T23:30:35.623",
"Id": "415121",
"Score": "0",
"body": "Fixed the bug, thanks. The azimuth / alpha (I guess we could call it that?) is a neat alternative to an enum. An alpha value is more flexible as you pointed out, the cost is that recalculating `x` and `y` when the direction is, say, 270, won't look as straightforward. So I feel it's a tradeoff between explicity and flexibility."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T22:59:12.753",
"Id": "214672",
"ParentId": "214669",
"Score": "8"
}
},
{
"body": "<h1>Initialization</h1>\n\n<p>As written, your robot lander can land at any X,Y coordinate on your grid, but will always be facing in the positive Y-axis direction. This seems unreasonable. If wind, turbulence can cause a position uncertainty, which requires initializing the robot at a particular X,Y coordinate, it seems reasonable to assume it might also land in any facing.</p>\n\n<pre><code>Robot() {\n this(0, 0, 0);\n}\n\nRobot(int x, int y) {\n this(x, y, 0);\n}\n\nRobot(int x, int y, int initial_facing) {\n // ...\n}\n</code></pre>\n\n<hr>\n\n<h1>Commands & Instructions</h1>\n\n<p>Your instructions are a series of single letter commands, but you can't actually send a single command to the robot. You should separate the individual commands from the series of instructions. Something like:</p>\n\n<pre><code>void turn_left() { ... }\nvoid turn_right() { ... }\nvoid move_forward() { ... }\n\npublic void command(char command_letter) {\n switch (command_letter) {\n case 'L': turn_left(); break;\n case 'R': turn_right(); break;\n case 'F': move_forward(); break;\n default: throw new IllegalArgumentException(\"Invalid command: \"+command_letter);\n }\n}\n\npublic void instructions(String moves) {\n for (char command_letter : moves.toCharArray()) {\n command(command_letter);\n }\n}\n</code></pre>\n\n<hr>\n\n<h1>Where am I?</h1>\n\n<p><code>position()</code> returns a <code>String</code> containing the coordinates of the robot. If a control program wants to query the position of the robot, in order to determine what commands should be sent to send it to the desired location, it would need to parse that string back into integer values.</p>\n\n<p>Consider instead returning the actual integer positions, possibly like:</p>\n\n<pre><code>public int[] position() {\n return new int[]{ x, y };\n}\n</code></pre>\n\n<p>Alternately, you might want to create a <code>class Position</code> which can store the x,y location of the robot. Or you could use <code>java.awt.Point</code></p>\n\n<pre><code>public Point position() {\n return new Point(x, y);\n}\n</code></pre>\n\n<p>Perhaps override the <code>toString()</code> method to return a human friendly description of the robot, including its position. Or maybe a <code>position_as_string()</code> method.</p>\n\n<p>Which way is the robot facing? Can't directly tell! You currently have to query the <code>position()</code>, then <code>move(\"F\")</code>, followed by <code>position()</code>, and then compare the positions to determine which way the robot is facing! How about adding a <code>facing()</code> method?</p>\n\n<hr>\n\n<p>Learn how to write proper unit tests. For example, with JUnit5, you could write:</p>\n\n<pre><code>import static org.junit.jupiter.api.Assertions.assertEquals;\nimport org.junit.jupiter.api.Test;\n\nclass RobotTests {\n\n private final Robot robot = new Robot();\n\n @Test\n void starts_at_origin() {\n assertEquals(\"0:0\", robot.position());\n }\n\n @Test\n void move_forward_twice() {\n robot.move(\"FF\");\n assertEquals(\"0:2\", robot.position());\n }\n\n @Test\n void move_and_turn_right() {\n robot.move(\"FFRF\");\n assertEquals(\"1:2\", robot.position());\n }\n\n @Test\n void three_rights_make_a_left() {\n robot.move(\"FFRRRFF\");\n assertEquals(\"-2:2\", robot.position());\n }\n\n @Test\n void but_one_left_does_not() {\n robot.move(\"FFLFF\");\n assertEquals(\"-2:2\", robot.position());\n }\n}\n</code></pre>\n\n<p>Notice that each test is run in a brand-new <code>RobotTests</code> instance, so you don't need to call <code>robot.reset()</code> between each.</p>\n\n<p>If you run this unit test, you'll find 4 of 5 tests pass, one test fails. I'll leave you to figure out why.</p>\n\n<hr>\n\n<h2>Additional Concerns</h2>\n\n<p><code>currentDirection</code> taking on the values <code>0</code>, <code>1</code>, <code>2</code> and <code>3</code> to represent the 4 cardinal directions is limiting. If later, you want to add in diagonal moves (<code>NW</code>, <code>SW</code>, <code>SE</code>, or <code>NE</code>), would you use the values 4 and above to represent them? Or would you renumber the original 4 directions to be <code>0</code>, <code>2</code>, <code>4</code> and <code>6</code>, and use <code>1</code>, <code>3</code>, <code>5</code>, and <code>7</code> for the diagonal directions?</p>\n\n<p>You might be tempted to use an <code>enum</code> for the direction values, but I think that would be a bad idea. I would use <code>0</code>, <code>90</code>, <code>180</code>, and <code>270</code> as direction values. These have physical <em>meaning</em>. If later your robot is allowed a more realistic <code>double x, y;</code> coordinate system, you could also change to use <code>double currentDirection;</code> and allow turns of a fraction of a degree. With <code>enum</code>, you'd lose this possible future flexibility.</p>\n\n<p>As an alternative, you might also consider using a directional vector:</p>\n\n<pre><code>int dx=0, dy=1; // currentDirection = 0°\n</code></pre>\n\n<p>And move_forward simply becomes:</p>\n\n<pre><code>x += dx;\ny += dy;\n</code></pre>\n\n<p>And a turn right could become:</p>\n\n<pre><code>int old_dx = dx;\n\ndx = dy;\ndy = -old_dx;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T23:14:54.170",
"Id": "415120",
"Score": "1",
"body": "This is solid advice. Personally I don't think an enum is a bad solution if we can assume the requirements aren't going to change."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T23:06:52.923",
"Id": "214674",
"ParentId": "214669",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T21:38:41.967",
"Id": "214669",
"Score": "6",
"Tags": [
"java",
"object-oriented",
"programming-challenge"
],
"Title": "Predict mars robot position"
} | 214669 |
<p>I have come up with the following snippet by building upon the answers given to my <a href="https://stackoverflow.com/questions/54964525/how-should-one-prepare-the-stack-when-calling-exitprocess">StackOverflow question</a>. Just trying to get some other eyeballs to review things so that they can point out any egregious mistakes that I probably made.</p>
<p>One area that was a bit tricky to me to get working is the bottom half of the <code>readFileHeader</code> label; there seemed to be some conflicting information about the <code>cmov</code> instruction and I still don't quite understand if I "should've" gone with an alternative that involves a jump or two. Sure, such a change is a micro-optimization but a huge part of this exercise to me is trying to understand the way different constructs affect the instruction pipeline and whatnot.</p>
<pre><code>include WindowsApi.inc ; imports all the "magic" constants that are in the following code
include WString.inc ; imports the macro for creating constant unicode strings
var0 textequ <rcx>
var1 textequ <rdx>
var2 textequ <r8>
var3 textequ <r9>
var4 textequ <qword ptr [(rsp + 20h)]>
var5 textequ <qword ptr [(rsp + 28h)]>
var6 textequ <qword ptr [(rsp + 30h)]>
TRUE = 1h
.const
align 2
filePath: WString <C:/Temp/Validation.csv>
.code
Main proc
sub rsp, 1048h ; align with 16 while simultaneously making room on the stack for the "home space", some parameters, and a 4096 byte buffer
lea var0, filePath ; put address of file path into parameter slot 0
mov var1, FILE_ACCESS_READ ; put access mode into parameter slot 1
mov var2, FILE_SHARE_READ ; put share mode into parameter slot 2
xor var3, var3 ; put security attributes into parameter slot 3
mov var4, FILE_DISPOSITION_OPEN ; put disposition into parameter slot 4
mov var5, FILE_FLAG_NORMAL ; put flags into parameter slot 5
mov var6, WINDOWS_NULL ; put pointer to template handle into parameter slot 6
call CreateFile ; create file handle
cmp rax, WINDOWS_INVALID_HANDLE ; validate file handle
je exitMain ; skip to exit point if create validation failed
mov var5, rax ; save a reference to the file handle for later (taking advantage of the unused parameter slot 5)
jmp readFileHeader ; skip to read file header
readFileBody:
xor eax, eax ; TODO: something useful with the number of bytes read in ecx...
readFileHeader:
mov var0, var5 ; put file handle into parameter slot 0
lea var1, qword ptr [(rsp + 38h)] ; put pointer to file buffer into parameter slot 1
mov var2, 1000h ; put requested number of bytes to read into parameter slot 2
lea var3, var6 ; put pointer to actual number of bytes that were read into parameter slot 3 (taking advantage of the unused parameter slot 6)
mov var4, WINDOWS_NULL ; put overlapped pointer into parameter slot 4
call ReadFile ; read file handle
mov rcx, var6 ; put pointer to actual number of bytes that were read into rcx
mov edx, TRUE ; assume that body should be processed by storing TRUE in edx
test eax, eax ; validate file read operation (non-zero == no errors)
cmovz edx, eax ; store zero in edx if file read operation failed
test ecx, ecx ; check for end of file (non-zero == more data)
cmovz edx, ecx ; store zero in edx if end of file reached
test edx, edx ; test edx for zero
jne readFileBody ; skip to read file body if edx was not zero
readFileFooter:
; TODO: properly handle errors by inspecting the value of eax...
mov var0, var5 ; put the reference to the file handle into parameter slot 0
call CloseHandle ; close file handle
exitMain:
xor ecx, ecx ; set return value to zero
call ExitProcess ; return control to Windows
Main endp
end
</code></pre>
<hr>
<p><strong>Edit</strong>; here is the best alternative I have been able to imagine so far; reduces total number of instructions from 9 to 6:</p>
<pre><code>call ReadFile ; read file handle
mov ecx, 0FFFFFFFFh ; put max 32-bit value into ecx
test eax, eax ; validate file read operation (non-zero == no errors)
cmovz ecx, eax ; if file read operation failed, put zero into ecx
and rcx, var6 ; if rcx is not zero, put the number of bytes read from var6 into rcx
jne readFileBody ; if rcx is not zero, skip to readFileBody
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T00:19:09.590",
"Id": "415122",
"Score": "0",
"body": "What is the conflicting information about cmov? btw there cannot be information that unconditionally either recommends cmov or disrecommends it because it is situational."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T00:20:35.033",
"Id": "415123",
"Score": "0",
"body": "@harold Maybe my wording there was quite poor; I suppose a better way to put things is that I don't quite understand the conditions of when `cmov` should and should not be used. I also suppose it is worth noting that I originally choose to go with `cmov` because 1) it was easier for me to parse the code and 2) it seemed \"bad\" to jump \"within a loop\"."
}
] | [
{
"body": "<h2>General/Style</h2>\n\n<ul>\n<li><p><strong>Line up instructions and operands in vertical columns to improve readability</strong> (like you've done with the comments); e.g.:</p>\n\n<pre><code>mov var6, WINDOWS_NULL ; put pointer to template handle into parameter slot 6\ncall CreateFile ; create file handle\ncmp rax, WINDOWS_INVALID_HANDLE ; validate file handle\nje exitMain ; skip to exit point if create validation failed\nmov var5, rax ; save a reference to the file handle for later (taking advantage of the unused parameter slot 5)\njmp readFileHeader ; skip to read file header\n; <snip>\nmov rcx, var6 ; put pointer to actual number of bytes that were read into rcx\nmov edx, TRUE ; assume that body should be processed by storing TRUE in edx\ntest eax, eax ; validate file read operation (non-zero == no errors)\ncmovz edx, eax ; store zero in edx if file read operation failed\ntest ecx, ecx ; check for end of file (non-zero == more data)\ncmovz edx, ecx ; store zero in edx if end of file reached\ntest edx, edx ; test edx for zero\n</code></pre></li>\n<li><p>This is totally subjective and dependent on your preferred coding style, so you're free to ignore it, but I like to <strong>write assembler directives in all uppercase</strong> to make them easier to distinguish from instruction opcodes and registers. So, I'd write <code>PROC</code>, <code>END</code>, <code>TEXTEQU</code>, <code>ALIGN</code>, and so on in all caps.</p></li>\n<li><p>You've defined a series of <code>var*</code> constants like so:</p>\n\n<pre><code>var0 textequ <rcx>\nvar1 textequ <rdx>\nvar2 textequ <r8>\nvar3 textequ <r9>\nvar4 textequ <qword ptr [(rsp + 20h)]>\nvar5 textequ <qword ptr [(rsp + 28h)]>\nvar6 textequ <qword ptr [(rsp + 30h)]>\n</code></pre>\n\n<p>Presumably, these are intended to encapsulate the Windows x64 calling convention for argument passing. But if that's the case, they are misnamed. They're not <em>var</em>iables at all—they're <em>arg</em>uments. If you must define these, I suggest calling them <code>arg*</code>.</p>\n\n<p>But <strong>I'd really suggest just not defining them at all. If you're going to program in assembly, you need to know your standard calling conventions like the back of your hand.</strong> Maintenance programmers who don't know them or can't recall them need to stop and look them up. They're not going to change, so there's little point in trying to hide them away behind constants. That just obfuscates the code, in my opinion. It also hides the fact that some uses of <code>var*</code> access memory (dereferencing an address to obtain a value), while others are just reading an enregistered value. There's a big difference between the two, both in semantics and performance, so good code should make that difference obvious to the reader.</p>\n\n<p>Also, if you are going to keep them, your <strong>capitalization is inconsistent</strong>. Other constants (e.g., <code>TRUE</code>) are written in all-caps (which is a good convention). Why aren't these constants also written in all-caps?</p>\n\n<p>Finally, if you're going to keep them, use them consistently. You forgot to use <code>var0</code> when calling the <code>ExitProcess</code> function:</p>\n\n<pre><code>xor ecx, ecx ; set return value to zero\ncall ExitProcess ; return control to Windows\n</code></pre></li>\n<li><p>Although <code>JE</code> == <code>JZ</code>, and <code>JNE</code> == <code>JNZ</code>, <strong>prefer to use the mnemonic with the most appropriate semantic meaning</strong>. After a <code>CMP</code> instruction, when you're checking for equality, either <code>JE</code> or <code>JNE</code> makes the most sense. But after a <code>TEST</code> instruction, where you're ANDing a register with itself just to set the zero flag, a <code>JZ</code> or <code>JNZ</code> makes the most sense. For example, I would rewrite:</p>\n\n<pre><code>test edx, edx ; test edx for zero\njne readFileBody ; skip to read file body if edx was not zero\n</code></pre>\n\n<p>as</p>\n\n<pre><code>test edx, edx\njnz readFileBody\n</code></pre>\n\n<p>(You did this already with <code>TEST</code>+<code>CMOVZ</code>.)</p></li>\n<li><p>Instead of packing the information about how you arrived at a magic number in a comment, <strong>write the arithmetic out explicitly</strong>. The assembler will fold the operations at assembly-time, so there won't be any cost. It's just more self-documenting for people looking at the code. In particular, this instruction:</p>\n\n<pre><code> sub rsp, 1048h ; align with 16 while simultaneously making room on the stack for the \"home space\", some parameters, and a 4096 byte buffer\n</code></pre></li>\n<li><p>Some of your comments are a bit too verbose. This is subjective, and it's ironic for me to be the one saying this, because I tend to like to write long, descriptive comments, but you do have to maintain the right balance. Per-line comments that I write in \"real\" code are much shorter than the ones I regularly write in Stack Overflow and Code Golf answers, since those are intended more for expository purposes than real documentation. They're also intended to be understandable by people who aren't assembly-language programmers, but your assembly-language code shouldn't necessarily be targeting that same audience.</p></li>\n<li><p>You know that the <code>ExitProcess</code> function <em>should</em> not ever return control to your code, but I (and compilers) like to assert that by placing a trap immediately after the call. A simple <code>int 3</code> will do; it's a simple, one-byte opcode (0xCC) that causes either a break into the debugger (if one is attached) or a crash.</p>\n\n<pre><code>exitMain:\n xor ecx, ecx ; process exit code is 0\n call ExitProcess ; return control to Windows\n int 3 ; trap if control ever reaches here\n</code></pre></li>\n</ul>\n\n<h2>Danger, Will Robinson!</h2>\n\n<p>You are allocating more than 4K bytes on the stack, which may be larger than the size of a page. Given the way the virtual memory manager works, you need to touch every 4Kth byte in order to force the stack to grow to the requested size. Otherwise, you risk getting access violations from hitting an uncommitted page.</p>\n\n<p>Microsoft's compiler automatically inserts stack-walking code that does this for you whenever you allocate more than 4K bytes of local variables inside of a function. This comes in the form of a call to the <code>__chkstk</code> function, which just reads every 4Kth byte from the previous stack top to the new stack top, ensuring that all of the necessary stack-reserved pages have actually been committed. (If there is no more memory available to commit the pages, then <code>__chkstk</code> fails.)</p>\n\n<p>So, in this case, the compiler would generate prologue code like the following:</p>\n\n<pre><code>Main PROC\n mov eax, 1048h\n call __chkstk\n sub rsp, rax\n ; ...\n</code></pre>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/4123609/allocating-a-buffer-of-more-a-page-size-on-stack-will-corrupt-memory\">Allocating a buffer of more a page size on stack will corrupt memory?</a> and <a href=\"https://stackoverflow.com/questions/8400118/what-is-the-purpose-of-the-chkstk-function\">What is the purpose of the _chkstk() function?</a> on Stack Overflow.</p>\n\n<h2>Peephole Optimization</h2>\n\n<ul>\n<li><p><strong>Don't use <code>LEA</code> when <code>MOV</code> will do.</strong> The mnemonic suggests that <code>LEA</code> is the way to load an address, and indeed it will do that, but so will <code>MOV</code>, as long as you use the <code>OFFSET</code> operator. Substitute:</p>\n\n<pre><code>lea var0, filePath\n</code></pre>\n\n<p>with</p>\n\n<pre><code>mov var0, OFFSET filePath\n</code></pre>\n\n<p>Honestly, the biggest use of <code>LEA</code> in assembly code is as a fancy way to do general-purpose integer arithmetic on non-address values, since it can perform addition with multiple operands, add <em>and</em> scale (by limited powers of two), simulate a three-operand instruction, and not clobber the flags. You will need it for scaled loads of addresses, but again, there, you're using its fancy address-calculation machinery, not simply to load an offset.</p></li>\n<li><p><strong>Use the non-volatile registers</strong> (<code>RBX</code>, <code>RBP</code>, <code>RDI</code>, <code>RSI</code>, and <code>R12</code> through <code>R15</code>) <strong>to store temporary values that you need to persist across function calls.</strong> The calling convention requires the contents of these registers to be persisted across calls, so anything you have in them will be safe. This abundance of registers on x64 allows you to avoid storing to the stack, and gain a bit more speed. So, replace:</p>\n\n<pre><code>mov var5, rax ; save a reference to the file handle for later (taking advantage of the unused parameter slot 5)\n</code></pre>\n\n<p>with something like:</p>\n\n<pre><code>mov r15, rax\n</code></pre></li>\n<li><blockquote>\n <p>there seemed to be some conflicting information about the cmov instruction and I still don't quite understand if I \"should've\" gone with an alternative that involves a jump or two.</p>\n</blockquote>\n\n<p>I'm not sure what the conflicting information was, but I can make it pretty simple for you:</p>\n\n<ul>\n<li>If the branch is <strong><em>predictable</em></strong>, then use an actual branch (jump). That will be faster (less overhead). Trust the branch predictor to do its job.</li>\n<li>If the branch is <strong><em>not predictable</em></strong> (because you have completely random input, or because it oscillates back and forth), then it is <em>probably</em> better to write branchless code using something like <code>CMOVcc</code> or <code>SETcc</code>. This will avoid the possibility of branch misprediction, at the cost of executing additional code each time.</li>\n</ul>\n\n<p>That's a good enough rule of thumb. Correctly-predicted branches are virtually free; mispredicted branches are extremely slow (relatively speaking). If you want more information, see <a href=\"https://stackoverflow.com/questions/40991778/an-expensive-jump-with-gcc-5-4-0/40993519#40993519\">this answer</a>.</p>\n\n<p>Also keep in mind, though, that it is generally pointless to optimize code that is not a performance hotspot (like an inner loop). The branching code is shorter and simpler to write, so that should be your first instinct.</p>\n\n<p><strong>Branching code is especially appropriate for error handling code like what you have here</strong>, since:</p>\n\n<ul>\n<li>Error handling is (almost) never a performance hotspot, and</li>\n<li>Errors should be rare occurrences, and thus the direction of execution in an error check will be correctly predicted by the CPU's built-in branch predictor.</li>\n</ul>\n\n<p>In fact, optimizing C and C++ compilers even go so far as to explicitly put error-handling code on a cold path, and <a href=\"https://stackoverflow.com/questions/30130930/is-there-a-compiler-hint-for-gcc-to-force-branch-prediction-to-always-go-a-certa/30138565#30138565\">there are annotations you can use to request this</a> if the optimizer isn't smart enough to do it on its own.</p>\n\n<p>Your current code is something like:</p>\n\n<pre><code> call ReadFile\n mov rcx, var6 ; rcx <= count of bytes read\n mov edx, TRUE ; assume success\n test eax, eax ; read failed?\n cmovz edx, eax ; edx = ((eax == 0) ? 0 : edx\n test ecx, ecx ; reached EOF?\n cmovz edx, ecx ; edx = ((ecx == 0) ? 0 : ecx\n test edx, edx ; read succeeded and not at EOF?\n jnz readFileBody ; if so, keep reading\n readFileFooter:\n</code></pre>\n\n<p>…wait—is that even right? Stop and write a spec:</p>\n\n<ul>\n<li>If read operation failed (<code>ReadFile</code> returns 0 in <code>EAX</code>), stop and fall through to close the handle.</li>\n<li>If there are no more bytes to read (we've reached the EOF, indicated by the byte count in <code>ECX</code> being 0), stop and fall through to close the handle.</li>\n<li>Otherwise, keep looping and reading bytes from the file body.</li>\n</ul>\n\n<p>In C:</p>\n\n<pre><code>if ((eax == 0) || (ecx == 0)) { break; }\nelse { continue; }\n</code></pre>\n\n<p>Right? Well, let me first take my own advice and write it as a series of branches:</p>\n\n<pre><code> call ReadFile\n mov rcx, var6 ; rcx <= count of bytes read\n test eax, eax ; read failed?\n jz readFileFooter ; if so, abort\n test ecx, ecx ; reached EOF?\n jnz readFileBody ; if not, keep reading\nreadFileFooter:\n</code></pre>\n\n<p>That's extremely simple and easy to understand. It's also going to be quite efficient, because branch prediction is going to be on your side.</p>\n\n<p>If you insisted upon writing it branchlessly, the first draft would be something like:</p>\n\n<pre><code> call ReadFile\n mov rcx, var6 ; rcx <= count of bytes read\n test eax, eax ; \\ dl = 1 if read failed;\n setz dl ; / dl = 0 if read succeeded\n test ecx, ecx ; \\ dh = 1 if reached EOF;\n setz dh ; / dh = 0 if not at EOF\n or dl, dh ; \\ if read succeeded and not at EOF,\n jnz readFileBody ; / keep reading; otherwise, bail\nreadFileFooter:\n</code></pre>\n\n<p>That is similar to your <code>CMOVcc</code> code, except that it uses <code>TESTcc</code> instead. It elides one instruction, but does risk a performance decrease on some microarchitectures where <a href=\"https://stackoverflow.com/questions/45660139/how-exactly-do-partial-registers-on-haswell-skylake-perform-writing-al-seems-to\">partial registers are not renamed separately</a> (because we're using <code>DL</code> and <code>DH</code>, the two byte-accessible portions of the <code>EDX</code> register). We could solve this problem by rewriting as:</p>\n\n<pre><code> call ReadFile\n mov rcx, var6 ; rcx <= count of bytes read\n test eax, eax ; \\ dl = 1 if read failed;\n setz dl ; / dl = 0 if read succeeded\n test ecx, ecx ; \\ al = 1 if reached EOF;\n setz al ; / al = 0 if not at EOF\n or al, dl ; \\ if read succeeded and not at EOF,\n jnz readFileBody ; / keep reading; otherwise, bail\nreadFileFooter:\n</code></pre>\n\n<p>This clobbers <code>EAX</code> (or, at least, the low 8 bytes of it), but we don't care at this point, because we've already gotten the information we need from the <code>ReadFile</code> function's return value. It still isn't extremely performant code, though. The <code>SETcc</code> instructions have a relatively high latency, and there is a long dependency chain in these instructions. Your original <code>CMOVcc</code> version isn't much better on either of those fronts. I personally find the <code>SETcc</code> version more idiomatic and therefore more readable, but not strongly so; choose whichever you like better.</p>\n\n<p>Your revised <code>CMOVcc</code> version is better. Or, at least, it is <em>shorter</em>. Whether it's actually better is a matter for a profiler to decide. Shorter code is not necessarily \"better\" or faster.</p>\n\n<pre><code> call ReadFile\n mov ecx, -1 ; NOTE: prefer to write constant as -1, not 0FFFFFFFFh\n test eax, eax\n cmovz ecx, eax\n and rcx, var6\n jnz readFileBody\nreadFileFooter:\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T13:35:48.477",
"Id": "415900",
"Score": "0",
"body": "Dumb question but how does one include `__chkstk`? I'm using VS2017 (MASM) and Google Fu has failed me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T19:51:58.000",
"Id": "415931",
"Score": "1",
"body": "@Kittoes Not a dumb question. It isn't really designed to be called from your own code. It's an internal helper function used by Microsoft's compiler. You can find the implementation at \"C:\\Program Files (x86)\\Microsoft Visual Studio <version>\\VC\\crt\\src\\intel\\chkstk.asm\". You can probably figure out a way to import it so it's callable from MASM with a declaration like `EXTRN __chkstk:NEAR`, but I've never done it before. See [the documentation](https://docs.microsoft.com/en-us/cpp/build/prolog-and-epilog?view=vs-2017) for a more detailed discussion of how it works, if you want to reimplement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T08:43:11.340",
"Id": "215079",
"ParentId": "214673",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215079",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-03T23:04:27.123",
"Id": "214673",
"Score": "3",
"Tags": [
"performance",
"file",
"windows",
"assembly",
"x86"
],
"Title": "Reading all file contents via x64 assembly"
} | 214673 |
<p>The following code gets 100% on the <a href="https://app.codility.com/programmers/lessons/4-counting_elements/perm_check/" rel="nofollow noreferrer">PermCheck task on Codility</a>. It should be O(N). </p>
<p>The question is:</p>
<blockquote>
<p>A non-empty array A consisting of N integers is given.</p>
<p>A permutation is a sequence containing each element from 1 to N once,
and only once.</p>
<p>For example, array A such that:</p>
<pre><code>A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
</code></pre>
<p>is a permutation, but array A such that:</p>
<pre><code>A[0] = 4
A[1] = 1
A[2] = 3
</code></pre>
<p>is not a permutation, because value 2 is missing.</p>
<p>The goal is to check whether array A is a permutation.</p>
<p>Write a function:</p>
<pre><code>function solution(A);
</code></pre>
<p>that, given an array A, returns 1 if array A is a permutation and 0 if
it is not.</p>
<p>For example, given array A such that:</p>
<pre><code>A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
</code></pre>
<p>the function should return 1.</p>
<p>Given array A such that:</p>
<pre><code>A[0] = 4
A[1] = 1
A[2] = 3
</code></pre>
<p>the function should return 0.</p>
<p>Write an efficient algorithm for the following assumptions:</p>
<ul>
<li>N is an integer within the range [1..100,000];</li>
<li>each element of array A is an integer within the range [1..1,000,000,000].</li>
</ul>
</blockquote>
<p>Let me know if you think it can be improved, but I think it is pretty good. ;)</p>
<pre><code>function solution(A) {
let m = A.length;
let sumA = A.reduce((partial_sum, a) => partial_sum + a);
let B = Array.apply(null, Array(m)).map(function () {});
var sum_indices = 0;
for (var i = 0; i < m; i++) {
B[A[i] - 1] = true;
sum_indices += i + 1;
}
if (sum_indices == sumA && B.indexOf(undefined) == -1) {
return 1;
} else {
return 0;
}
}
</code></pre>
| [] | [
{
"body": "<p>Summing the arrays is not necessary. You only need to check that the input's maximum and length are equal, and that it's free of duplicates.</p>\n\n<p>This approach scores 100% as well. It saves a couple of array traversals and exits earlier when a duplicate exists.</p>\n\n<pre><code>function solution(A) {\n var max = 0,\n seen = Array( A.length );\n for (var i of A) {\n if (i>max) max=i;\n if (seen[i]) return 0;\n seen[i]=true;\n }\n return +(max == A.length);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T03:27:21.427",
"Id": "415251",
"Score": "1",
"body": "Good solution though I would consider a map or set instead of array for your seen variable, as intent would probably be a little clearer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T16:10:03.907",
"Id": "415344",
"Score": "0",
"body": "@MikeBrant I tried it before posting, but arrays of integers (or booleans) are very hard to beat, performance-wise. Using a set was about 4x slower. That said, it *does* make the code tidier. See Blindman67's solution for a good example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T11:03:30.067",
"Id": "214695",
"ParentId": "214679",
"Score": "7"
}
},
{
"body": "<p>You can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\"><code>Set</code></a> to reduce the mean complexity.</p>\n\n<p>There are also several opportunities to exit the function early. </p>\n\n<ul>\n<li>When a duplicate is found</li>\n<li>When a value is found greater than the array length</li>\n</ul>\n\n<p>Thus we get...</p>\n\n<pre><code>function solution(A) {\n const found = new Set();\n for (const num of A) {\n if (found.has(num) || num > A.length) { return 0 }\n found.add(num);\n }\n return 1;\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T13:02:51.040",
"Id": "415303",
"Score": "1",
"body": "I think your final conditional is not even needed and you can just `return 1` after the loop exits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T14:40:52.603",
"Id": "415321",
"Score": "0",
"body": "@OhMyGoodness Yes. good point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T00:11:14.870",
"Id": "415849",
"Score": "0",
"body": "`if (len > 1e5) { return 0 }` is redundant, given the assumptions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T01:55:08.837",
"Id": "415856",
"Score": "0",
"body": "@AndréWerlang Ah yes I see N is the max array length, not the max valid sequence size. No point holding length in `len` so almost nothing left of the function."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T03:24:18.787",
"Id": "214744",
"ParentId": "214679",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "214695",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T06:05:22.103",
"Id": "214679",
"Score": "4",
"Tags": [
"javascript",
"programming-challenge",
"combinatorics"
],
"Title": "PermCheck Codility"
} | 214679 |
<p>This code is to solve the Hacker Rank problem <a href="https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays" rel="noreferrer">array left rotation</a>.</p>
<p>A left rotation operation on an array of size <em>n</em> shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].</p>
<p>Given an array of <em>n</em> integers and a number, <em>d</em>, perform <em>d</em> left rotations on the array. Then print the updated array as a single line of space-separated integers.</p>
<pre><code>public static int[] rotLeft(int[] a, int d)
{
for (int intI = 0; intI < d; intI++)
{
int temp = 0;
temp = a[0];
for (int intK = 0; intK < a.Length; intK++)
{
a[a.Length - (a.Length - intK)] = a.Length - 1 == intK ? temp : a[a.Length - (a.Length - (intK + 1))];
}
}
return a;
}
static void Main(string[] args)
{
string[] nd = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(nd[0]);
int d = Convert.ToInt32(nd[1]);
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));
int[] result = rotLeft(a, d);
Console.WriteLine(string.Join(" ", result));
}
</code></pre>
<p>This program works fine, but it takes too long with some examples. How can I improve it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T12:45:46.103",
"Id": "415177",
"Score": "6",
"body": "The best code is no code at all. Do you actually need to rotate the array, or just print the elements in rotated order? Because if that’s the case then you can save a whole lot of copying around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T13:26:49.100",
"Id": "415185",
"Score": "0",
"body": "From O(n^2) to O(n): `int n = d % a.Length; var b = a.Skip(n).Concat(a.Take(n)).ToArray();`. You can always get rid of the lazy enumerable when its too slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T14:32:56.383",
"Id": "415191",
"Score": "8",
"body": "@Caramiriel, you've got the wrong box. The one for answers is further down the page."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T16:00:37.510",
"Id": "415203",
"Score": "1",
"body": "@Caramiriel this isn't `O(n)` because `Skip` is not _clever_... as far as I know it iterates the collection to skip the items."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T18:09:53.703",
"Id": "415207",
"Score": "4",
"body": "@t3chb0t Even if it goes through the array twice, `2n`, or `200n` for that matter, is still `O(n)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T19:17:05.750",
"Id": "415211",
"Score": "0",
"body": "@t3chb0t Skip is O(k) where k is the size of elements you've told it to skip. That's the best you can do for an arbitrary IEnumerable. And as TemporalWolf said it isn't quadratic by any variable you look at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T07:54:33.683",
"Id": "415266",
"Score": "0",
"body": "@TemporalWolf this is a pretty interesting logic: `2n == n` could explain how this works?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T11:54:37.340",
"Id": "415295",
"Score": "0",
"body": "@t3chb0t How can user with 30k rep on code review not know about big O notation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T12:22:10.457",
"Id": "415297",
"Score": "0",
"body": "@ghord it's not about not knowing but about not agreeing with the cannonical and often unprecise form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T19:13:52.363",
"Id": "415379",
"Score": "1",
"body": "@t3chb0t See the canonical answer on [What is BigO?](https://stackoverflow.com/a/487278/3579910) When n is 10, 2n is 20 and n^2 is 100... and it only gets worse the larger n gets. That's why. If n is 2 million, then 200n is 400 million and n^2 is 4 trillion... still ten thousand times larger: what the 200n version can do in 1 minute, it will take almost a week (6.94 days) to run at n^2... and that's before you run into memory issues. That's why BigO works the way it does."
}
] | [
{
"body": "<p>About naming:</p>\n\n<p><code>intI</code> and <code>intK</code>: don't include the type in the variable name, it is obvious from the context and intellisense and as a loop index a plain <code>i</code> and <code>k</code> are more understandable.</p>\n\n<hr>\n\n<p>A first simple optimization is that you can avoid the check if <code>intK</code> has reached the end: </p>\n\n<blockquote>\n <p><code>a.Length - 1 == intK ?</code></p>\n</blockquote>\n\n<p>Instead you can just iterate up to <code>a.Length - 1</code> and then append <code>temp</code> at the end:</p>\n\n<pre><code>public static int[] rotLeft(int[] a, int d)\n{\n for (int intI = 0; intI < d; intI++)\n {\n int temp = a[0];\n\n for (int intK = 0; intK < a.Length - 1; intK++)\n {\n a[a.Length - (a.Length - intK)] = a[a.Length - (a.Length - (intK + 1))];\n }\n\n a[a.Length - 1] = temp;\n }\n\n return a;\n}\n</code></pre>\n\n<hr>\n\n<p>Next step is to consider the math:</p>\n\n<pre><code>a.Length - (a.Length - intK) = a.Length - a.Length + intK = intK\n</code></pre>\n\n<p>and in the same way:</p>\n\n<pre><code>a.Length - (a.Length - (intK + 1)) = intK + 1\n</code></pre>\n\n<p>So you could write:</p>\n\n<pre><code>public static int[] rotLeft(int[] a, int d)\n{\n for (int intI = 0; intI < d; intI++)\n {\n int temp = a[0];\n\n for (int intK = 0; intK < a.Length - 1; intK++)\n {\n a[intK] = a[intK + 1];\n }\n\n a[a.Length - 1] = temp;\n }\n\n return a;\n}\n</code></pre>\n\n<hr>\n\n<p>But the real performance problem is that you move each entry in the array <code>d</code> number of times. You can move each entry just once by moving it d places. A simple way to do that could be:</p>\n\n<pre><code>public static int[] rotLeft(int[] a, int d)\n{\n int[] temp = new int[d];\n\n for (int i = 0; i < d; i++)\n temp[i] = a[i];\n\n for (int i = d; i < a.Length; i++)\n {\n a[i - d] = a[i];\n }\n\n for (int i = 0; i < d; i++)\n a[a.Length - d + i] = temp[i];\n\n return a;\n}\n</code></pre>\n\n<hr>\n\n<p>Another issue is that you operate on the input array <code>a</code> directly and return it as a return value. In this way both the return value and <code>a</code> contains the shifted values. In a challenge like this it may not be important, but I think I would return a new array with the shifted data leaving <code>a</code> unchanged - in \"real world\":</p>\n\n<pre><code>public static int[] rotLeft(int[] a, int d)\n{\n int[] result = new int[a.Length];\n\n for (int i = d; i < a.Length; i++)\n {\n result[i - d] = a[i];\n }\n\n for (int j = 0; j < d; j++)\n {\n result[a.Length - d + j] = a[j];\n }\n\n return result;\n}\n</code></pre>\n\n<p>If you want to operate on <code>a</code> directly intentionally it would be more consistent returning <code>void</code> to signal that you're operating on the input directly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-12T17:55:18.123",
"Id": "457411",
"Score": "0",
"body": "Great answer. However, if the number of rotations `d` is as large or greater than the size of array, you'll get out of bounds errors. A quick check at the top could be: `if (d >= a.Length) d = d % a.Length;`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T08:03:50.097",
"Id": "214682",
"ParentId": "214680",
"Score": "18"
}
},
{
"body": "<blockquote>\n<pre><code> static void Main(string[] args)\n {\n string[] nd = Console.ReadLine().Split(' ');\n int n = Convert.ToInt32(nd[0]);\n int d = Convert.ToInt32(nd[1]);\n int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp));\n</code></pre>\n</blockquote>\n\n<p>Don't Repeat Yourself. There's an easy opportunity here to factor out a method which reads an array of integers from stdin.</p>\n\n<p>In general I would prefer to remove the explicit lambda, but I think that in this case just passing <code>Convert.ToInt32</code> would be ambiguous because of the overloads.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> int[] result = rotLeft(a, d);\n Console.WriteLine(string.Join(\" \", result));\n }\n</code></pre>\n</blockquote>\n\n<p>When implementing a spec, ask yourself what the inputs and the outputs are. As long as you respect those, you should be at liberty to optimise the processing. So it's not actually necessary to rotate the array: just to print the result of rotating it.</p>\n\n<pre><code> Console.Write(a[d]);\n for (int i = d+1; i < a.Length; i++)\n {\n Console.Write(' ');\n Console.Write(a[i]);\n }\n for (int i = 0; i < d; i++)\n {\n Console.Write(' ');\n Console.Write(a[i]);\n }\n</code></pre>\n\n<hr>\n\n<p>But I think that that code probably has a bug. Does the spec make any guarantees about the value of <code>d</code> other than that it's an integer? Can it be negative? Can it be greater than <code>n</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T11:50:12.637",
"Id": "415171",
"Score": "0",
"body": "Most of the I/O code is provided as part of the challenge. The only thing OP has to provide is the code inside the rotLeft function, which should return the rotated array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T13:01:30.630",
"Id": "415180",
"Score": "0",
"body": "@jcaron, it's OP's responsibility to ask only about their own code. The help centre is quite explicit that [any aspect of the code posted is fair game for feedback and criticism](//codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:12:24.157",
"Id": "415269",
"Score": "0",
"body": "The constraints say that `1 <= d <= n`, so yes, we have guarantees about `d`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:30:02.497",
"Id": "415273",
"Score": "1",
"body": "@Astrinus, if I wanted answers to those questions I'd have posted them as comments on the question. As I see it, one of the things a code review should do is challenge OP to think about whether they've fully understood the spec, and whether they can update the code if the spec (or their understanding of it) changes."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T08:43:29.057",
"Id": "214684",
"ParentId": "214680",
"Score": "9"
}
},
{
"body": "<p>I guess your code is slow because of the two loops and its <em>O(n^2)</em> complexity. You can actually solve it with only one loop by <em>rotating</em> the index with <code>%</code> (modulo). This would even allow you to <em>rotate</em> the array in both directions;</p>\n\n<pre><code>public static IEnumerable<T> Shift<T>(this T[] source, int count)\n{\n for (int i = 0; i < source.Length; i++)\n {\n var j =\n count > 0\n ? (i + count) % source.Length\n : (i + count + source.Length) % source.Length;\n yield return source[j];\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T10:00:24.537",
"Id": "415152",
"Score": "11",
"body": "In fact, a general tip for programming challenges like this is that, whenever the challenge says \"repeat this operation _N_ times,\" it _almost always_ actually means \"find a faster way to get the same result as if you'd repeated the operation _N_ times.\" That's because the challenges are meant to be challenging, and just writing a `for` loop to run the same code multiple times is really no challenge at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T10:02:08.477",
"Id": "415153",
"Score": "0",
"body": "`%` is typically slow; and `i+count` can't wrap more than once. So really you just need a conditional subtract. If you're actually copying the array, hopefully the compiler can split it into two loops that simply copy the 1st / 2nd parts of the array without doing a bunch of expensive per-index calculation, like Henrik's answer. Also hopefully the compiler will hoist the `count>0` check out of the loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T10:41:14.900",
"Id": "415160",
"Score": "8",
"body": "@PeterCordes - I think `%` is clearer and never so slow as to justify such an optimization without profiling first. I would be very surprised if it were the bottleneck in application software, rather than, say, disk IO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T22:05:17.440",
"Id": "415231",
"Score": "0",
"body": "In C, a simplistic microbenchmark doing *just* a modulo increment shows that it's about 6x slower on a Haswell CPU. [is it better to avoid using the mod operator when possible?](//stackoverflow.com/a/35114401). Most things aren't a big deal, but integer division is *slow* unless it's by a compile-time constant that the compiler can turn into a multiply+shift. The OP already said that their solution for rotating an array was too slow rotating 1 element at a time, so presumably a factor of 6 (or more if the compiler can turn it into 2x memcpy) could matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T22:14:10.497",
"Id": "415232",
"Score": "3",
"body": "You can hoist the `count > 0` check out of the loop by calculating the left-rotate count once. `if(count < 0) count += source.Length;` Then the loop becomes much more readable, and probably more efficient unless the compiler already managed to do that for you."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T08:44:11.563",
"Id": "214685",
"ParentId": "214680",
"Score": "17"
}
},
{
"body": "<p>Because of the 2 imbricated <code>for</code> loops here:</p>\n\n<blockquote>\n<pre><code> for (int intI = 0; intI < d; intI++) { \n for (int intK = 0; intK < a.Length; intK++) {\n ...\n }\n }\n</code></pre>\n</blockquote>\n\n<p>your code performs <code>d * a.Length</code> actions - which takes quadratic time when <code>d</code> is near <code>a.Length/2</code>. </p>\n\n<p>So, we may ask, <strong>can we do better</strong> ?</p>\n\n<p>The answer is yes. There is a linear-time solution. It is as follows:</p>\n\n<ol>\n<li>\"mirror\" the first <code>d</code> elements</li>\n<li>mirror the whole array</li>\n<li>mirror the <code>size-d</code> first elements.</li>\n</ol>\n\n<p>Implementation of <code>mirror</code> (reverse an array) is left to the reader.</p>\n\n<p>Linear time complexity. 0(1) extra room needed (loop variable and temporary for exchange).</p>\n\n<p>So it is clearly an <strong>improvement</strong> on the original version.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T09:05:57.510",
"Id": "214686",
"ParentId": "214680",
"Score": "3"
}
},
{
"body": "<p>You are focusing on the wrong portion of the problem. You're thinking the array needs to be rotated. The output of the array needs to be \"rotated\" but the array can remain as-is.</p>\n\n<p>So simply write a loop that starts at the middle of the array, incrementing until it hits the end, and then continues along from the beginning until it hits the index just before the one you started at.</p>\n\n<p>The output of that loop is the \"rotated\" array, from the visibility of the testing framework.</p>\n\n<pre><code> string sep = \"\";\n for (int i = d % a.Length; i < a.Length; i++) {\n Console.Write(sep);\n Console.Write(a[i]);\n sep = \" \";\n }\n for (int i = 0; i < d % a.Length; i++)\n {\n Console.Write(sep);\n Console.Write(a[i]);\n sep = \" \";\n }\n</code></pre>\n\n<p>This is a great reason why you should sometimes see <code>hackerrank</code> as a poor place to really learn programming. </p>\n\n<p><code>hackerrank</code> primarily contains programming problems harvested from programming competitions. Competitions where these problems are meant to be solved fast, with a time deadline. This means that the problems are more about building a quick, clever, solution and less about really learning the lessons that would help you in a programming career.</p>\n\n<p>Another example of a solution is</p>\n\n<pre><code> string sep = \"\";\n for (int i = d; a.Length + d - i > 0; i++) {\n Console.Write(sep);\n Console.Write(a[i % a.Length]);\n sep = \" \";\n }\n</code></pre>\n\n<p>Which is, according to <code>hackerrank</code>s estimation, \"just as good\" as the above solution, but is far less readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T19:21:17.440",
"Id": "415212",
"Score": "1",
"body": "Well one thing one should certainly learn from this challenge is what `string.Join` does and how it avoids the rather awful for loop :) (The given solution also misses some necessary modulo ops)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T20:20:04.137",
"Id": "415217",
"Score": "0",
"body": "@Voo Out of curiosity, which modulo does this miss? I know I wrote it by hand without the aid of a computer, but the loop (in my 5 element example, starting at index 3 would be 3, 4, 5, 6, 7 (8 would be 5 + 3 - 8, so it wouldn't get there). and 3 % 5 = 3, 4 % 5 = 4, 5 % 5 = 0, 6 % 5 = 1, 7 % 5 = 2. Now, I just might have a bug in there after all; but, maybe not, which is __a perfect example of why writing it this way is less than ideal__ and why `hackerrank`s fascination with programming competitions as question banks is bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T21:14:00.197",
"Id": "415226",
"Score": "2",
"body": "You're supposed to do n rotations. Nowhere does it say that n < arr.Length. You could have an array of `1,2,3` and d=5. Both of your solutions fail with an out of bounds there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:15:34.943",
"Id": "415272",
"Score": "1",
"body": "@Voo: if you read the challenge, you see that `1 <= d <= n`, i.e. rotate an `n` elements array by `d` steps, so you cannot have more rotations than elements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T17:10:45.433",
"Id": "415357",
"Score": "0",
"body": "@Voo I think you keep focusing on how (in my latter example) `i` is often out-of-range of the array. That's probably why you keep saying \"out of bounds\" which would cause an error if I was pulling out the `i` element of the array. But I'm not pulling `i` out of the array, I'm pulling `i % a.Length` which can't be out of bounds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T17:15:14.483",
"Id": "415358",
"Score": "0",
"body": "@Edwin Yeah I missed the modulo on your second loop on my phone. Not entirely sure if it works correctly - I doubt it, but updating loop end conditions in every iteration makes it rather hard to reason about loops in your head. Your first version definitely crashes out of bounds on the second loop as soon as `iterations > i >= arr.len`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T19:17:59.997",
"Id": "415380",
"Score": "0",
"body": "@Voo Now that you see your comments are misleading, please consider removing them so others are not misled. Yes, you can do N rotations with the above code. That's because on a 5 element array, a rotation of 10 and a second rotation of 3 combine as a rotation of 13 (which mod 5 equals 3). The code above doesn't care if you rotate beyond the end of the array (in combined rotations or single ones) as long as the sum of your combined rotations and the array size doesn't exceed `MAX_INT`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T19:28:34.340",
"Id": "415381",
"Score": "0",
"body": "@Edwin I literally posted the exact set of numbers for which your first method will throw an exception and I already agreed that the second one doesn't, shouldn't be too confusing for people."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T19:32:33.123",
"Id": "415382",
"Score": "0",
"body": "@Voo Ah, I see, I didn't add the mod to the first set of examples. I've been here thinking that the \"condensed\" second program was the one you were noting through an out-of-bounds, when all along it was the first (which works, but only for a more limited set of inputs). I know these comments are awfully short, so a short call-out to the failing text isn't always possible. I'm updating it now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T19:36:04.523",
"Id": "415383",
"Score": "0",
"body": "@Edwin Ah yes that makes sense, \"*First* versions *second* loop\" is easy to miss in short comments. The second one seems fine (I did write some tests to assure myself ;) ), except for the wraparound behavior you noted (which could be easily fixed by using a long, but then the chances of this ever being observed are slim to none)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-10T07:28:45.820",
"Id": "471202",
"Score": "0",
"body": "@Edwin \"perform d left rotations on the array. Then print the updated array\". So updating the array is **required**."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T19:19:39.017",
"Id": "214720",
"ParentId": "214680",
"Score": "4"
}
},
{
"body": "<p>If r = number of rotations, a = int[] array, n = a.length, to rotate the array you need to</p>\n\n<ol>\n<li>move a[r to n] to the beginning of the array</li>\n<li>move a[0 to r] to end of array</li>\n</ol>\n\n<p>Also r can be reduced to r % n, as for every n rotations, the array repeats.</p>\n\n<p>Code:</p>\n\n<pre><code> int[] result = new int[];\n r = r % n;\n int count = 0;\n\n for(int i=r;i<n;i++){\n result[count++] = a[i];\n }\n\n for(int i=0;i<r;i++){\n result[count++] = a[i];\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-13T07:50:04.080",
"Id": "238813",
"ParentId": "214680",
"Score": "2"
}
},
{
"body": "<p>Another solution, with proper justification I hope.</p>\n\n<p>First, we will consider rotating to the <em>right</em>. Not a big deal, because shifting an array (of size <em>n</em>) by <em>d</em> position to the left is the same as shifting it <em>n-d</em> positions to the right. And conversely.</p>\n\n<p>It will just make the explanations easier.</p>\n\n<h1>Example : shift an array <em>a</em> of size 21, 6 positions to the right.</h1>\n\n<h2>Poor <em>a[0]</em>, what shall we do with you?</h2>\n\n<p>Consider <em>a[0]</em>. It it suppose to move to <em>a[6]</em>. Which moves to <em>a[12]</em>. Pushed into <em>a[18]</em>. Going to <em>a[3]</em> (because 18 + 6 = 24 = 21 + 3), etc.</p>\n\n<p>So we follow a path which goes back to the initial position. It is the cycle (0, 6, 12, 18, 3, 9, 15, 0, 6, ....).</p>\n\n<h2>Code for shifting <em>a[0]</em> and friends</h2>\n\n<p>Here is the code (C-ish)</p>\n\n<pre><code>int next = 0;\nint saved = a[0];\ndo {\n next = (next + d) % n;\n swap (saved, a[next]);\n} while (next != 0);\n</code></pre>\n\n<h1>Here comes the GCD</h1>\n\n<p>But there are other cycles. Actually this is linked to the greatest common divisor.\nThere are exactly <em>gcd(d, n)</em> such cycles. And 0,1,...gcd(d,n-1) belong to different cycles.</p>\n\n<p>So they are convenient starting points.</p>\n\n<h1>Final code</h1>\n\n<pre><code>int nb_cycles = gcd(d, n);\n\nfor (int start = 0; start < nb_cycles; start++) {\n int next = start;\n int saved = a[start];\n do {\n next = (next + d) % n;\n swap (saved, a[next]);\n } while (next != start);\n}\n</code></pre>\n\n<h1>Complexity</h1>\n\n<ul>\n<li>Linear time, as each element of the array is assigned exactly once.</li>\n<li>In-place, non recursive</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-10T07:56:53.133",
"Id": "240259",
"ParentId": "214680",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "214682",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T06:11:42.423",
"Id": "214680",
"Score": "17",
"Tags": [
"c#",
"algorithm",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Hacker Rank: Array left rotation"
} | 214680 |
<p>I wrote code to (naively) perform lru memoisation. I tried to write it in a functional programming style, and so did not make use of any global variables.</p>
<h2>My Code</h2>
<pre class="lang-py prettyprint-override"><code>from collections import deque, defaultdict as dd
def naive_lru(mx=None):
"""
* Closure that returns a memoiser.
* Params:
* `mx`: (`int`) The maximum size of the cache of the returned memoiser.
* Return:
* `memoise`: (`function`) A memoiser.
* Vars:
* `caches`: (`defaultdict`) stores the caches for the various functions.
* `lim`: (`bool`) set to `True` if `mx` isn't `None`. It is used to indicate that the size of the cache should be tracked.
* `ln`: (`int`) that tracks the cache size.
* `deck`: (`deque`) used for administrating the cache. Elements in the deque are ordered according to when they were last accessed.
* `lengths`: (`defaultdict`) stores the lengths of the caches for the various functions.
* `lims`: (`defaultdict`) stores whether a given cache has a maximum size.
* `decks`: (`defaultdict`) stores the deques of the caches for the various functions.
* `maxes`: (`defaultdict`) stores the maximum size of the caches for the various functions.
"""
caches, lim = dd(lambda: dd(lambda: None)), False
if mx is not None:
lim, ln = True, 0
deck = deque()
lengths, lims, decks, maxes = dd(lambda: 0), dd(lambda: False), dd(lambda: deque()), dd(lambda: None)
def memoise(mxsize=None, lst=False, idx=None, init=0):
"""
* Returns a memoisation decorator for a given function.
* Params:
* `mxsize` (`int`): The maximum size of the cache for the memoised variant of the input function.
* `lst` (`list`): A boolean variable that determines whether a list would be used for the function cache. For functions with domains that can be mapped onto a dense set, using a list for caching would be more efficient (and faster) than using a dict.
* The cache would only be set to a list if `mxsize` is `None` as implementing lru functionality with a list is quite nontrivial — and more importantly very messy — frequent deletions would destroy the dense property that was a prerequisite for using the list as a cache, so lru functionality is only provided when the cache is a dict.
* `idx` (`function`): The transformation function that maps input data unto their corresponding index in the cache.
* `init` (`int`): The initial size of the cache list. If an upper bound on the size of the function's domain is known, a list of that size can be created at initialisation. This is more efficient than repeatedly appending to or extending the list.
* Return:
* `memoised`: (`function`) A memoisation decorator.
"""
def memoised(f):
"""
* Memoisation function that returns a memoised variant of a given input function.
* Params:
* `f`: (`function`) The function to be memoised.
* Return:
* `mem_f`: (`function`) Memoised variant of the input function.
"""
nonlocal lst
if lim:
deck.appendleft(f)
ln += 1
if ln > mx:
del caches[deck.pop()] #Remove the least recently used function cache.
if mxsize is not None:
lims[f], lst, maxes[f] = True, False, mxsize
else:
if lst:
caches[f] = [None]*init
def mem_f(*args, **kwargs):
tpl = (args, frozenset(kwargs))
index = tpl if idx is None else idx(tpl)
if caches[f][index] is None:
caches[f][index] = f(*args, **kwargs)
if lims[f]:
decks[f].appendleft(index)
lengths[f] += 1
if lengths[f] > maxes[f]:
del caches[f][decks[f].pop()] #Remove the least recently used argument cache.
return caches[f][index]
return mem_f
return memoised
return memoise
</code></pre>
<h3>Sample Usage</h3>
<pre class="lang-py prettyprint-override"><code>mem = naive_lru()
@mem(lst=True, init=10000, idx=lambda x: x[0][0])
def fib(n):
if n in [0, 1]:
return n
return fib(n - 2) + fib(n - 1)
print(fib(500)) #Outputs "139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125".
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T10:01:01.990",
"Id": "214690",
"Score": "3",
"Tags": [
"python",
"beginner",
"functional-programming",
"reinventing-the-wheel",
"memoization"
],
"Title": "Naive Implementation of A Least Recently Used (LRU) Cache Memoiser"
} | 214690 |
<p>I have an agreement with a customer. When the agreement ends, the customer needs to pay. The amount which the customer needs to pay increases for each month that has passed since the agreement was initiated. The maximum duration is 3 years, so I have a final expiration date. From this final expiration date, I must be able to find the periodic expiration date (the date when the payment increases). In other words, I need a function which does this:</p>
<pre><code>DateTime GetNextExpirationDate(finalExpirationDate)
</code></pre>
<p>One of the issues which I am struggling with is that the algorithm needs to consider whether the expiration date in the current month has already passed (there will be a date each month). It also needs to consider that the day of the month for the final expiration date, might not exist for the periodic expiration dates (e.g. if the final expiration date is the 31st of something). </p>
<p>I have some code which is working, but it appears somewhat redundant and with many steps. I was wondering, if perhaps it could be simplified (either a little or a lot).</p>
<pre><code>public DateTime GetNextExpirationDate(DateTime finalExpirationDate)
{
int expirationDay = finalExpirationDate.Day;
int currentMonth = DateTime.Now.Month;
int currentYear = DateTime.Now.Year;
int daysInCurrentMonth = DateTime.DaysInMonth(currentYear, currentMonth);
// If the month has less days that the day of the final expiration date,
// then we need to use the maximum date of the month.
int expirationDayThisMonth = Math.Min(expirationDay, daysInCurrentMonth);
DateTime expirationDateThisMonth = new DateTime(currentYear, currentMonth, expirationDayThisMonth);
// If the periodic expiration date in the current month is already surpassed,
// then we need to the date in the next month.
if (expirationDateThisMonth < DateTime.Now)
{
DateTime dateInOneMonth = DateTime.Now.AddMonths(1);
int nextMonthMonth = dateInOneMonth.Month;
int nextMonthYear = dateInOneMonth.Year;
int daysInNextMonth = DateTime.DaysInMonth(nextMonthYear, nextMonthMonth);
int expirationDayNextMonth = Math.Min(expirationDay, daysInNextMonth);
DateTime expirationDateNextMonth = new DateTime(nextMonthYear, nextMonthMonth, expirationDayNextMonth);
return expirationDateNextMonth;
}
else
{
return expirationDateThisMonth;
}
}
</code></pre>
<p>Any ways to improve this?</p>
<p><strong>Input/output examples:</strong></p>
<pre><code>Final expiration date: 15.12.2019
DateTime.Now: 12.03.2019
Output: 15.03.2019
Final expiration date 11.10.2019
DateTime.Now: 16.04.2019
Output: 11.05.2019
</code></pre>
<p>(I know that I cannot change <code>DateTime.Now</code> but it does work as an pseudo-input, which is why I included it). </p>
| [] | [
{
"body": "<p>When working with <code>DateTime</code> it's usually a good idea to not use a hardcoded <code>DateTime.Now</code>. This makes testing such methods very difficult because you cannot mock it so you have to write very tricky tests all with <code>Now</code>. You allso cannot easily switch to <code>UtcNow</code> etc. and you have to know which <em>now</em> it uses internally.</p>\n\n<p>A much better solution would be to use another parameter like <code>DateTime referenceDate</code>. This way you can use any combinations of the two values and create more predictable and easier to understand tests.</p>\n\n<p>Additionally I'd make this method static because it does not access any class fields etc.</p>\n\n<hr>\n\n<p>Oh, I also need to add that you use excelent variable names! This is exactly how it should be done! ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T12:53:38.647",
"Id": "415179",
"Score": "0",
"body": "Very good points. Especially the `DateTime.Now` one, since my primary personal goal is to get better at writing testable code :-). Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T12:50:56.340",
"Id": "214706",
"ParentId": "214700",
"Score": "10"
}
},
{
"body": "<p>I would try to clean it up by extracting the tricky and repetitive day truncation logic into a reusable function. This would result in something like:</p>\n\n<pre><code> /* Creates a DateTime instance for the given year, month and day. \n * It will truncate the possiblyTruncatedDay down to the largest number possible \n * for the given month in case if it's out of bounds.\n * Eg. trying to create an illegal Feb 31 instance will fallback to Feb 28 or 29) */\n private static DateTime CreateTruncating(int year, int month, int possiblyTruncatedDay)\n {\n return new DateTime(\n year,\n month,\n Math.Min(possiblyTruncatedDay, DateTime.DaysInMonth(year, month)));\n }\n\n public static DateTime GetNextExpirationDate(DateTime finalExpirationDate)\n { \n int expirationDay = finalExpirationDate.Day;\n int currentMonth = DateTime.Now.Month;\n int currentYear = DateTime.Now.Year;\n DateTime expirationDateThisMonth = CreateTruncating(currentYear, currentMonth, expirationDay);\n\n if (expirationDateThisMonth >= DateTime.Now)\n {\n return expirationDateThisMonth;\n }\n\n DateTime dateInOneMonth = DateTime.Now.AddMonths(1);\n return CreateTruncating(dateInOneMonth.Year, dateInOneMonth.Month, expirationDay);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T21:15:28.000",
"Id": "415227",
"Score": "0",
"body": "Not a bad idea. Would it make sense to nest the `CreateTruncating()` method inside `GetNextExpirationDate`, since it is exclusively used by this method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T00:17:53.077",
"Id": "415239",
"Score": "0",
"body": "A matter of taste; private methods are often only called in just one place... To me it's about whatever you find more readable"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T15:22:43.670",
"Id": "214710",
"ParentId": "214700",
"Score": "7"
}
},
{
"body": "<p>Potentially simpler version?</p>\n\n<pre><code>/// <summary>\n/// Number of calendar months between two DateTimes, rounding down partial months.\n/// Will return x such that startDate.AddMonths(x) < endDate and\n/// startDate.AddMonths(x+1) >= endDate.\n/// Ignores time components.\n/// </summary>\n/// <param name=\"startDate\">Start Date</param>\n/// <param name=\"endDate\">End Date</param>\n/// <returns>Number of Months between Start Date and End Date</returns>\npublic static int MonthsBetween(DateTime startDate, DateTime endDate)\n{\n return (endDate.Year - startDate.Year) * 12 + \n (endDate.Month - startDate.Month) + \n ((endDate.Day >= startDate.Day) ? 0 : -1); //rounding down for partial months\n}\n\n\n/// <summary>\n/// Gets the next monthly expiration date after the Reference Date\n/// with day component aligned with Final Expiration Date\n/// Ignores time components.\n/// </summary>\n/// <param name=\"finalExpirationDate\">Final Expiration Date</param>\n/// <param name=\"referenceDate\">Reference Date</param>\n/// <returns>Next monthly expiration date after Reference Date</returns>\npublic DateTime GetNextExpirationDate(DateTime finalExpirationDate, DateTime referenceDate)\n{\n return finalExpirationDate.AddMonths(-MonthsBetween(referenceDate, finalExpirationDate));\n}\n</code></pre>\n\n<p>It's unclear from your description what you want to do if today is an expiration date. The code above will generate today's date in that scenario, which is what your code does. If you want to generate next month's expiration date in that scenario, change the <code>>=</code> to a <code>></code> in <code>MonthsBetween</code> (and adjust the comments as appropriate, of course).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T11:02:28.833",
"Id": "415290",
"Score": "0",
"body": "Quite an interesting (and very different approach). I like the very math-based approach, though it might confuse some :-). You are correct, that there is an unclear scenario, if expiration is today. This is still an open issue, which is not clearly described in the specifications I got."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T20:16:24.627",
"Id": "415390",
"Score": "0",
"body": "Thanks, I'll add a little explanation which may help. I've also added another solution below, which might be easier to explain."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T21:28:34.523",
"Id": "214729",
"ParentId": "214700",
"Score": "1"
}
},
{
"body": "<p><strong>Naming</strong></p>\n\n<p><code>Expiration</code> vs <code>Final Expiration</code> seems kind of confusing, imo. Might I suggest <code>PenaltyDate</code> for when amount they owe increases, and <code>ExpirationDate</code> for that final date that they must pay.</p>\n\n<p><strong>Testability</strong></p>\n\n<p>As others have mentioned, passing in a <code>referenceDate</code> will allow you test more easily test outcomes.</p>\n\n<p><strong>Modularity</strong></p>\n\n<p>Breaking the redundant part into a separate function like others have suggested.</p>\n\n<p><strong>Bringing it all together</strong></p>\n\n<pre><code>public static DateTime GetNextPenaltyDate(DateTime expirationDate, DateTime referenceDate)\n{\n var penaltyDate = GetPenaltyDate(expirationDate, referenceDate);\n if (penaltyDate < referenceDate)\n {\n var nextPenaltyDate = GetPenaltyDate(expirationDate, referenceDate.AddMonths(1));\n return nextPenaltyDate;\n }\n else\n {\n return penaltyDate;\n }\n}\n\nprivate static DateTime GetPenaltyDate(DateTime expirationDate, DateTime referenceDate)\n{\n int daysInMonth = DateTime.DaysInMonth(referenceDate.Year, referenceDate.Month);\n int penaltyDay = Math.Min(expirationDate.Day, daysInMonth);\n return new DateTime(referenceDate.Year, referenceDate.Month, penaltyDay);\n}\n</code></pre>\n\n<p><strong>Testing Mine via Console</strong></p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Print(\n expirationDate: new DateTime(2019, 12, 15),\n referenceDate: new DateTime(2019, 03, 12)\n );\n\n Print(\n expirationDate: new DateTime(2019, 10, 11),\n referenceDate: new DateTime(2019, 04, 16)\n );\n\n Console.ReadKey();\n }\n\n private static void Print(DateTime expirationDate, DateTime referenceDate)\n {\n Console.WriteLine(\"Final Expiration Date: {0}\", expirationDate);\n Console.WriteLine(\"Reference Date: {0}\", referenceDate);\n Console.WriteLine(\"Output: {0}\", Expiration.GetNextPenaltyDate(expirationDate, referenceDate));\n }\n}\n</code></pre>\n\n<p><strong>My Results</strong></p>\n\n<p>My output is formatted differently, but if I'm not mistaken the data matches.</p>\n\n<pre><code>Final Expiration Date: 12/15/2019 12:00:00 AM \nReference Date: 3/12/2019 12:00:00 AM \nOutput: 3/15/2019 12:00:00 AM\n\nFinal Expiration Date: 10/11/2019 12:00:00 AM\nReference Date: 4/16/2019 12:00:00 AM\nOutput: 5/11/2019 12:00:00 AM\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T11:10:28.963",
"Id": "415292",
"Score": "0",
"body": "Thanks for your input. You might be on to something, regarding the naming. I will try to make it more clear, what the different expiration dates are."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T22:04:49.993",
"Id": "214732",
"ParentId": "214700",
"Score": "1"
}
},
{
"body": "<p>Another, less \"mathy\" approach - move backwards 1 month at a time from the final expiration date until we get to the reference date.</p>\n\n<pre><code>/// <summary>\n/// Gets the next monthly expiration date after the Reference Date\n/// with day component aligned with Final Expiration Date\n/// </summary>\n/// <param name=\"finalExpirationDate\">Final Expiration Date</param>\n/// <param name=\"referenceDate\">Reference Date</param>\n/// <returns>Next monthly expiration date after Reference Date</returns>\npublic DateTime GetNextExpirationDate(DateTime finalExpirationDate, DateTime referenceDate)\n{\n int i = 0;\n while(finalExpirationDate.AddMonths(-i) > referenceDate)\n {\n i++;\n }\n return finalExpirationDate.AddMonths(-i + 1);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T20:13:53.993",
"Id": "214787",
"ParentId": "214700",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T11:42:04.280",
"Id": "214700",
"Score": "7",
"Tags": [
"c#",
".net",
"datetime"
],
"Title": "Find the next monthly expiration date"
} | 214700 |
<p>I have a class Record which keeps entries of strings(implemented using vector of strings). I want to keep the data member private to the class. To get entries, I have defined a member function get_entry which accepts a reference to vector of strings to store results.</p>
<p>Below is the code.</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
class Record {
public:
void add_entry(const std::string& entry)
{
static int seq = 1;
entries.push_back(std::to_string(seq++) + " "+ entry);
}
void get_entry(std::vector<std::string>& res) const
{
for (auto &v: entries)
res.push_back(v);
}
private:
std::vector<std::string> entries;
};
int main()
{
Record name;
name.add_entry("abc");
name.add_entry("def");
std::vector<std::string> res;
name.get_entry(res);
for (auto &v : res)
std::cout << v << "\n";
return 0;
}
</code></pre>
<p>Are there other better ways to get entries from such a class? I don't want to make <code>entries</code> data member public and access it directly.</p>
| [] | [
{
"body": "<p>Just return <code>entries</code> by value. It will make a deep copy automatically:</p>\n\n<pre><code>std::vector<std::string> get_entries() const\n{\n return entries;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T12:45:49.233",
"Id": "214705",
"ParentId": "214704",
"Score": "1"
}
},
{
"body": "<p>The obvious downside of your current approach is that you do a lot potentially unnecessary copying. One common solution is to return (const) iterators to the entries, i.e.,:</p>\n\n<pre><code>class Record\n{\n public:\n // ...\n\n auto cbegin() const { return entries.cbegin(); }\n auto cend() const { return entries.cend(); }\n\n // Perhaps similar methods for getting non-const iterators ...\n};\n</code></pre>\n\n<p>This solution allows you to use e.g., standard algorithms on the entries, but you can't manipulate the underlying range from the outside (due to const-ness).</p>\n\n<p>To support your earlier use case, you can still do <code>std::vector<std::string> res(r.cbegin(), r.cend());</code> if you wish, where <code>r</code> is an object of type <code>Record</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T17:15:30.527",
"Id": "214713",
"ParentId": "214704",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214713",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T12:41:30.400",
"Id": "214704",
"Score": "2",
"Tags": [
"c++",
"object-oriented"
],
"Title": "Getting Record entries"
} | 214704 |
<p>i'm using a dataframe full of headers/field names to develop a schema and I need unique values for each header - but each header should be represented. I want to loop though the dataframe <em>list</em> of fields and the second time I come across a field name, I want to add an ever increasing number to it. The order is important.</p>
<p>e.g.</p>
<pre><code>headers['name'] =pd.DataFrame['vegetable', 'fruit', 'meat', 'dairy', 'meat', 'fruit', 'fruit']
</code></pre>
<p>I need the output to be: </p>
<pre><code>name | name+count
vegetable | vegetable
fruit | fruit
meat | meat
dairy | dairy
meat | meat1
fruit | fruit1
fruit | fruit2
</code></pre>
<pre><code>for header in headers['names']:
row = headers.loc[headers['names'] == header].index
if len(row) > 1:
for i in range(2, len(row)):
headers['name+count'][row[i]] = headers['names'][row[i]] + str(i-1)
print(headers['name+count'][row[i]])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T14:54:22.433",
"Id": "415193",
"Score": "0",
"body": "Your descriptions makes no sense to me? can you rephrase it? Also is the code working as you want, so it can be reviewed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T15:07:38.473",
"Id": "415195",
"Score": "0",
"body": "@422_unprocessable_entity My edit which has been overwritten https://codereview.stackexchange.com/revisions/214708/2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T16:20:34.460",
"Id": "415204",
"Score": "1",
"body": "That looks like unlucky timing, since the timestamps are so close to each other. As OP you should be able to rollback to your revision 2 using the [revisions page for this post](https://codereview.stackexchange.com/posts/214708/revisions). After that just apply the parts of the edit by @200_success you agree with (it seems like most you already did yourself, such as the code being properly marked as code)."
}
] | [
{
"body": "<p>You can group by the name and then append an increasing number to it:</p>\n\n<pre><code>import pandas as pd\n\ndef add_count(x):\n return x + ([\"\"] + list(map(str, range(1, len(x)))))\n\ndf = pd.DataFrame(['vegetable', 'fruit', 'meat', 'dairy', 'meat', 'fruit', 'fruit'],\n columns=[\"name\"])\nx = df.groupby(\"name\", as_index=False)[\"name\"].apply(add_count)\ndf[\"name2\"] = x.reset_index(level=0, drop=True)\nprint(df)\n# name name2\n# 0 vegetable vegetable\n# 1 fruit fruit\n# 2 meat meat\n# 3 dairy dairy\n# 4 meat meat1\n# 5 fruit fruit1\n# 6 fruit fruit2\n</code></pre>\n\n<p>This avoids manually iterating over rows or columns, something that is usually a good thing when dealing with <code>pandas</code> dataframes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T16:38:46.463",
"Id": "214712",
"ParentId": "214708",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T14:40:54.040",
"Id": "214708",
"Score": "4",
"Tags": [
"python",
"pandas"
],
"Title": "Cumulative counts of items in a Pandas dataframe"
} | 214708 |
<p>From some generated code I get a
<code>javax.xml.datatype.XMLGregorianCalendar</code> and I want to convert it to a <code>LocalDateTime</code> without any zone-offset (UTC).</p>
<p>My current code accomplishes it, but I think it must be possible to acheaf the same result in a more elegant (and shorter) way.</p>
<pre><code> public static LocalDateTime xmlGregorianCalendar2LocalDateTime(XMLGregorianCalendar xgc) {
// fix the time to UTC:
final int offsetSeconds = xgc.toGregorianCalendar().toZonedDateTime().getOffset().getTotalSeconds();
final LocalDateTime localDateTime = xgc.toGregorianCalendar().toZonedDateTime().toLocalDateTime(); // this simply ignores the timeZone
return localDateTime.minusSeconds(offsetSeconds); // ajust according to the time-zone offet
}
</code></pre>
| [] | [
{
"body": "<p>Something like :</p>\n\n<pre><code>xgc.toGregorianCalendar().toZonedDateTime().toLocalDateTime() ?\n</code></pre>\n\n<p>If you don't want to just rip off the zone information, but instead get the local time at UTC :</p>\n\n<pre><code>ZonedDateTime utcZoned = xgc.toGregorianCalendar().toZonedDateTime().withZoneSameInstant(ZoneId.of(\"UTC\"));\nLocalDateTime ldt = utcZoned.toLocalDateTime();\n</code></pre>\n\n<p>This answer is from the guy who has written the java.time specifications and implemented them btw : <a href=\"https://stackoverflow.com/questions/29767084/convert-between-localdate-and-xmlgregoriancalendar\">https://stackoverflow.com/questions/29767084/convert-between-localdate-and-xmlgregoriancalendar</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T07:09:09.497",
"Id": "415733",
"Score": "0",
"body": "As I wrote in the comment of my code, this ignores the zone-offset -> wrong time (if zone is not +00:00)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T08:30:15.297",
"Id": "415870",
"Score": "0",
"body": "So you just need to convert your zonedDateTime to utcZonedDateTime before converting it to local time, see my completed code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-20T16:40:02.617",
"Id": "461908",
"Score": "1",
"body": "Be aware that the conversion from XmlGregorianCalendar to GregorianCalendar has a slight precision loss. Nanoseconds will be dropped. This will be ok in most use cases."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:37:34.970",
"Id": "214922",
"ParentId": "214711",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "214922",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T16:03:41.923",
"Id": "214711",
"Score": "5",
"Tags": [
"java",
"datetime"
],
"Title": "XMLGregorianCalendar to LocalDateTime"
} | 214711 |
<p><strong>This is what I wan't to do:</strong></p>
<p><a href="https://i.stack.imgur.com/HAss7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HAss7.jpg" alt="enter image description here"></a></p>
<p>In my app I've 2 custom widgets called <code>SelectItems</code>. If the user clicks on item, it changes the background color. Everything is working just fine, but a code, which manages the state is a bit cumbersome:</p>
<pre><code>import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Home(),
);
}
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<SelectItemModel> selectItemModels = [
SelectItemModel(
text: 'First item',
isSelected: true,
),
SelectItemModel(
text: 'Second item',
isSelected: false,
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.only(
top: 60,
),
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: _buildSelectItems(),
),
),
);
}
List<SelectItem> _buildSelectItems() {
List<SelectItem> items = [];
for (var i = 0; i < selectItemModels.length; i++) {
var item = selectItemModels[i];
items.add(SelectItem(
text: item.text,
isSelected: item.isSelected,
onPressed: () => {_select(i)},
));
}
return items;
}
void _select(int index) {
for (var i = 0; i < selectItemModels.length; i++) {
setState(() {
i == index
? selectItemModels[i].isSelected = true
: selectItemModels[i].isSelected = false;
});
}
}
}
class SelectItem extends StatelessWidget {
const SelectItem({
@required this.text,
@required this.isSelected,
@required this.onPressed,
});
final String text;
final bool isSelected;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPressed,
child: Container(
width: 150,
height: 150,
decoration: BoxDecoration(
color: _getColor(isSelected),
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.black38,
width: 2,
),
),
child: Center(
child: Text(text),
),
),
);
}
Color _getColor(bool isSelected) {
return isSelected ? Colors.blueAccent : Colors.white;
}
}
class SelectItemModel {
SelectItemModel({
this.text,
this.isSelected,
});
String text;
bool isSelected;
}
</code></pre>
<p><strong>So how this works:</strong></p>
<p>I've created a custom widget <code>SelectItem</code>. It just displays a square shape with text in it. If it's <code>selected</code>, then the color is blue, otherwise white.</p>
<pre><code>class SelectItem extends StatelessWidget {
const SelectItem({
@required this.text,
@required this.isSelected,
@required this.onPressed,
});
final String text;
final bool isSelected;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPressed,
child: Container(
width: 150,
height: 150,
decoration: BoxDecoration(
color: _getColor(isSelected),
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: Colors.black38,
width: 2,
),
),
child: Center(
child: Text(text),
),
),
);
}
Color _getColor(bool isSelected) {
return isSelected ? Colors.blueAccent : Colors.white;
}
}
</code></pre>
<p>Then I've a <code>SelectItemModel</code>:</p>
<pre><code>class SelectItemModel {
SelectItemModel({
this.text,
this.isSelected,
});
String text;
bool isSelected;
}
</code></pre>
<p>which I use in <code>Home</code> <code>StateFullWidget</code> to fill a List of <code>SelectItems</code>.</p>
<pre><code>class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<SelectItemModel> selectItemModels = [
SelectItemModel(
text: 'First item',
isSelected: true,
),
SelectItemModel(
text: 'Second item',
isSelected: false,
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.only(
top: 60,
),
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: _buildSelectItems(),
),
),
);
}
List<SelectItem> _buildSelectItems() {
List<SelectItem> items = [];
for (var i = 0; i < selectItemModels.length; i++) {
var item = selectItemModels[i];
items.add(SelectItem(
text: item.text,
isSelected: item.isSelected,
onPressed: () => {_select(i)},
));
}
return items;
}
void _select(int index) {
for (var i = 0; i < selectItemModels.length; i++) {
setState(() {
i == index
? selectItemModels[i].isSelected = true
: selectItemModels[i].isSelected = false;
});
}
}
}
</code></pre>
<p>I think this part is the most problematic. Is there a simpler way of filling the widget with child widgets and managing the click behavior?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T17:16:57.527",
"Id": "214714",
"Score": "2",
"Tags": [
"dart",
"flutter"
],
"Title": "Flutter - Set the state of the dynamically created child widgets"
} | 214714 |
<p>Review compatibility, readability, good code standards, security. </p>
<p>This is for development server, where webmaster uses GUI fo IDE and fine way to create quickly apache2 virtualhost using GUI but fallback to text interface is present. Second review of script with applying previous review and adding more features.<br>
I`ll post code parts fist, then whole script and git link to it.</p>
<p>If user runs script without terminal I need to notify him somehow about errors. <code>xmessage</code> provided with X but looks ugly, but looks compatible. May be suggested other way - portable and better looking. User will always get error output in terminal what's fine. In any case if using GUI user suggested to install <code>zenity</code> as a main gui tool of script - that will be message from <code>xmessage</code>.</p>
<pre><code>notify_user () {
echo "$1" >&2
[ -t 0 ] || if type -p notify-send >/dev/null; then notify-send "$1"
else xmessage -buttons Ok:0 -nearmouse "$1" -timeout 10; fi
}
</code></pre>
<p>Is following <code>exit 1</code> exits function or script? I guess only function. That's why empty input not break script, at least tested in giu. How to rewrite this function to handle empty input as error to <code>break</code> script?</p>
<pre><code>get_virtual_host() {
if [ -t 0 ]; then
read -p "Create virtualhost (= Folder name,case sensitive)" -r host
else
host=$(zenity --forms --add-entry=Name --text='Create virtualhost (= Folder name,case sensitive)')
fi
case "$host" in
"") notify_user "Bad input: empty" ; exit 1 ;;
*"*"*) notify_user "Bad input: wildcard" ; exit 1 ;;
*[[:space:]]*) notify_user "Bad input: whitespace" ; exit 1 ;;
esac
echo "$host"
}
host=$(get_virtual_host)
</code></pre>
<p>What is better, hardcode some config string variables, allow input parameters[with leak verification], or make install script what hardcodes input parameters for server, also make .desktop file? I think hardcode is good, as one could hardcode and make permissions to edit and execute. Looks following:</p>
<pre><code>webmaster="leonid" # user who access web files. group is www-data
maindomain=".localhost" # domain for creating subdomains, leading dot required
serveradmin="webmaster@localhost" # admin email
webroot="/home/${webmaster}/Web/" # root folder where subfolders for virtualhosts created
</code></pre>
<p>Full script: (git: <a href="https://github.com/LeonidMew/CreateVirtualHost" rel="nofollow noreferrer">https://github.com/LeonidMew/CreateVirtualHost</a>)</p>
<pre><code>#!/bin/bash
webmaster="leonid" # user who access web files. group is www-data
maindomain=".localhost" # domain for creating subdomains, leading dot required
serveradmin="webmaster@localhost" # admin email
webroot="/home/${webmaster}/Web/" # root folder where subfolders for virtualhosts created
a2ensite="050-" # short prefix for virtualhost config file
apachehost="/etc/apache2/sites-available/${a2ensite}" # prefix for virtualhost config file
tmphost=$(mktemp) # temp file for edit config
trap "rm $tmphost" EXIT # rm temp file on exit
notify_user () {
echo "$1" >&2
[ -t 0 ] || if type -p notify-send >/dev/null; then notify-send "$1"; else xmessage -buttons Ok:0 -nearmouse "$1" -timeout 10; fi
}
if [ -t 0 ];then
usegui=""
else
if ! type -p zenity >/dev/null;then
notify_user "Use terminal or install zenity for gui. '$ sudo apt install zenity'"
exit 1
else
usegui="yes"
fi
fi
# if [ "$(id -un)" == "root" ]
# then
# notify_user "You should not run this script as root but as user going to edit web files."
# exit 1
# fi
get_virtual_host() {
if [ -t 0 ]; then
read -p "Create virtualhost (= Folder name,case sensitive)" -r host
else
host=$(zenity --forms --add-entry=Name --text='Create virtualhost (= Folder name,case sensitive)')
fi
case "$host" in
"") notify_user "Bad input: empty" ; exit 1 ;;
*"*"*) notify_user "Bad input: wildcard" ; exit 1 ;;
*[[:space:]]*) notify_user "Bad input: whitespace" ; exit 1 ;;
esac
echo "$host"
}
host=$(get_virtual_host)
hostfile="${apachehost}${host}.conf" # apache virtualhost config file
dir="${webroot}${host}" # folder used as document root for virtualhost
# virtualhost template
cat >"$tmphost" <<EOF
<VirtualHost *:80>
ServerAdmin $serveradmin
DocumentRoot $dir
ServerName ${host}${maindomain}
ServerAlias ${host}${maindomain}
<Directory "$dir">
AllowOverride All
Require local
</Directory>
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
LogLevel error
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
EOF
if [ ! -z "$usegui" ];then
# edit virtualhost config
text=$(zenity --text-info --title="virtualhost config" --filename="$tmphost" --editable)
if [ -z "$text" ]
then
# cancel button pressed
exit 0
fi
echo "$text" > "$tmphost"
else
# edit virtualhost config
editor=${VISUAL:-$EDITOR}
if [ -z "$editor" ];then
if type -p nano >/dev/null;then editor="nano"; fi
fi
if [ -z "$editor" ];then
if type -p vim >/dev/null;then editor="vim"; fi
fi
if [ -z "$editor" ];then
echo "edit '$tmphost' to your liking, then hit Enter"
read -p "I'll wait ... "
else
"$editor" "$tmphost"
fi
fi
# probably want some validating here that the user has not broken the config
# apache will not reload config if incorrect
getsuperuser () {
if [ ! -z "$usegui" ];then
echo "pkexec"
else
echo "sudo"
fi
}
notify_user "execute root commands with $(getsuperuser) to create virtualhost"
$(getsuperuser) /bin/bash <<EOF
mkdir -p "$dir"
chown ${webmaster}:www-data "$dir"
chmod u=rwX,g=rX,o= "$dir"
cp "$tmphost" "$hostfile"
chown root:root "$hostfile"
chmod u=rw,g=r,o=r "$hostfile"
a2ensite "${a2ensite}${host}.conf"
systemctl reload apache2
EOF
notify_user "Virtualhost added. Apache2 reloaded."
</code></pre>
| [] | [
{
"body": "<h3>Don't repeat yourself</h3>\n\n<p>Some snippets appear repeatedly in the code, for example:</p>\n\n<blockquote>\n<pre><code>if type -p some-command >/dev/null; then ...\n</code></pre>\n</blockquote>\n\n<p>Make it a function:</p>\n\n<pre><code>have_command() {\n type -p \"$1\" >/dev/null\n}\n</code></pre>\n\n<p>And then you can write more naturally:</p>\n\n<pre><code>if have_command notify-send; then\n notify-send ...\nfi\n</code></pre>\n\n<p>The same for checking if running in terminal:</p>\n\n<pre><code>in_terminal() {\n [ -t 0 ]\n}\n</code></pre>\n\n<h3>Avoid excessively long lines</h3>\n\n<p>It can be annoying to have to scroll to the right to see what this line is about:</p>\n\n<blockquote>\n<pre><code>[ -t 0 ] || if type -p notify-send >/dev/null; then notify-send \"$1\"; else xmessage -buttons Ok:0 -nearmouse \"$1\" -timeout 10; fi\n</code></pre>\n</blockquote>\n\n<p>On top of that, I think an <code>if</code> statement is easiest to read in this form:</p>\n\n<pre><code>if ...; then\n ...\nelse\n ...\nfi\n</code></pre>\n\n<p>Lastly, I think it's hard to read when an <code>if</code> statement is chained after a previous command with <code>||</code>.</p>\n\n<p>I would find this easier to read:</p>\n\n<pre><code>in_terminal && return\nif have_command notify-send; then\n notify-send \"$1\"\nelse\n xmessage -buttons Ok:0 -nearmouse \"$1\" -timeout 10\nfi\n</code></pre>\n\n<h3>Use more functions</h3>\n\n<p>This piece of code tries to detect an editor to use, by checking multiple alternatives:</p>\n\n<blockquote>\n<pre><code>editor=${VISUAL:-$EDITOR}\nif [ -z \"$editor\" ];then\n if type -p nano >/dev/null;then editor=\"nano\"; fi\nfi\nif [ -z \"$editor\" ];then\n if type -p vim >/dev/null;then editor=\"vim\"; fi\nfi\nif [ -z \"$editor\" ];then\n echo \"edit '$tmphost' to your liking, then hit Enter\"\n read -p \"I'll wait ... \"\nelse\n \"$editor\" \"$tmphost\"\nfi\n</code></pre>\n</blockquote>\n\n<p>What's not great about this is if the first check succeeds, the other checks still run.\nI mean, if <code>EDITOR</code> is already defined, then <code>if [ -z \"$editor\" ]</code> will still be executed 3 times for nothing.</p>\n\n<p>This is a good opportunity to use a function with <em>early returns</em>:</p>\n\n<pre><code>find_editor() {\n local editor=${VISUAL:-$EDITOR}\n if [ \"$editor\" ]; then\n echo \"$editor\"\n return\n fi\n\n for cmd in nano vim; then\n if have_command \"$cmd\"; then\n echo \"$cmd\"\n return\n fi\n done\n}\n\neditor=$(find_editor)\n\nif [ -z \"$editor\" ]; then\n echo \"edit '$tmphost' to your liking, then hit Enter\"\n read -p \"I'll wait ... \"\nelse\n \"$editor\" \"$tmphost\"\nfi\n</code></pre>\n\n<h3>Simplify conditions</h3>\n\n<p>This condition is written more complicated than it needs to be:</p>\n\n<blockquote>\n<pre><code>if [ ! -z \"$usegui\" ];then\n</code></pre>\n</blockquote>\n\n<p>You can simplify to:</p>\n\n<pre><code>if [ \"$usegui\" ]; then\n</code></pre>\n\n<h3>Missed double-quoting</h3>\n\n<p>You did a good job double-quoting variables used as command arguments. Here's one place you missed:</p>\n\n<blockquote>\n<pre><code>trap \"rm $tmphost\" EXIT\n</code></pre>\n</blockquote>\n\n<p>This would be better written as:</p>\n\n<pre><code>trap 'rm \"$tmphost\"' EXIT\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T06:45:44.387",
"Id": "214748",
"ParentId": "214716",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214748",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T18:24:24.573",
"Id": "214716",
"Score": "1",
"Tags": [
"bash"
],
"Title": "bash script - Create virtualhost on development server (ver 2)"
} | 214716 |
<p>Building on a previous <a href="https://codereview.stackexchange.com/questions/214002/xmlhttprequest-in-the-browser">answer</a> and an attempt to write a comprehensive <code>XMLHttpRequest</code> example that covers all kinds of possible errors and return them to caller gracefully instead of a crash. </p>
<pre><code>function Remote() {}
Remote.upload = function(formData, progressHandler) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000");
xhr.setRequestHeader("Accept", "application/json");
xhr.addEventListener("error", function(event){
reject({code: 0, message: "A network error occurred.", event: event});
});
xhr.upload.addEventListener("progress", progressHandler);
xhr.addEventListener("readystatechange", function() {
if(xhr.readyState == 4 && xhr.status != 0) { // exclude status 0
try {
xhr.status == 200 ? resolve(JSON.parse(xhr.response)) : reject(JSON.parse(xhr.response));
} catch(error) {
reject({code: 0, message: "JSON parsing error.", body: xhr.response});
}
}
});
xhr.send(formData);
});
};
function progressHandler(event) {
if(event.lengthComputable) {
console.log((event.loaded / event.total * 100 | 0));
}
}
</code></pre>
<p>Here in this example, I've added a check in the <code>readystatechange</code> not to handle status 0 errors since event handler can be triggered with all sorts of those errors, whether invalid certificate, offline or request getting suppressed. (Limitation: Can't figure out the exact error scenario hence the generic Network error message.</p>
<ul>
<li>200 status is success as suggested by the REST contract so it's hard coded. </li>
<li>JSON parsing error is also a possibility to handle any issues.</li>
<li>Code is meant to be backward compatible for older browsers.</li>
</ul>
<p>Hope the code is comprehensive and takes care of all corners. </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T18:51:37.680",
"Id": "214719",
"Score": "3",
"Tags": [
"javascript",
"error-handling",
"rest"
],
"Title": "A XMLHttp Request in the browser"
} | 214719 |
<p>Synology NASs have a Task Scheduler that allows you to schedule deletion of files over X days old from recycle bins. This feature isn't working for me–running the task results in no files being deleted. The task works if I schedule a full deletion of the recycle bin, but I'd prefer to only delete a file if it sits in the bin for more than X days. As such, I've created this user script to do so. I want to make sure that it deletes exactly as I want.</p>
<ul>
<li>Only entries within the recycle bin of the specific shared folder <code>/volume1/share1/#recycle/</code></li>
<li>Only files that are over 60 days old</li>
<li><strong>Not</strong> the recycle bin folder itself</li>
<li>Delete empty folders</li>
</ul>
<p>Script: </p>
<pre><code>deletepath="/volume1/share1/#recycle/"
logpath="/volume1/share2/SynoScripts/logs/deleteOlderThanXDays.txt"
errorpath="/volume1/share2/SynoScripts/errors/deleteOlderThanXDays.txt"
now=`date "+%Y-%m-%d %H:%M:%S"`
echo "" >> $logpath
echo $now >> $logpath
echo "" >> $errorpath
echo $now >> $errorpath
# Delete files
/usr/bin/find $deletepath -type f -mtime +60 -exec rm -v {} \; >>$logpath 2>>$errorpath
# Delete empty folders
/usr/bin/find $deletepath -mindepth 1 -type d -empty -exec rmdir {} \; >>$logpath 2>>$errorpath
</code></pre>
<p>Does this script appear to satisfy my requirements?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T20:56:18.443",
"Id": "415218",
"Score": "0",
"body": "Are you required to remove non-plain files, such as device nodes, sockets, FIFOs and devices?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T09:28:53.617",
"Id": "468035",
"Score": "0",
"body": "Does your `find` implementation have the `-delete` predicate? That could save a lot of processes."
}
] | [
{
"body": "<p>If this is intended to be run as a command, I recommend you add a suitable shebang line. Although the question is tagged <a href=\"/questions/tagged/bash\" class=\"post-tag\" title=\"show questions tagged 'bash'\" rel=\"tag\">bash</a>, there's nothing here that isn't portable POSIX shell, so I recommend</p>\n\n<pre><code>#!/bin/sh\n</code></pre>\n\n<hr>\n\n<p>Is it intentional that the paths all share a common initial prefix <code>/volume1</code> and that the log and error paths share a longer common prefix? If so, encode that for easier re-use:</p>\n\n<pre><code>volume=/volume1\nscriptdir=$volume/share2/SynoScripts\nlogpath=$scriptdir/logs/deleteOlderThanXDays.txt\nerrorpath=$scriptdir/errors/deleteOlderThanXDays.txt\n</code></pre>\n\n<p>Personally, I'd call those last two <code>logfile</code> and <code>errorfile</code> for clarity.</p>\n\n<p>There's no need to quote the values in these assignments, but the values should be quoted when used later, so that we don't break the script when they change to include spaces or other significant characters.</p>\n\n<hr>\n\n<p>Instead of multiple <code>echo</code> commands, consider using a single <code>date</code> with <code>tee</code>:</p>\n\n<pre><code>date '+%n%Y-%m-%d %T' | tee -a \"$logpath\" >>\"$errorpath\"\n</code></pre>\n\n<p>After that, we can simply redirect all output and errors:</p>\n\n<pre><code>exec >>\"$logpath\" 2>>\"$errorpath\"\n</code></pre>\n\n<hr>\n\n<p>When using <code>find</code>, prefer to group many arguments into a few commands, using <code>+</code> instead of <code>\\;</code>:</p>\n\n<pre><code>find \"$deletepath\" \\! -type d -mtime +60 -exec rm -v '{}' +\nfind \"$deletepath\" -mindepth 1 -type d -empty -exec rmdir -v '{}' +\n</code></pre>\n\n<p>I assume you meant to use <code>-v</code> consistently for both commands here.</p>\n\n<hr>\n\n<p>Modified version</p>\n\n<pre><code>#!/bin/sh\n\nvolume=/volume1\nscriptdir=\"$volume/share2/SynoScripts\"\n\ndeletepath=\"$volume/share1/#recycle\"\nlogpath=\"$scriptdir/logs/deleteOlderThanXDays.txt\"\nerrorpath=\"$scriptdir/errors/deleteOlderThanXDays.txt\"\n\n# redirect all output and errors\nexec >>\"$logpath\" 2>>\"$errorpath\"\n\n# log the start time to both logs\ndate '+%n%Y-%m-%d %T' | tee -a \"$errorpath\"\n\n# delete old non-directory files (including devices, sockets, etc)\nfind \"$deletepath\" \\! -type d -mtime +60 -exec rm -v '{}' +\n\n# delete empty directories, regardless of age\nfind \"$deletepath\" -mindepth 1 -type d -empty -exec rmdir -v '{}' +\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T21:19:19.710",
"Id": "214727",
"ParentId": "214721",
"Score": "3"
}
},
{
"body": "<p>I think the modified date doesn't change when the file is moved to #Recycle area, so if the file is already older than 60 days, it will deleted the next time the script runs.</p>\n\n<p>I have observed that the 'change' date gets reset when moved to a new directory. Do a 'stat' or 'ls -lc' of the file before and after moving to different directory and you should see the 'change' date reset to current time, while the 'modified' date does not change.</p>\n\n<p>I haven't had time to figure out how to modify the script to use 'change' time instead of 'modfied' time, but I bet some clever person could code that. Using the 'change' date should give you the full 60 days to recover the file.</p>\n\n<p>--- update 2020.June.3 ---\nLooks as though the recent update to DSM, 6.2.3-25426, may have fixed Synology's method for purging the #recycle area based on how many days have passed since items were moved to the #recycle area.\nI had been tinkering with a find command for searching for aged files & folders but not deleting them, only to find that after the update, almost all the aged files, over 60 days, got purged and a bunch of my free disk space was reclaimed.</p>\n\n<p>Anyway .. the core method that seemed to be finding the 60 day aged files in the #recycle bin, though I had not tested with '-delete'</p>\n\n<p>find /volume1/Data/#recycle -depth -mindepth 1 -ctime +60 -type f -print -delete</p>\n\n<p>find /volume1/Data/#recycle -depth -mindepth 1 -type d -empty -print -delete</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T07:50:42.087",
"Id": "468020",
"Score": "0",
"body": "Welcome to CodeReview@SE. There is a `-ctime`-flag to `find` entirely analogous to `-mtime`. A pity `touch` doesn't figure such. From non-NAS use, I seem to remember ctime changes after moves between file-systems, but not for moves between directories on the same FS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T09:40:25.017",
"Id": "468038",
"Score": "0",
"body": "Creating a new name for a file wouldn't normally affect the ctime value, unless it's a cross-filesystem move."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T23:53:56.173",
"Id": "473715",
"Score": "0",
"body": "So something like this (I haven't tested) to purge recycled files/folders after they have been there over 60 days:\n\ncd to the #recycle ; \n\nfind . -depth -mindepth 1 -type f -ctime +60 -delete ; \n\nfind . -depth -mindepth 1 -type d -empty -delete ; \n\nSome useful references: \n<https://www.gnu.org/software/findutils/manual/html_node/find_html/Age-Ranges.html#index-_002dctime>. \n<https://www.gnu.org/software/findutils/manual/html_node/find_html/Delete-Files.html#Delete-Files>. \n<https://www.gnu.org/software/findutils/manual/html_node/find_html/Size.html#index-_002dempty>"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T06:29:56.107",
"Id": "238657",
"ParentId": "214721",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214727",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T19:41:51.673",
"Id": "214721",
"Score": "2",
"Tags": [
"bash",
"file-system",
"scheduled-tasks"
],
"Title": "Bash on Synology - Delete recycle bin entries over X days old"
} | 214721 |
<p>I am developing my own kind of Enumeration like <a href="https://github.com/ardalis/SmartEnum" rel="nofollow noreferrer"><code>SmartEnum</code></a> but trying to prevent the user to provide a recursive-ish type definition like below:</p>
<blockquote>
<pre><code>public sealed class TestEnum : SmartEnum<TestEnum>
{
public static readonly TestEnum One = new TestEnum(nameof(One), 1);
public static readonly TestEnum Two = new TestEnum(nameof(Two), 2);
public static readonly TestEnum Three = new TestEnum(nameof(Three), 3);
private TestEnum(string name, int value)
: base(name, value)
{
}
}
</code></pre>
</blockquote>
<p>I ended up on this code: </p>
<pre><code>public static class EnumerationHelpers
{
public static TEnumeration ParseName<TEnumeration>(string name)
where TEnumeration : Enumeration
{
return EnumerationCacheProvider<TEnumeration>.Get().Names[name];
}
// Lack of inference from the compiler, cannot write
// public static TEnumeration ParseValue<TEnumeration, TValue>(TValue value)
// where TEnumeration : Enumeration
public static TEnumeration ParseValue<TEnumeration>(object value)
where TEnumeration : Enumeration
{
return EnumerationCacheProvider<TEnumeration>.Get().Values[value];
}
public static IEnumerable<TEnumeration> GetAll<TEnumeration>()
where TEnumeration : Enumeration
{
return EnumerationCacheProvider<TEnumeration>.Get().All;
}
public static IEnumerable<object> GetValues<TEnumeration>()
where TEnumeration : Enumeration
{
return EnumerationCacheProvider<TEnumeration>.Get().Values.Keys;
}
public static IEnumerable<string> GetNames<TEnumeration>()
where TEnumeration : Enumeration
{
return EnumerationCacheProvider<TEnumeration>.Get().Names.Keys;
}
}
internal class EnumerationCache<TEnumeration>
where TEnumeration : Enumeration
{
public readonly IReadOnlyCollection<TEnumeration> All;
public readonly IReadOnlyDictionary<string, TEnumeration> Names;
public readonly IReadOnlyDictionary<object, TEnumeration> Values;
public EnumerationCache(IEnumerable<TEnumeration> source)
{
var list = source.ToList();
var names = new Dictionary<string, TEnumeration>();
var values = new Dictionary<object, TEnumeration>();
foreach (var item in list)
{
// First definitions found are subsequently overriden
if (!names.ContainsKey(item.Name))
{
names[item.Name] = item;
}
if (!values.ContainsKey(item.Value))
{
values[item.Value] = item;
}
}
All = new ReadOnlyCollection<TEnumeration>(list);
Names = names;
Values = values;
}
}
internal static class EnumerationCacheFactory<TEnumeration>
where TEnumeration : Enumeration
{
public static EnumerationCache<TEnumeration> Create()
{
var enumerationType = typeof(TEnumeration);
var nameValues = enumerationType
.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
.Where(field => field.FieldType == enumerationType)
.Select(field => (TEnumeration) field.GetValue(null));
return new EnumerationCache<TEnumeration>(nameValues);
}
}
internal class EnumerationCacheProvider<TEnumeration>
where TEnumeration : Enumeration
{
private static readonly Lazy<EnumerationCache<TEnumeration>> EnumerationCache;
static EnumerationCacheProvider()
{
EnumerationCache = new Lazy<EnumerationCache<TEnumeration>>(EnumerationCacheFactory<TEnumeration>.Create);
}
public static EnumerationCache<TEnumeration> Get()
{
return EnumerationCache.Value;
}
}
// Base class to not end up on multiple generic issue in helper methods
public abstract class Enumeration : IComparable
{
public string Name { get; }
public object Value { get; }
protected Enumeration(string name, object value)
{
Name = name;
Value = value;
}
public override bool Equals(object other)
{
if (!(other is Enumeration otherValue))
{
return false;
}
var typeMatches = GetType() == other.GetType();
var valueMatches = Value.Equals(otherValue.Value);
return typeMatches && valueMatches;
}
public override int GetHashCode() => Value.GetHashCode();
public int CompareTo(object other)
{
return Comparer.Default.Compare(Value, ((Enumeration) other).Value);
}
public static bool operator ==(Enumeration left, Enumeration right)
{
return Equals(left, right);
}
public static bool operator !=(Enumeration left, Enumeration right)
{
return !Equals(left, right);
}
}
public abstract class Enumeration<TValue> : Enumeration, IEquatable<Enumeration<TValue>>, IComparable<Enumeration<TValue>>
{
public new TValue Value => (TValue) base.Value;
protected Enumeration(string name, TValue value)
: base(name, value)
{
}
public bool Equals(Enumeration<TValue> other)
{
return Equals(other as object);
}
public override bool Equals(object other)
{
if (!(other is Enumeration<TValue> otherValue))
{
return false;
}
var typeMatches = GetType() == other.GetType();
var valueMatches = Value.Equals(otherValue.Value);
return typeMatches && valueMatches;
}
public override int GetHashCode() => Value.GetHashCode();
public int CompareTo(Enumeration<TValue> other)
{
return Comparer<TValue>.Default.Compare(Value, other.Value);
}
public static bool operator ==(Enumeration<TValue> left, Enumeration<TValue> right)
{
return Equals(left, right);
}
public static bool operator !=(Enumeration<TValue> left, Enumeration<TValue> right)
{
return !Equals(left, right);
}
}
</code></pre>
<p>Which can be used as:</p>
<pre><code>public class Card : Enumeration<int>
{
public static readonly Card ClubKing = new Card(nameof(ClubKing), 1);
public static readonly Card ClubQueen = new Card(nameof(ClubQueen), 2);
public static readonly Card HeartKing = new Card(nameof(HeartKing), 1);
private Card(string name, int value)
: base(name, value)
{
}
}
public static class Program
{
public static void Main(params string[] args)
{
var cards = EnumerationHelpers.GetAll<Card>();
var cardNames = EnumerationHelpers.GetNames<Card>();
var cardValues = EnumerationHelpers.GetValues<Card>();
var clubKing = EnumerationHelpers.ParseName<Card>("ClubKing");
clubKing = EnumerationHelpers.ParseValue<Card>(1);
}
}
</code></pre>
<p>A few things:</p>
<ul>
<li>Yup there is a bit of boxing here and there in order to maintain a single root class since the inference for the helper methods do not work with several generic parameters.</li>
<li>The first value or name found is not overridden by subsequent definition of the same value or name.</li>
</ul>
<p>I am looking for feedbacks that can help to improve my implementation that aims to provide a good alternative to traditional C# <code>enum</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T19:58:05.217",
"Id": "415215",
"Score": "0",
"body": "You may find this to your interests: https://codeblog.jonskeet.uk/2009/09/10/generic-constraints-for-enums-and-delegates/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T20:00:21.557",
"Id": "415216",
"Score": "0",
"body": "@JesseC.Slicer I know that article but this is not really related to what I am trying to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T05:39:10.637",
"Id": "415257",
"Score": "4",
"body": "I'm not sure I understand the concept and why it is necessary. Could you provide some more realistic use cases where you think this is more useful (smarter) than plain C# `enum` and classes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T07:39:46.490",
"Id": "415265",
"Score": "0",
"body": "@HenrikHansen the reason is the same as why https://github.com/ardalis/SmartEnum and https://github.com/HeadspringLabs/Enumeration: to provide java-like enumerations. `enum`s in .NET are just numbers and you cannot use anything else (except leveraging reflection on fields attributes). \n\nUnlike the SmartEnum library, my solution aims at providing simpler helper methods and simpler inheritance while trading those against more boxing allocations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:08:22.437",
"Id": "415267",
"Score": "0",
"body": "Not really smart that other _smart-enum_... I'd like to join @HenrikHansen request and ask you too to summarize the features that your smarter-enum is about. You have just posted some code but we don't know how it is supposed to work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:11:02.783",
"Id": "415268",
"Score": "0",
"body": "@t3chb0t there is an example in my post, is it not enough?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:12:42.483",
"Id": "415270",
"Score": "0",
"body": "@t3chb0t the same sort of Enumeration is created for eShopContainer for the DDD-ish service as part of their seed work: of https://github.com/dotnet-architecture/eShopOnContainers/blob/53479908a08232a80769de80237ccd181cd213f2/src/Services/Ordering/Ordering.Domain/SeedWork/Enumeration.cs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:13:41.270",
"Id": "415271",
"Score": "0",
"body": "If this is all then it doesn't look very useful... no comparisons, no casting, no equalities, no bit operations... mhmm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:34:19.083",
"Id": "415274",
"Score": "0",
"body": "Re \"*trying to prevent the user to provide a recursive-ish type definition like below:*\", I may be missing something, but doesn't your `Card` example exactly duplicate the recursive definition of `TestEnum`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:36:48.377",
"Id": "415275",
"Score": "0",
"body": "@Peter Taylor `TestEnum : SmartEnum<TestEnum>` TestEnum has to be defined as the defining class and the generic parameter of the parent class at the same time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T09:55:16.600",
"Id": "415283",
"Score": "0",
"body": "@EhouarnPerret: OK, I'm just not convinced about the usefulness of this approach. But +1 for the question and code, because of the efforts and thoughts you have put into it."
}
] | [
{
"body": "<p>I'm not entirely convinced of the need for this class - in my experience, using extension methods for enum classes which need more than the basic functionality is sufficient. Also this lacks some things which native enums have, in particular an equivalent of <code>[Flags]</code> (which is useful in parsing and <code>ToString</code>).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static TEnumeration ParseName<TEnumeration>(string name)\n where TEnumeration : Enumeration\n {\n return EnumerationCacheProvider<TEnumeration>.Get().Names[name];\n }\n</code></pre>\n</blockquote>\n\n<p>(and similar methods). What exceptions can this throw? Are they what someone who is switching over from <code>Enum.Parse</code> would expect?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // Lack of inference from the compiler, cannot write\n // public static TEnumeration ParseValue<TEnumeration, TValue>(TValue value)\n // where TEnumeration : Enumeration\n public static TEnumeration ParseValue<TEnumeration>(object value)\n where TEnumeration : Enumeration\n</code></pre>\n</blockquote>\n\n<p>What you <em>can</em> write is</p>\n\n<pre><code> public static TEnumeration ParseValue<TEnumeration, TValue>(TValue value)\n where TEnumeration : Enumeration<TValue>\n</code></pre>\n\n<p>It's not clear from the comment whether you are aware of this and have rejected it, or whether you overlooked it.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> foreach (var item in list)\n {\n // First definitions found are subsequently overriden\n if (!names.ContainsKey(item.Name))\n {\n names[item.Name] = item;\n }\n if (!values.ContainsKey(item.Value))\n {\n values[item.Value] = item;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>The comment says the complete opposite of what the code actually does.</p>\n\n<p>Would it not be more robust to throw an exception if the same name or value occurs twice? I can't tell, for example, whether it's an error that the <code>Card</code> example defines two different cards with the same value, but I think it probably is and should be caught as early as possible.</p>\n\n<hr>\n\n<p>The existence of <code>EnumerationCacheFactory<TEnumeration></code> and <code>EnumerationCacheProvider<TEnumeration></code> seems to me to be an \"architecture astronaut\" tendency. I see no reason why their fragments of code couldn't be included in <code>EnumerationCache</code>, and as a bonus <code>EnumerationCache</code>'s constructor could be made private.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var nameValues = enumerationType\n .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)\n</code></pre>\n</blockquote>\n\n<p>Why <code>Public</code>? In my opinion you're missing an opportunity here.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static EnumerationCache<TEnumeration> Get()\n {\n return EnumerationCache.Value;\n }\n</code></pre>\n</blockquote>\n\n<p>I would be tempted to replace this with some transparent properties</p>\n\n<pre><code> public static IReadOnlyDictionary<string, TEnumeration> Names => EnumerationCache.Value.Names\n</code></pre>\n\n<p>etc.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public override bool Equals(object other)\n {\n if (!(other is Enumeration otherValue))\n {\n return false;\n }\n\n var typeMatches = GetType() == other.GetType();\n var valueMatches = Value.Equals(otherValue.Value);\n\n return typeMatches && valueMatches;\n }\n</code></pre>\n</blockquote>\n\n<p>Why not simplify to</p>\n\n<pre><code> public override bool Equals(object other)\n {\n if (ReferenceEquals(other, null) || GetType() != other.GetType())\n {\n return false;\n }\n\n return Value.Equals(((TEnumeration)otherValue).Value);\n }\n</code></pre>\n\n<p>Also, the constructor doesn't require <code>value</code> to be non-null, so either that or various other methods are buggy.</p>\n\n<hr>\n\n<p>Why does <code>Enumeration<TValue></code> override <code>Enumeration.Equals</code>, <code>Enumeration.GetHashCode</code>, etc? The overrides don't change the behaviour at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T16:00:44.747",
"Id": "415338",
"Score": "0",
"body": "* `public static TEnumeration ParseValue<TEnumeration, TValue>(TValue value) where TEnumeration : Enumeration<TValue>`\n\n\"It's not clear from the comment whether you are aware of this and have rejected it, or whether you overlooked it.\"\n\nCause `TValue` is not inferred by the compiler so that the call would be: `Parse<Card, int>(1) and sadly, not Parse<Card>(1)`.\n\n* \"The comment says the complete opposite of what the code actually does.\": correct, I forgot to put a \"not\" in that comment.\n\n* \"Why not simplify to [...]\": agree with you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T09:28:38.247",
"Id": "214753",
"ParentId": "214723",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "214753",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T19:49:21.047",
"Id": "214723",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
"enum"
],
"Title": "Enhanced C# Enumeration / `enum`"
} | 214723 |
<p>I have this algorithm, called <a href="https://en.wikipedia.org/wiki/Variable_elimination" rel="nofollow noreferrer">Variable Elimination</a>, which is used quite often in my code-base (library). It is an algorithm for factor graphs (a type of bipartite graphs), used to efficiently maximize something over the nodes, thus I need to make it as fast as possible.</p>
<p>Since I had 5 separate implementations of this algorithm, and I'll probably need more in the future, I wanted to coalesce the algorithm into a single functor class.</p>
<p>Now, the main problem is that this is kind of a meta-algorithm. While the main steps are always the same, the specifics differ depending on what you are trying to actually accomplish by using the algorithm, and on what data structures you are using. Think of this as std::sort, which takes a lambda as a parameter for custom sorting; but here it's a lot messier. There's 4 nested loops total, and I may need to do custom operations between them. These custom operations may also need to store temporaries.</p>
<p>I have no idea whether there are best practices for this use-case, so the only idea I could come up with was to force the user to define a custom "global" structure which they have to pass in. This structure should provide a bunch of callbacks, which are then called within the algorithm itself to make everything run correctly. Some optional callbacks are called only if they exist using <code>if constexpr</code>.</p>
<p>I've already tested this, and while the usage is not super-pretty, I can use this algorithm in ~50 lines of code rather than 150 (and avoid duplication), which I guess it's a plus.</p>
<p>I'm looking for feedback on whether this approach makes any sense at all, and possibly what the alternatives are.</p>
<pre><code>#ifndef AI_TOOLBOX_FACTORED_GENERIC_VARIABLE_ELIMINATION_HEADER_FILE
#define AI_TOOLBOX_FACTORED_GENERIC_VARIABLE_ELIMINATION_HEADER_FILE
#include <AIToolbox/Factored/Utils/Core.hpp>
#include <AIToolbox/Factored/Utils/FactorGraph.hpp>
namespace AIToolbox::Factored {
/**
* @brief This class represents the Variable Elimination algorithm.
*
* This class applies Variable Elimination to an input FactorGraph<Factor>.
*
* Since the cross-sum steps in the algorithm differ from the type of node
* in the graph, we require as input a separate structure which may contain
* certain methods depending on what the use-case requires, and which holds
* any needed temporaries to store for the duration of the algorithm.
*
* In particular, this structure (the `global` parameter), *MUST* provide:
*
* - A member `Factor newFactor` which stores the results of the cross-sum
* of each removed variable. At each iteration over the values of that
* variable's neighbors, we move from it, so be sure to re-initialize it
* if needed.
* - A member `void crossSum(const Factor &)` function, which should
* perform the cross-sum of the input into the `newFactor` member
* variable.
* - A member `void makeResult(FinalFactors &&)` method, which should
* process the final factors of the VE process in order to create your
* result.
*
* Since VE usually requires custom computations, you can *OPTIONALLY*
* define the following methods:
*
* - A member `void beginRemoval()` method, which is called at the
* beginning of the removal of each variable.
* - A member `void initNewFactor()` method, which is called when the
* `newFactor` variable needs to be initialized.
* - A member `void beginCrossSum()` method, which is called at the
* beginning of each set of cross-sum operations.
* - A member `void endCrossSum()` method, which is called at the end of
* each set of cross-sum operations.
* - A member `bool isValidNewFactor()` method, which returns whether the
* `newFactor` variable can be used after all cross-sum operations.
* - A member `void mergeRules(Rules &&, Rules &&)` method, which can be
* used to specify a custom step during the merge of the rules created by
* eliminating a variable with the previous ones.
*
* All these functions can optionally be `const`; nothing changes. The
* class will fail to compile if you provide a method with the required
* name but with the wrong signature, as we would just skip it silently
* otherwise.
*
* @tparam Factor The Factor type to use.
*/
template <typename Factor>
class GenericVariableElimination {
public:
using Rule = std::pair<PartialValues, Factor>;
using Rules = std::vector<Rule>;
using Graph = FactorGraph<Rules>;
using FinalFactors = std::vector<Factor>;
/**
* @brief This operator performs the Variable Elimination operation on the inputs.
*
* @param F The space of all factors to eliminate.
* @param graph The already populated graph to perform VE onto.
* @param global The global callback structure.
*/
template <typename Global>
void operator()(const Factors & F, Graph & graph, Global & global);
private:
/**
* @brief An helper struct to validate the interface of the global callback structure.
*
* @tparam M The type of the global callback structure to validate.
*/
template <typename M>
struct global_interface;
/**
* @brief This function removes the input factor from the graph.
*
* @param F The space of all factors to eliminate.
* @param graph The already populated graph to perform VE onto.
* @param f The factor to eliminate.
* @param finalFactors The storage of all the eliminated factors with no remaining neighbors.
* @param global The global callback structure.
*/
template <typename Global>
void removeFactor(const Factors & F, Graph & graph, const size_t f, FinalFactors & finalFactors, Global & global);
};
template <typename Factor>
template <typename M>
struct GenericVariableElimination<Factor>::global_interface {
private:
#define STR2(X) #X
#define STR(X) STR2(X)
#define ARG(...) __VA_ARGS__
// For each function we want to check, we are going to try each
// overload in succession (char->int->long->...).
//
// The first two simply accept the function with the approved
// signature, whether it is const or not. The third checks whether
// the member just exists, and reports that it probably has the
// wrong signature (since we didn't match before).
//
// The last just fails to find the match.
#define MEMBER_CHECK(name, retval, input) \
\
template <typename Z> static constexpr auto name##Check(char) -> decltype( \
static_cast<retval (Z::*)(input)> (&Z::name), \
bool() \
) { return true; } \
template <typename Z> static constexpr auto name##Check(int) -> decltype( \
static_cast<retval (Z::*)(input) const> (&Z::name), \
bool() \
) { return true; } \
template <typename Z> static constexpr auto name##Check(long) -> decltype( \
&Z::name, \
bool()) \
{ \
static_assert(!std::is_same_v<M, M>, "You provide a member '" STR(name) "' but with the wrong signature."); \
return false; \
} \
template <typename Z> static constexpr auto name##Check(...) -> bool { return false; }
MEMBER_CHECK(beginRemoval, void, ARG(const Graph &, const typename Graph::FactorItList &, const typename Graph::VariableList &, const size_t))
MEMBER_CHECK(initNewFactor, void, void)
MEMBER_CHECK(beginCrossSum, void, void)
MEMBER_CHECK(crossSum, void, const Factor &)
MEMBER_CHECK(endCrossSum, void, void)
MEMBER_CHECK(isValidNewFactor, bool, void)
MEMBER_CHECK(mergeRules, Rules, ARG(Rules &&, Rules &&))
MEMBER_CHECK(makeResult, void, FinalFactors &&)
#undef MEMBER_CHECK
#undef ARG
#undef STR
#undef STR2
public:
// All results are stored here for use later. All optional members
// that do not exist, we simply do not call.
enum {
beginRemoval = beginRemovalCheck<M> ('\0'),
initNewFactor = initNewFactorCheck<M> ('\0'),
beginCrossSum = beginCrossSumCheck<M> ('\0'),
crossSum = crossSumCheck<M> ('\0'),
endCrossSum = endCrossSumCheck<M> ('\0'),
isValidNewFactor = isValidNewFactorCheck<M> ('\0'),
mergeRules = mergeRulesCheck<M> ('\0'),
makeResult = makeResultCheck<M> ('\0'),
};
};
template <typename Factor>
template <typename Global>
void GenericVariableElimination<Factor>::operator()(const Factors & F, Graph & graph, Global & global) {
static_assert(global_interface<Global>::crossSum, "You must provide a crossSum method!");
static_assert(global_interface<Global>::makeResult, "You must provide a makeResult method!");
static_assert(std::is_same_v<Factor, decltype(global.newFactor)>, "You must provide a public 'Factor newFactor;' member!");
FinalFactors finalFactors;
// This can possibly be improved with some heuristic ordering
while (graph.variableSize())
removeFactor(F, graph, graph.variableSize() - 1, finalFactors, global);
global.makeResult(std::move(finalFactors));
}
template <typename Factor>
template <typename Global>
void GenericVariableElimination<Factor>::removeFactor(const Factors & F, Graph & graph, const size_t f, FinalFactors & finalFactors, Global & global) {
const auto factors = graph.getNeighbors(f);
auto variables = graph.getNeighbors(factors);
PartialFactorsEnumerator jointActions(F, variables, f);
const auto id = jointActions.getFactorToSkipId();
Rules newRules;
if constexpr(global_interface<Global>::beginRemoval)
global.beginRemoval(graph, factors, variables, f);
// We'll now create new rules that represent the elimination of the
// input variable for this round.
const bool isFinalFactor = variables.size() == 1;
while (jointActions.isValid()) {
auto & jointAction = *jointActions;
if constexpr(global_interface<Global>::initNewFactor)
global.initNewFactor();
for (size_t sAction = 0; sAction < F[f]; ++sAction) {
if constexpr(global_interface<Global>::beginCrossSum)
global.beginCrossSum();
jointAction.second[id] = sAction;
for (const auto factor : factors)
for (const auto rule : factor->getData())
if (match(factor->getVariables(), rule.first, jointAction.first, jointAction.second))
global.crossSum(rule.second);
if constexpr(global_interface<Global>::endCrossSum)
global.endCrossSum();
}
bool isValidNewFactor = true;
if constexpr(global_interface<Global>::isValidNewFactor)
isValidNewFactor = global.isValidNewFactor();
if (isValidNewFactor) {
if (!isFinalFactor) {
newRules.emplace_back(jointAction.second, std::move(global.newFactor));
// Remove new agent ID
newRules.back().first.erase(newRules.back().first.begin() + id);
}
else
finalFactors.push_back(std::move(global.newFactor));
}
jointActions.advance();
}
// And finally as usual in variable elimination remove the variable
// from the graph and insert the newly created variable in.
for (const auto & it : factors)
graph.erase(it);
graph.erase(f);
if (!isFinalFactor && newRules.size()) {
variables.erase(std::remove(std::begin(variables), std::end(variables), f), std::end(variables));
auto newFactorNode = graph.getFactor(variables)->getData();
if constexpr(global_interface<Global>::mergeRules) {
newFactorNode = global.mergeRules(std::move(newFactorNode), std::move(newRules));
} else {
newFactorNode.insert(
std::end(newFactorNode),
std::make_move_iterator(std::begin(newRules)),
std::make_move_iterator(std::end(newRules))
);
}
}
}
}
#endif
</code></pre>
<p>Here is an example of a <code>Global</code> implementation, just to give you an idea:</p>
<pre><code>struct Global {
LP & lp;
const size_t phiId;
Factor newFactor;
void initNewFactor() {
newFactor = lp.row.size();
lp.addColumn();
lp.addColumn();
}
void beginCrossSum() {
lp.row.setZero();
lp.row[newFactor] = -1.0;
}
void crossSum(const Factor & f) {
lp.row[f] = 1.0;
}
void endCrossSum() {
lp.pushRow(LP::Constraint::LessEqual, 0.0);
// Now do the reverse for all opposite rules (same rules +1)
for (int i = lp.row.size() - 2; i >= 0; --i) {
if (lp.row[i] != 0.0) {
lp.row[i+1] = lp.row[i];
lp.row[i] = 0.0;
}
}
lp.pushRow(LP::Constraint::LessEqual, 0.0);
}
void makeResult(VE::FinalFactors && finalFactors) {
// Finally, add the two phi rules for all remaining factors.
lp.row.setZero();
lp.row[phiId] = -1.0;
for (const auto ruleId : finalFactors)
lp.row[ruleId] = 1.0;
lp.pushRow(LP::Constraint::LessEqual, 0.0);
// Now do the reverse for all opposite rules (same rules +1)
for (const auto ruleId : finalFactors) {
lp.row[ruleId] = 0.0;
lp.row[ruleId+1] = 1.0;
}
lp.pushRow(LP::Constraint::LessEqual, 0.0);
}
};
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T19:55:03.957",
"Id": "214724",
"Score": "3",
"Tags": [
"c++",
"functional-programming",
"template",
"c++17"
],
"Title": "Generic Variable Elimination with multiple entry points"
} | 214724 |
<p>This semester a classmate and I visited a course on functional programming in our university. For grading, we've to submit a small project which should be written in Clojure and make use of functional programming.
However, the topic of the course itself was mostly about Clojure and its syntax and not so much about functional programming itself. That's why we're not quite sure if our code complies with functional programming paradigms.</p>
<p>It would be highly appreciated if someone takes a look at our code to point out flaws and possible violations of functional programming.
If you see anything that could be written simpler or seems confusing to you, please point it out, since we're new to Clojure and not sure if we've done everything correctly or in the most efficient way (probably not). </p>
<p>Following below is the main part of our code. The entire project can be found <a href="https://gitlab.mi.hdm-stuttgart.de/mk255/rss-feeds-webapp/tree/43562851ed1eb80dd3ac23a130eb35f50d9fcc4c" rel="nofollow noreferrer">in our Gitlab repository</a>.
Since it's a web app we've used hiccup, ring and compojure.
The main functionalities are a landing page at <code>/</code>, which lets you either put in a RSS Feed url or select one RSS Feed from categories provided by us.
Once you submit you're routed to <code>/feed</code>. Here we render the separate items of the current feed.
You've the possibility to filter the feed by typing something, like 'Trump' and as a result we only show the feed items that include the word 'Trump' either in the title or the description. Additionally those "matches" are afterwards highlighted like so:</p>
<p><a href="https://i.stack.imgur.com/PjH8y.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PjH8y.jpg" alt="enter image description here"></a></p>
<p>Furthermore, there's the possibility to filter by author. All authors of the current feed are available as an option in a select box.</p>
<p><strong>Code</strong>
<em>feed.clj</em></p>
<pre><code> (ns rss-feeds-webapp.feed
(:require
[compojure.core :refer :all]
[ring.middleware.defaults :refer [wrap-defaults site-defaults]]
[clj-http.client :as client]
[clojure.java.io :as io]
[clojure.xml :as xml]
[clojure.string :as string])
(:import [java.io ByteArrayInputStream])
(:use
[rss-feeds-webapp.helper :refer :all]
))
;; gets the feed from the url, then parses it to an byte array and then to an xml sequenze
(defn get-feed [link]
(xml-seq (xml/parse (io/input-stream (ByteArrayInputStream. (.getBytes (:body (client/get link)) "UTF-8"))))) )
;; returns the content of the xml tag
;; @param [item] xml-seq the post item which contains the title, description and link7
;; @param [tag] key the tag, that contains the information you want, e.g. title
(defn get-content [item tag]
(for [x item
:when (= tag (:tag x))]
(first (:content x))))
;; creates an hash-map for the feed item, containing the title, description, link, creator and pubDate (if it exists)
;; param [item] xml-seq the post item,
(defn get-item [item]
{:title (get-content item :title )
:description (get-content item :description)
:link (get-content item :link)
:pubDate (get-content item :pubDate)
:image (get-content item :image)
:creator (get-content item :dc:creator)
}
)
;; creates an hash-map for the feed item, containing the creator
;; param [item] xml-seq the post item,
(defn get-author [item]
{:creator (get-content item :dc:creator)
})
;; finds all feed items and calls the get-item function for each one
;; @param [item] xml-seq the post item which contains the title, description, creator and link
(defn get-items [ return-items link]
(for [x (get-feed link)
:when (= :item (:tag x))]
(conj return-items(get-item (:content x)))))
;; finds all feed items and calls the get-author function for each one
;; @param [item] xml-seq the post item which contains the creator
(defn get-authors [ return-authors link]
(for [x (get-feed link)
:when (= :item (:tag x))]
(conj return-authors(get-author (:content x)))))
;; we define a default Value to filterTerm in case it's null
;; then we filter the items so that either the title or the description of the feed contain the filter term and the author equals the authorTerm
(defn filter-items-by-term [term author]
(let [term (or term "")]
(let [author (or author "")]
(fn [[item]]
(and (or
(string/includes?
(simplify-string (apply str (get item :title)))
(simplify-string term))
(string/includes?
(simplify-string (apply str (get item :description)))
(simplify-string term))
)
(string/includes?
(simplify-string (apply str (get item :creator)))
(simplify-string author))
)))))
;; calls the get-items function, in the end it returns an array with all the items
;; items get filtered by filter term
(defn get-feed-data [link & [filterTerm authorTerm]]
(filter (filter-items-by-term filterTerm authorTerm) (get-items [] link))
)
;; calls the get-authors function, in the end it returns an array with all authors
(defn get-feed-authors [link]
(distinct (get-authors [] link)))
;; gets the feed title
(defn get-feed-title [link]
(first (for [x (get-feed link)
:when (= :title (:tag x))]
(first (:content x)))))
</code></pre>
<p><em>helper.clj</em></p>
<pre><code>(ns rss-feeds-webapp.helper
(:require
[clojure.string :as string]))
;; parses a date string into our desired output format
(defn get-time [date-string]
(.format (java.text.SimpleDateFormat. "dd/MM/yyyy - HH:mm") (new java.util.Date date-string))
)
;; removes all trailing whitespaces and converts the string to lowercase
;; --> needed for accurate comparison
(defn simplify-string [str]
(let [str (or str "")]
(string/lower-case (string/trim str))))
;; takes one string, analyzes it for regex matches of the filterTerm and returns a list with html spans
;; apply list is needed so the lazy sequence gets converted to a list for sequential access
(defn get-highlighted-text-by-key [item filterTerm key]
(let [title []
match (re-matches (re-pattern (str "(?i)(.*)(" filterTerm ")(.*)"))(apply str (get item key)))]
(if match
;; drops the first element of the match vector, since that's the whole string
(let [nested-title (for [substr (drop 1 match)]
(if (= (simplify-string substr) (simplify-string filterTerm))
[:span {:class "highlight"} substr]
[:span substr]
)
)]
(apply list (conj title (apply list nested-title) )))
(apply list (conj title [:span (get item key "No title specified")])))))
;; checks if the option value matches the link parameter and returns true
(defn get-selected-option [value filterTerm]
(if (= value filterTerm) true false))
</code></pre>
<p><em>templating.clj</em></p>
<pre><code>(ns rss-feeds-webapp.templating
(:use
[hiccup.page :only (html5 include-css include-js)]
[hiccup.form :refer :all]
[rss-feeds-webapp.helper :refer :all]
[rss-feeds-webapp.feed :refer :all]
[ring.util.anti-forgery :as util]
)
)
(defn gen-page-head
[title]
[:head
[:title (str title)]
(include-css "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css")
(include-css "/css/styles.css")])
(defn render-item [item filterTerm]
[:div {:class "card"}
;;[:img {:class "card-img-left" :src "..." :alt "Card image cap"}]
[:div {:class "card-body"}
[:h5 (get-highlighted-text-by-key item filterTerm :title)]
[:p {:class "card-text"} (get item :creator "No author specified")]
[:p {:class "card-text"} (get-highlighted-text-by-key item filterTerm :description)]
[:p {:class "card-date"} (get-time (apply str(get item :pubDate "PubDate"))) ]
[:a {:class "btn btn-outline-info" :href (apply str(get item :link)) :target "_blank"} "Read full article"]
]]
)
(defn render-author-options [item filterTerm]
[:option {:value (apply str(get item :creator "No title specified")) :selected (get-selected-option (apply str(get item :creator )) filterTerm )}
(get item :creator "No title specified")]
)
(defn render-authors [content filterTerm]
(for [entry content]
(render-author-options (first entry) filterTerm)))
(defn render-feed [content filterTerm]
(for [entry content]
(render-item (first entry) filterTerm)))
(defn render-category-selection []
[:div {:class "container margin-top-25 no-left-padding"}
[:div {:class "col-md-12 no-left-padding"}
[:h3 "Or select a category"]
[:form {:method "get" :action "/feed" :class "category-form"}
(util/anti-forgery-field)
[:div {:class "col-lg-8 col-sm-12 no-left-padding no-right-padding"}
[:div {:class "input-group"}
[:div {:class "select-wrapper"}
[:select {:class "custom-select form-control no-right-border-radius" :name (str "link")}
[:option {:value "https://www.nytimes.com/services/xml/rss/nyt/World.xml"} "World News"]
[:option {:value "http://feeds.bbci.co.uk/news/world/europe/rss.xml"} "Europe"]
[:option {:value "http://feeds.nytimes.com/nyt/rss/Business"} "Business"]
[:option {:value "http://feeds.bbci.co.uk/news/health/rss.xml"} "Health"]
[:option {:value "http://feeds.nytimes.com/nyt/rss/Technology"} "Technology"]
[:option {:value "http://rss.nytimes.com/services/xml/rss/nyt/Travel.xml"} "Travel"]
[:option {:value "http://feeds.bbci.co.uk/news/education/rss.xml"} "Education & Family"]
[:option {:value "https://www.nytimes.com/services/xml/rss/nyt/Sports.xml"} "Sports"]
[:option {:value "http://feeds.feedburner.com/vagubunt"} "Linux & Webdevelopment"]
[:option {:value "https://www.sitepoint.com/feed/"} "Programming"]
[:option {:value "https://css-tricks.com/feed"} "CSS-Tricks"]
[:option {:value "https://clojureverse.org/posts.rss"} "Clojure"]
]
]
[:span {:class "input-group-btn"}
[:input.action {:type "submit" :class "btn btn-outline-secondary no-left-border-radius" :value "Load selected category"}]]]]]]]
)
(defn render-possible-feeds []
[:div {:class "container no-left-padding" :style "margin-top: 50px"}
[:div {:class "col-md-12 no-left-padding"}
[:h5 "Possible Feeds"]
[:div {:class "col-md-12 no-left-padding"}
[:p "http://feeds.feedburner.com/vagubunt"]
[:p "http://www.spiegel.de/schlagzeilen/tops/index.rss"]
[:p "http://rss.cnn.com/rss/cnn_topstories.rss"]
[:p "http://feeds.bbci.co.uk/news/world/europe/rss.xml"]
[:p "https://www.nytimes.com/services/xml/rss/nyt/HomePage.xml"]
[:p "https://www.nytimes.com/services/xml/rss/nyt/World.xml"]
[:p "http://feeds.nytimes.com/nyt/rss/Technology"]
[:p "http://www.tagesschau.de/xml/rss2"]
[:p "https://spectrum.ieee.org/rss/fulltext"]
]]]
)
(defn body [title & content]
(html5
(gen-page-head title)
[:body
[:div {:class "container" :style "position: relative"}
[:a {:href "/" :title "Go back home"}
[:img {:class "site-logo" :src "http://tiny.cc/rdun3y" :alt "Card image cap"}]]
[:h1 {:class "margin-vertical-20"} title]
content
]]))
;; renders an input group with an input field and an action button to the right
(defn render-input-group [inputPlaceholder, actionText, inputName, inputType]
[:div {:class "input-group"}
[:input {:type inputType :class "form-control" :name inputName :placeholder inputPlaceholder}]
[:span {:class "input-group-btn"}
[:input.action {:type "submit" :class "btn btn-primary no-left-border-radius" :value actionText}]]]
)
;; HTML Page for /
(defn view-input []
(body
"RSS-Feed Viewer"
[:div
[:div {:class "container margin-top-25 no-left-padding"}
[:div {:class "col-md-12 no-left-padding"}
[:h3 "Enter a rss-feed url:"]
[:form {:method "get" :action "/feed"}
(util/anti-forgery-field)
[:div {:class "col-lg-6 no-left-padding no-right-padding"}
(render-input-group "Enter your RSS Url..." "load feed" "link" "url")
]
]
]]
(render-category-selection)
(render-possible-feeds)]
))
;; HTML Page for /view-error
(defn view-error []
(body
"RSS-Feed Viewer"
[:div
[:div {:class "container margin-top-25 no-left-padding"}
[:div {:class "col-md-12 no-left-padding"}
[:h3 {:class "error"} "Ups, something went wrong..."]
]]]
))
;; HTML Page for /feed
(defn view-feed [link, filter, author]
(body
(get-feed-title link)
[:div {:class "container no-left-padding no-right-padding"}
[:form {:method "get" :action "/feed"}
(util/anti-forgery-field)
[:div {:class "col-lg-6 no-left-padding no-right-padding"}
[:div {:class "input-group hidden"}
[:input {:type "url" :class "form-control" :name "link" :placeholder "..." :value link}]
[:span {:class "input-group-btn"}
[:input.action {:type "submit" :class "btn btn-primary no-left-border-radius" :value "Go"}]]]
[:div {:class "input-group"}
[:input {:type "text" :class "form-control" :autofocus true :name "filter" :placeholder "Filter RSS Feeds..." :value filter}]
[:span {:class "input-group-btn"}
[:input.action {:type "submit" :class "btn btn-primary no-left-border-radius" :value "Filter feeds"}]]]
]
[:div {:class "col-lg-8 col-sm-12 no-left-padding no-right-padding"}
[:div {:class "input-group margin-top-25"}
[:div {:class "select-wrapper"}
[:select {:class "custom-select form-control no-right-border-radius" :name (str "author")}
[:option {:value "" :selected (get-selected-option "" author )} "--- choose author ---" ]
(render-authors (get-feed-authors link) author)]
]
[:span {:class "input-group-btn"}
[:input.action {:type "submit" :class "btn btn-outline-secondary no-left-border-radius" :value "Filter authors"}]]]]]
]
(render-feed (get-feed-data link filter author) filter)
))
</code></pre>
| [] | [
{
"body": "<p>This code is quite good for someone learning the language. You haven't made any of the common errors such as using <code>def</code> inside of function instead of <code>let</code>. I don't see anything really outright wrong with the code, so I'll just be commenting on style and things that I think can be improved. I'll just go top to bottom after addressing some things you mentioned.</p>\n\n<hr>\n\n<blockquote>\n <p>. . . we're not quite sure if our code complies with functional programming paradigms.</p>\n</blockquote>\n\n<p>Yes, this code is functional. You aren't needlessly mutating anything by abusing <code>atom</code>s or relying on side-effects. Really, those are major deciding factors.</p>\n\n<hr>\n\n<pre><code>(:use [rss-feeds-webapp.helper :refer :all])\n</code></pre>\n\n<p>Shouldn't be there. That should be tucked inside the <code>:require</code> with everything else. Use of <code>:use</code> is discouraged, as is <code>:refer :all</code> in many cases. Blanket unqualified imports of namespaces aren't ideal. Say you come back to this project a year from now. Are you going to remember what functions come from what modules? Unless the names provide enough context, you may have trouble. Bulk unqualified imports also increase the chance of having a name conflict. Always try to use <code>:as</code>, or <code>:refer [...]</code> when importing. That way you can easily see what code is coming from where, and avoid polluting your namespace.</p>\n\n<hr>\n\n<pre><code>(.getBytes (:body (client/get link)) \"UTF-8\")\n</code></pre>\n\n<p>That would benefit from using a type hint.</p>\n\n<pre><code>; I'm assuming :body is returning a String\n(ByteArrayInputStream. ^String (.getBytes (:body (client/get link)) \"UTF-8\"))\n</code></pre>\n\n<p>Not only does that help a smart IDE like IntelliJ give you better autocomplete suggestions, it also makes your code faster by avoiding reflection. If you run <code>lein check</code>, your call to <code>.getBytes</code> will cause the following warning:</p>\n\n<pre><code>Reflection warning, your-file-here.clj - reference to field getBytes can't be resolved.\n</code></pre>\n\n<p>Avoiding reflection isn't a big deal in this case, but it's a good thing to keep in mind.</p>\n\n<hr>\n\n<p><code>get-content</code> and similar functions make good use of <code>for</code>. I'll just point out though that they can also be written in terms of <code>map</code> and <code>filter</code> as well:</p>\n\n<pre><code>(defn get-content [item tag]\n (->> item\n (filter #(= tag (:tag %)))\n (map #(first (:content %)))))\n\n; Or\n\n(defn get-content [item tag]\n (->> item\n (filter #(= tag (:tag %)))\n (map (comp first :content))))\n</code></pre>\n\n<p>If you already have a <code>->></code> \"pipe\" going, it may prove to be cleaner to use <code>map</code>/<code>filter</code> here instead of <code>for</code>. This is purely a matter of taste though.</p>\n\n<hr>\n\n<pre><code>(defn filter-items-by-term [term author]\n (let [term (or term \"\")]\n (let [author (or author \"\")]\n</code></pre>\n\n<p>contains needless nesting. It can simply be</p>\n\n<pre><code>(defn filter-items-by-term [term author]\n (let [term (or term \"\")\n author (or author \"\")]\n</code></pre>\n\n<hr>\n\n<p>A lot of your code (like in the example immediately above), you're doing something like</p>\n\n<pre><code>(or some-parameter a-default-value)\n</code></pre>\n\n<p>Now, this <em>is</em> a good way of dealing with possibly-<code>nil</code> values. The placement of the check is weird though. Take a look at <code>filter-items-by-term</code>. Why are <code>term</code> and <code>author</code> possibly <code>nil</code>? Because <code>get-feed-data</code> takes optional parameters, and passes the data, unchecked, to <code>filter-items-by-term</code>. This means that part of the implementation of <code>filter-items-by-term</code> (checking for <code>nil</code> values) is needed due to the implementation of <code>get-feed-data</code> (passing potentially <code>nil</code> values). What if you change how one of the functions work and forget to change the other? It also seems needlessly complicated that many of your functions are trying to \"protect themselves\" by assuming that bad data may be handed in. It would be <em>much</em> cleaner to expect that the caller, when possible, checks the data prior to calling. All your functions should expect valid data. If the caller has bad data, it's up to them to fix it. I'd make the following changes:</p>\n\n<pre><code>(defn filter-items-by-term [term author]\n ; Assumes valid data is being passed!\n (fn [[item]]\n\n(defn get-feed-data [link & [filterTerm authorTerm]]\n ; It's now this function's duty to verify its own data\n (filter (filter-items-by-term (or filterTerm \"\")\n (or authorTerm \"\"))\n (get-items [] link)))\n</code></pre>\n\n<p>And similarly for the other cases like this.</p>\n\n<p>I also cleaned up <code>get-feed-data</code>. It had two things that I didn't like:</p>\n\n<ul>\n<li><p>Trailing <code>)</code> on a new line, like you would have a <code>}</code> in Java. This isn't necessary if you're using a good IDE and consistent indentation. It seems like one of you is using this style while the other isn't, since it's inconsistent. Even worse than using an unidiomatic style is applying the style inconsistently. Your teacher will mark you down for inconsistency alone if they're paying attention.</p></li>\n<li><p>Trying to shove a bunch on one line. It's much better to break up long lines for readability. </p></li>\n</ul>\n\n<hr>\n\n<p>Also in that same function, you have the long anonymous function being returned. In it, you repeatedly access <code>item</code> using keys. It might be cleaner to deconstruct <code>item</code> in the parameter list:</p>\n\n<pre><code>(fn [[{:keys [title description creator]}]]\n (and (or\n (string/includes?\n (simplify-string (apply str title))\n (simplify-string term))\n (string/includes?\n (simplify-string (apply str description))\n (simplify-string term)))\n\n (string/includes?\n (simplify-string (apply str creator))\n (simplify-string author))))\n</code></pre>\n\n<p>Also note, <code>(get item :title)</code> can be written simply as <code>(:title item)</code>. Keywords implement <code>IFn</code>:</p>\n\n<pre><code>(ifn? :hello)\n=> true\n</code></pre>\n\n<p>They are usable as functions that return the corresponding element when applied to a map.</p>\n\n<hr>\n\n<p><code>get-feed-data</code> could also make use of <code>partial</code>. You're having the function return another function so you can supply some data ahead of time, then have <code>filter</code> call it with the last bit of data. This is very common, and is the situation that <code>partial</code> was made for. Id make the following changes:</p>\n\n<pre><code>; Note how \"item\" was simply added as a third parameter\n(defn filter-items-by-term [term author {:keys [title description creator]}]\n ; And now a function isn't returned\n (and (or\n (string/includes?\n (simplify-string (apply str title))\n (simplify-string term))\n (string/includes?\n (simplify-string (apply str description))\n (simplify-string term)))\n\n (string/includes?\n (simplify-string (apply str creator))\n (simplify-string author))))\n</code></pre>\n\n<p>And now:</p>\n\n<pre><code>(defn get-feed-data [link & [filterTerm authorTerm]]\n ; Partially apply \"filterTerm\" and \"autherTerm\" to \"filter-items-by-term\"\n (filter (partial filter-items-by-term filterTerm authorTerm) \n (get-items [] link)))\n</code></pre>\n\n<p>or, just manually wrap it in another function (<code>#()</code> here):</p>\n\n<pre><code>(defn get-feed-data [link & [filterTerm authorTerm]]\n (filter #(filter-items-by-term filterTerm authorTerm %)\n (get-items [] link)))\n</code></pre>\n\n<p><code>partial</code> may seem complicated at first, but this example should make it clearer:</p>\n\n<pre><code>(let [add-five (partial + 5)]\n (println (add-five 5) (add-five 20)))\n\n10 25\n</code></pre>\n\n<p>It returns a function that expects the rest of the arguments. This is useful when you have some data right now, and want to call the function with some other data later.</p>\n\n<p>Why would I make this change? Why should <code>filter-items-by-term</code> care about how it's being used? Why should it need to know that the caller needs to supply some of the data later? It shouldn't.</p>\n\n<hr>\n\n<p>Speaking of long lines, I'd break up the <code>get-time</code> body:</p>\n\n<pre><code>(defn get-time [date-string]\n (.format (java.text.SimpleDateFormat. \"dd/MM/yyyy - HH:mm\") \n (new java.util.Date date-string)))\n</code></pre>\n\n<p>Align everything properly based on indentation (like you would in Python), and <a href=\"https://shaunlebron.github.io/parinfer/\" rel=\"nofollow noreferrer\">Par-infer</a> (Parenthesis Inference) can automatically handle closing braces for you. I <em>never</em> manually add <code>)</code>s when writing Clojure. IntelliJ's <a href=\"https://cursive-ide.com/\" rel=\"nofollow noreferrer\">Cursive</a> plugin (both free) includes Par-Infer which infers where they should be and adds them for me. I highly recommend this set-up if you plan on writing Clojure.</p>\n\n<hr>\n\n<p><code>get-selected-option</code> is redundant and has a confusing name. It isn't actually \"getting\" anything, it's a predicate. It also doesn't make sense to write <code>(if pred? true false)</code>. The predicate already returns <code>true</code> or <code>false</code> (or at least a truthy/falsey value), so the <code>if</code> here isn't needed. I'd change it to:</p>\n\n<pre><code>(defn is-filter-term? [value filterTerm]\n (= value filterTerm))\n</code></pre>\n\n<p>Although it could be argued that this function is so simple that it should just be inlined. It's pretty clear what a simple call to <code>=</code> is checking.</p>\n\n<hr>\n\n<p>For <code>render-authors</code> and the function below it, I'd just use <code>map</code> here. Especially since you don't need any filtering or use of <code>:let</code>, <code>map</code> would likely be cleaner:</p>\n\n<pre><code>(defn render-authors [content filterTerm]\n (map #(render-author-options (first %) filterTerm) \n content))\n</code></pre>\n\n<p>But again, this a matter of taste. I will say though, if you have a iterable collection like <code>content</code>, it's a good idea to match Clojure convention and have it as the last parameter of the function. That way, you can do something like:</p>\n\n<pre><code>(->> content\n (map some-transformation)\n (render-authors some-filter-term) ; Wouldn't be possible with your current order\n (filter some-predicate))\n</code></pre>\n\n<p>Threading macros (<code>-></code> and <code>->></code> mainly) are pretty common, and writing functions that work well with them will make your life easier. You didn't use and threading macros in your code, but I also don't see any good opportunities to use them either. I'd practice using them if you intend to keep writing Clojure, as they're exceedingly helpful.</p>\n\n<hr>\n\n<p>In <code>get-highlighted-text-by-key</code>, there's a few notable things.</p>\n\n<p>One, I'm not sure <code>title</code> is necessary here. It's needed in two places, and neither of those places seem to even need it. Unless my brain is just fried, <code>(conj title (apply list nested-title))</code> is just conjoining <code>(apply list nested-title)</code> to an empty vector, which will just result in a single element vector. It would make more sense to just write:</p>\n\n<pre><code>(vector (apply list nested-title))\n</code></pre>\n\n<p>I also don't understand why you then wrap that in a <code>(apply list</code>, which just converts it to a list. You convert <code>nested-title</code> to a list with the first <code>(apply list</code>, then wrap it in a vector with <code>(conj []</code>, then convert the vector to a list with a second <code>(apply list</code> I'm not sure what you're trying to do here. It looks like that entire line could be reduced to just:</p>\n\n<pre><code>(list (apply list nested-title))\n</code></pre>\n\n<p>Although, I'll note that that plain lists aren't used very often unless you're writing macros. Lists are simple linked lists, so they can't do <code>O(1)</code> lookups by index. Use vectors in the vast majority of cases unless you have good reason to use something else (like you're writing a macro). Simply returning the lazy list that <code>for</code> evaluates to would likely be fine here. The caller can force the result if they want to.</p>\n\n<p>Second,</p>\n\n<pre><code>(let [match (re-matches (re-pattern (str \"(?i)(.*)(\" filterTerm \")(.*)\"))(apply str (get item key)))]\n (if match\n</code></pre>\n\n<p>(Besides being <em>way</em> too long of a line) is a perfect case to make use of <code>if-let</code>:</p>\n\n<pre><code>(if-let [match (re-matches (re-pattern (str \"(?i)(.*)(\" filterTerm \")(.*)\"))(apply str (get item key)))]\n (... If truthy, do this, using \"match\" ...)\n (... If falsey, do this, without having access to \"match\")\n</code></pre>\n\n<p><code>if-let</code> checks if the bound variable is truthy. If it is, it executes the first body <em>with the truthy binding in scope</em>. If it's falsey, it executes the second body, <em>without the binding in scope</em>.</p>\n\n<hr>\n\n<hr>\n\n<p>I think that's all the major things I can find. Good luck. Hopefully this was helpful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T23:26:15.013",
"Id": "214735",
"ParentId": "214726",
"Score": "1"
}
},
{
"body": "<p>Thanks a lot for the thorough explanation and analysis!</p>\n\n<p>I tried your suggestion for updating the 'get-highlighted-text-by-key' method, unfortunately, it didn't work right away though. I managed to make it work like so:</p>\n\n<pre><code>(defn get-highlighted-text-by-key [item filterTerm key]\n (if-let [match (re-matches (re-pattern (str \"(?i)(.*)(\" filterTerm \")(.*)\"))\n (apply str (get item key)))]\n ;; drops the first element of the match vector, since that's the whole string\n (let [nested-title (for [substr (drop 1 match)]\n (if (= (simplify-string substr) (simplify-string filterTerm))\n [:span {:class \"highlight\"} substr]\n [:span substr]\n )\n )]\n nested-title)\n [:span (get item key \"No title specified\")]))\n</code></pre>\n\n<p>This is also way simpler and makes more sense. When I wrote the method I had the feeling that something is off, but I couldn't quite wrap my head around it. So thanks for clearing that up!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T20:42:47.977",
"Id": "415401",
"Score": "0",
"body": "No problem. Glad to help. Note though, I'm not sure that this should be an answer. It might get flagged."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T20:43:52.753",
"Id": "415402",
"Score": "0",
"body": "Yes, I tried posting as a comment, but I didn't manage to make it work for the code though :/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T20:35:33.793",
"Id": "214791",
"ParentId": "214726",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T21:18:58.650",
"Id": "214726",
"Score": "4",
"Tags": [
"functional-programming",
"homework",
"clojure",
"rss"
],
"Title": "RSS feed viewer in Clojure"
} | 214726 |
<p>I'm working on a stack implementation using a linked list, but I have a strong feeling that I overcomplicated my solution. I would appreciate it if you review this code and give me any suggestions on code and style.</p>
<pre><code>#pragma once
#include <functional>
#include <iostream>
#include <type_traits>
#include <stdexcept>
template <typename T>
class StackList
{
private:
class Node
{
T data;
Node * next;
Node(Node * next, const T & data) :next(next), data(data) {};
friend class StackList<T>;
};
int size_ = 0;
Node * head_ = nullptr;
Node * tail_ = nullptr;
void AddToTail(T& data);
public:
StackList() = default;
StackList(StackList & other);
StackList(StackList && other);
StackList & operator=(StackList & other);
StackList & operator=(StackList && other);
~StackList() { EmptyList(); }
void EmptyList();
void push(const T & data);
T pop();
const T& operator[](int count) const;
T& operator[](int count) { return const_cast<T &>(static_cast<const StackList &>(*this).operator[](count)); };
int size() { return size_; }
void Traverse(std::function<void(T&)> lamda) const;
void Traverse(std::function<void(T&)> lamda){ (static_cast<const StackList &>(*this).Traverse(lamda)); }
template <typename T>
friend std::ostream & operator<<(std::ostream & os, StackList<T> & stack);
};
template <typename T>
void StackList<T>::AddToTail(T& data)
{
if (head_ == nullptr)
head_ = tail_ = new Node(nullptr, data);
else
{
tail_->next = new Node(nullptr, data);
tail_ = tail_->next;
}
}
template <typename T>
StackList<T>::StackList(StackList & other)
{
std::function<void(T&)> lamda = [&](T& data) {this->AddToTail(data); this->size_++; };
other.Traverse(lamda);
}
template <typename T>
StackList<T>::StackList(StackList && other) : head_(other.head_), tail_(other.tail_), size_(other.size_)
{
other.head_ = 0;
other.tail_ = 0;
other.size_ = 0;
}
template <typename T>
StackList<T> & StackList<T>::operator=(StackList<T> & other)
{
if (this != &other)
{
if (other.size_ == 0)
EmptyList();
else
{
if (size_ >= other.size_)
{
Node * current = head_;
std::function<void(T&)> lamda = [&](T& data) {current->data = data; tail_ = current; current = current->next; };
other.Traverse(lamda);
while (current != nullptr)
{
Node * save = current->next;
delete current;
current = save;
}
}
else
{
Node * current = other.head_;
std::function<void(T&)> lamda = [&](T& data) {data = current->data; current = current->next; };
Traverse(lamda);
while (current != nullptr)
{
AddToTail(current->data);
current = current->next;
}
}
tail_->next = nullptr;
size_ = other.size_;
}
}
return *this;
}
template <typename T>
StackList<T> & StackList<T>::operator=(StackList<T> && other)
{
if (this != &other)
{
head_ = other.head_;
tail_ = other.tail_;
size_ = other.size_;
other.head_ = 0;
other.tail_ = 0;
other.size_ = 0;
}
return *this;
}
template <typename T>
const T& StackList<T>::operator[](int count) const
{
if (count > size_ - 1 && count < 0)
throw std::invalid_argument("Out of range index!");
Node * search = head_;
for (int i = 0; i < count; i++)
search = search->next;
return search->data;
}
template <typename T>
void StackList<T>::EmptyList()
{
while (head_ != nullptr)
pop();
}
template <typename T>
void StackList<T>::push(const T & data)
{
head_ = new Node(head_, data);
if (tail_ == nullptr)
tail_ = head_;
size_++;
}
template <typename T>
T StackList<T>::pop()
{
if (size_ > 0)
{
T retval = head_->data;
Node * temp = head_->next;
delete head_;
head_ = temp;
size_--;
if (size_ == 0)
head_ = tail_ = nullptr;
return retval;
}
else
{
throw std::invalid_argument("Pop of empty list");
}
}
template <typename T>
void StackList<T>::Traverse(std::function<void(T&)> lamda) const
{
Node * cur = head_;
while (cur != nullptr)
{
lamda(cur->data);
cur = cur->next;
}
}
template <typename T>
std::ostream & operator<<(std::ostream & os, StackList<T> & stack)
{
std::function<void(T&)> lamda = [&](T& data) { os << data << std::endl; };
std::ios_base::fmtflags f(os.flags());
os << "Stack of " << typeid(T).name() << ", size = " << stack.size() << std::endl;
stack.Traverse(lamda);
os.flags(f);
return os;
}
</code></pre>
| [] | [
{
"body": "<p>Stack only needs to implement <code>push</code>, <code>pop</code>, <code>top</code>, <code>empty</code>.\nAdditionally you can have copy, assignment, <code>swap</code>, <code>clear</code> and serialization routines to make your class user-friendly.</p>\n\n<p>Comments about this implementation:</p>\n\n<ul>\n<li><p>Recommend separate files (H & CPP) for class definition and implementation. May even want to go to lengths to have a Stack interface (in C++ this can be done via class with only public pure virtual function and virtual no-op destructor). This StackList would be an implementation/child of the Stack.</p></li>\n<li><p>You don't need both <code>head_</code> and <code>tail_</code>, only one is sufficient for FIFO/Stack API implementation</p></li>\n<li><p>Copy Constructor function signature is incorrect, it needs to be <code>StackList(const StackList & other)</code>, it is incorrect to be able to modify the input during copy via lvalue-ref.</p></li>\n<li><p>Recommend following Copy-Swap idiom to implement <code>operator=</code>. You may even be able to get away with not needing to create 2 overloads one for lvalue-reference and one for rvalue-reference, use an object copy instead.</p></li>\n<li><p>Do not create <code>operator[]</code> as it is not needed for Stack. Its run-time complexity is linear, so no need to add a slow unnecessary public method.</p></li>\n<li><p><code>Traverse</code> doesn't need to be public on the <code>StackList</code> class</p></li>\n<li><p>Recommend having const reference of StackList in <code>operator<<(std::ostream & os, const StackList<T> & stack)</code> as it doesn't need to modify the stack.</p></li>\n<li><p>Follow <code>std</code> data structure API convention:</p>\n\n<ul>\n<li>Naming: Recommend changing the name of <code>EmptyList</code> to <code>clear</code></li>\n<li>Adding an <code>empty</code> member function. This can be achieved via <code>0 == size()</code>, but prefer to have an explicit <code>empty</code> to ease Stack usage</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T09:00:07.397",
"Id": "415278",
"Score": "0",
"body": "What would go into the implementation file, given that the entire class is a template type?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T03:54:52.380",
"Id": "214745",
"ParentId": "214733",
"Score": "3"
}
},
{
"body": "<p>I'd recommend putting a blank line after your <code>#pragma once</code>, and again after your <code>#include</code>s, just for readability.</p>\n\n<p>Nit on the naming: When I (a speaker of English, which is an adjective-noun language) see <code>StackList</code>, I think \"a list of stacks\" or possibly \"a list implemented in terms of a stack,\" which in fact is the exact opposite of what you have here. What you have here is a <code>ListStack</code> — a stack implemented in terms of a linked list.</p>\n\n<hr>\n\n<pre><code>StackList() = default;\nStackList(StackList & other);\nStackList(StackList && other);\nStackList & operator=(StackList & other);\nStackList & operator=(StackList && other);\n~StackList() { EmptyList(); }\n</code></pre>\n\n<p>First of all, personally I'd recommend defining all these functions in-line right here, rather than making me scroll down to find their definitions later in the same file.</p>\n\n<p>Another naming nit: if a <code>StackList</code> is a List implemented as a Stack, then surely an <code>EmptyList</code> should be a List that's always Empty! As @Chintan pointed out, what you actually have here is traditionally named <code>this->clear()</code>. \"Empty\" is a particularly bad name because it can be read as a verb or as an adjective, and actually C++ uses the adjective reading: <code>vec.empty()</code> asks \"Is this vector empty?\", not \"Please make this vector empty.\" (This was a large part of the motivation for C++17's <code>[[nodiscard]]</code> attribute.)</p>\n\n<p>The biggest problem here, though, is that you got the copy constructor's signature wrong!</p>\n\n<pre><code>StackList(StackList & other);\nStackList(StackList && other);\nStackList & operator=(StackList & other);\nStackList & operator=(StackList && other);\n</code></pre>\n\n<p>should read</p>\n\n<pre><code>StackList(const StackList& other);\nStackList(StackList&& other) noexcept;\nStackList& operator=(const StackList& other);\nStackList& operator=(StackList&& other) noexcept;\n</code></pre>\n\n<p>The <code>const</code> is very important! Without it, you wouldn't be able to make a copy of a list that you had <a href=\"https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/\" rel=\"nofollow noreferrer\">promised never to modify</a>.</p>\n\n<pre><code>void foo(const StackList& lst) {\n auto lst2 = lst; // this line fails to compile\n}\n</code></pre>\n\n<hr>\n\n<pre><code>const T& operator[](int count) const; \nT& operator[](int count) { return const_cast<T &>(static_cast<const StackList &>(*this).operator[](count)); };\n</code></pre>\n\n<p>Note that it's \"un-C++-ish\" to provide such a concise spelling for an O(n) operation.\nAlso, I think it would be more natural to use <code>const_cast</code> rather than <code>static_cast</code> here, since all you're doing (and all you're trying to do) is add a <code>const</code> qualifier.</p>\n\n<hr>\n\n<pre><code>template <typename T>\nfriend std::ostream & operator<<(std::ostream & os, StackList<T> & stack);\n</code></pre>\n\n<p>You should <em>definitely</em> move this operator in-line, so that you don't have to make it a template.\nAdditionally, what you have here is actually invalid because you're trying to redefine the name <code>T</code>, which already has a meaning — it's the template type parameter to <code>StackList</code>. So what I would write is:</p>\n\n<pre><code>friend std::ostream& operator<<(std::ostream& os, const StackList& stack) {\n std::ostream os2(os.rdbuf());\n os2 << \"Stack of \" << typeid(T).name() << \", size = \" << stack.size() << std::endl;\n stack.Traverse([&](T& data) {\n os2 << data << std::endl;\n });\n return os;\n}\n</code></pre>\n\n<p>Note that I've made a few more changes; for example, rather than imperatively fiddle with the <code>flags</code> of the given ostream, I'd just create my own ostream. That way, the user couldn't mess up my output:</p>\n\n<pre><code>StackList<int> lst;\nlst.push(100);\nstd::cout << std::hex << lst << std::endl;\n</code></pre>\n\n<p>With your code, this prints <code>64</code>; with my code, this prints <code>100</code>.</p>\n\n<p>Also, \"<a href=\"https://accu.org/index.php/journals/2619\" rel=\"nofollow noreferrer\">don't use <code>endl</code></a>\" applies here.</p>\n\n<hr>\n\n<p>Your code repeatedly uses the identifier <code>lamda</code> [sic] to refer to a variable of type <code>std::function</code>. That's not correct. I actually think you should get rid of all the <code>std::function</code>s in your code and just <em>use</em> lambdas, actually. (That's \"lambdas\" with a \"b\".) So for example, you have:</p>\n\n<pre><code>void Traverse(std::function<void(T&)> lamda) const;\nvoid Traverse(std::function<void(T&)> lamda){ (static_cast<const StackList &>(*this).Traverse(lamda)); }\n\ntemplate <typename T>\nvoid StackList<T>::Traverse(std::function<void(T&)> lamda) const\n{\n Node * cur = head_;\n while (cur != nullptr)\n {\n lamda(cur->data);\n cur = cur->next;\n }\n}\n</code></pre>\n\n<p>Actually there's a problem even before we get to the lambdas! You seem to have added the non-const overload of <code>Traverse</code> on autopilot. It doesn't do what you want <em>at all</em>. Remove it, and re-add it when you have a need for it.</p>\n\n<p>Speaking of untested code, you should be compiling with <code>-W -Wall</code> and probably <code>-Wextra</code>, and fixing all the bugs that the compiler tells you about. That would catch things like</p>\n\n<pre><code>warning: field 'next' will be initialized after field 'data' [-Wreorder]\n Node(Node * next, const T & data) :next(next), data(data) {};\n ^\n</code></pre>\n\n<p>Every bug caught by the compiler is a bug you don't have to catch!\nAnd every bug caught by <em>a unit test</em> is a bug you don't have to catch, too. Write some tests for your code (such as <code>Traverse</code>). You'll find plenty of bugs.</p>\n\n<p>Okay, so, here's how I would write <code>Traverse</code>:</p>\n\n<pre><code>template<class F>\nvoid Traverse(const F& visit) {\n for (Node *cur = head_; cur != nullptr; cur = cur->next) {\n visit(cur->data);\n }\n}\n</code></pre>\n\n<p>This is a better API than the <code>std::function</code>-based API you wrote, because with this API, I'm not forcing my caller to wrap their lambda into a <code>std::function</code>. This saves a lot of compile time, and saves a dynamic allocation at runtime, but perhaps most importantly, it allows the caller to pass in <em>non-copyable</em> lambdas such as</p>\n\n<pre><code>StackList<int> lst;\nlst.Traverse([ptr = std::make_unique<int>(42)](int& data) {\n data += *ptr;\n});\n</code></pre>\n\n<hr>\n\n<p>Consider why <code>AddToTail</code> doesn't <code>++size_</code>, and whether perhaps it should.</p>\n\n<hr>\n\n<p>Your copy-assignment operator seems much too complicated. (And is missing a pair of braces around the body of the first <code>if</code>.) I think I'd expect to see something about this long, lines-of-code-wise:</p>\n\n<pre><code>StackList& operator=(const StackList& rhs) {\n if (this != &rhs) {\n Node **src = &rhs.head_;\n Node **dst = &head_;\n while (*src != nullptr && *dst != nullptr) {\n (*dst)->data = (*src)->data;\n src = &(*src)->next;\n dst = &(*dst)->next;\n }\n while (*src != nullptr) {\n *dst = new Node(nullptr, (*src)->data);\n dst = &(*dst)->next;\n src = &(*src)->next;\n }\n while (*dst != nullptr) {\n Node *temp = (*dst)->next;\n delete *dst;\n *dst = temp;\n }\n // updating tail_ is left as an exercise for the reader\n }\n return *this;\n}\n</code></pre>\n\n<p>You might compare your implementation to <code>std::list</code>, and think about whether it's possible to take that <code>while (*dst != nullptr)</code> loop and factor it out into a member function named <code>erase</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T05:03:17.730",
"Id": "214746",
"ParentId": "214733",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T22:19:19.380",
"Id": "214733",
"Score": "5",
"Tags": [
"c++",
"linked-list",
"stack"
],
"Title": "Stack template using linked list"
} | 214733 |
<p>I'm doing the exercices from <a href="https://clojurecademy.com/" rel="nofollow noreferrer">clojureacademy</a>.
Here are the instructions for this one.</p>
<blockquote>
<p>Bob is a lackadaisical teenager. In conversation, his responses are very limited.</p>
<ul>
<li>Returns "Whatever." if given phrase is one of the following inputs:
<ul>
<li>"Tom-ay-to, tom-aaaah-to."</li>
<li>"Let's go make out behind the gym!"</li>
<li>"It's OK if you don't want to go to the DMV."</li>
<li>"Ending with ? means a question."</li>
<li>"1, 2, 3"</li>
</ul></li>
<li><p>Returns "Woah, chill out!" if given phrase is one of the following inputs:</p>
<ul>
<li>"WATCH OUT!"</li>
<li>"WHAT THE HELL WERE YOU THINKING?"</li>
<li>"ZOMG THE %^<em>@#$(</em>^ ZOMBIES ARE COMING!!11!!1!"</li>
<li>"1, 2, 3 GO!"</li>
<li>"I HATE YOU"</li>
</ul></li>
<li><p>Returns "Sure." if given phrase is one of the following inputs:</p>
<ul>
<li>"Does this cryogenic chamber make me look fat?"</li>
<li>"4?"</li>
</ul></li>
<li>Returns "Fine. Be that way!" if given phrase is one of the following inputs:
<ul>
<li>""</li>
<li>" "</li>
</ul></li>
</ul>
</blockquote>
<p>Here is my code in <code>src/ex1_bob/core.clj</code>:</p>
<pre><code>(ns ex1-bob.core
(:gen-class))
; responses
; =======================
(def whatever "Whatever.")
(def chill-out "Woah, chill out!")
(def sure "Sure.")
(def fine "Fine. Be that way!")
; triggers
; =======================
(def sure-triggers
["Does this cryogenic chamber make me look fat?" "4?"])
(def whatever-triggers
["Tom-ay-to, tom-aaaah-to."
"Let's go make out behind the gym!"
"It's OK if you don't want to go to the DMV."
"Ending with ? means a question."
"1, 2, 3"])
(def chill-out-triggers
["WATCH OUT!"
"WHAT THE HELL WERE YOU THINKING?"
"ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!"
"1, 2, 3 GO!"
"I HATE YOU"])
(defn has-phrase
"return `true` if the given phrase is found in the collection, `false` otherwise"
[phrase coll]
(if (some #(= phrase %) coll)
true
false))
(defn response-for
"return `true` if the given phrase is found in the collection, `false` otherwise"
[phrase]
(cond
(has-phrase phrase whatever-triggers) whatever
(has-phrase phrase chill-out-triggers) chill-out
(has-phrase phrase sure-triggers) sure
(= (clojure.string/trim phrase) "") fine))
</code></pre>
<p>I also wrote some tests in <code>test/ex1_bob/core_test.clj</code>:</p>
<pre><code>(ns ex1-bob.core-test
(:require [clojure.test :refer :all]
[ex1-bob.core :refer :all]))
; This does not work because `is` is a macro, and it seems it does not like to
; be used in a `map` or with `comp`.
;
; (deftest non-working-response-for-chill-out-triggers
; (doall (map (comp is #(= % chill-out) response-for) chill-out-triggers)))
(deftest response-for-chill-out-triggers
(is (every? #(= % chill-out) (map response-for chill-out-triggers))))
(deftest response-for-whatever-triggers
(is (every? #(= % whatever) (map response-for whatever-triggers))))
(deftest response-for-sure-triggers
(is (every? #(= % sure) (map response-for sure-triggers))))
(deftest response-for-empty-string
(is (every? #(= % fine) (map response-for [""]))))
</code></pre>
<p>Two things make me a bit unhappy about this code:</p>
<ul>
<li>the <code>has-phrase</code> function seems a bit silly. Do I really have to write a function to return <code>true</code>/<code>false</code> if an element is found in a collection? I feel that there must be a function that does this already</li>
<li><p>I first wrote my unit test with:</p>
<pre><code>(deftest non-working-response-for-chill-out-triggers
(doall (map (comp is #(= % chill-out) response-for) chill-out-triggers)))
</code></pre>
<p>The idea is to have one assertion for each item, which I assumed would give me a better error message in case of a failure (because I know which item failed). But it seems that <code>is</code> is a macro and somehow, the interpreter doesn't like this.</p></li>
</ul>
| [] | [
{
"body": "<p>First, working top-down, your triggers at the top should be in sets (<code>#{}</code>), not vectors (you'll see why a little farther down):</p>\n\n<pre><code>(def sure-triggers\n #{\"Does this cryogenic chamber make me look fat?\"\n \"4?\"})\n\n(def whatever-triggers\n #{\"Tom-ay-to, tom-aaaah-to.\"\n \"Let's go make out behind the gym!\"\n \"It's OK if you don't want to go to the DMV.\"\n \"Ending with ? means a question.\"\n \"1, 2, 3\"})\n\n(def chill-out-triggers\n #{\"WATCH OUT!\"\n \"WHAT THE HELL WERE YOU THINKING?\"\n \"ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!\"\n \"1, 2, 3 GO!\"\n \"I HATE YOU\"})\n</code></pre>\n\n<hr>\n\n<p><code>has-phrase</code> has a couple things that can be improved:</p>\n\n<ul>\n<li><p>Clojure ends predicates with a <code>?</code> by convention. I'd rename it to <code>has-phrase?</code>.</p></li>\n<li><p><code>some</code> already returns a truthy/falsey value. <code>(if pred? true false)</code> is unnecessary.</p></li>\n</ul>\n\n<p>Just reduce it to:</p>\n\n<pre><code>(defn has-phrase?\n \"Return whether or not the given phrase is found in the collection\"\n [phrase coll]\n (some #(= phrase %) coll))\n</code></pre>\n\n<p>BUT, now that you're using sets instead of vectors, this whole function is unnecessary:</p>\n\n<pre><code>(whatever-triggers \"1, 2, 3\")\n=> \"1, 2, 3\" ; Truthy\n\n(whatever-triggers \"Not in the set\")\n=> nil\n</code></pre>\n\n<p>Sets themselves can be used as functions. If the item is in the set, they return the item back (a truthy result), else they return <code>nil</code> (falsey). This will also be much faster, since now you don't need to have <code>some</code> iterate potentially the entire vector (although obviously speed isn't a factor here). This changes <code>reponse-for</code> to:</p>\n\n<pre><code>(defn response-for\n \"return `true` if the given phrase is found in the collection, `false` otherwise\"\n [phrase]\n (cond\n (whatever-triggers phrase) whatever\n (chill-out-triggers phrase) chill-out\n (sure-triggers phrase) sure\n (= (clojure.string/trim phrase) \"\") fine))\n</code></pre>\n\n<hr>\n\n<p>This could be changed using some <code>some</code> trickery. <code>some</code> returns the first truthy value returned by its predicate. If you pass it pairs of <code>[trigger-set response]</code>, you can iterate over the the pairs to find the first one that satisfies it, then return the response:</p>\n\n<pre><code>(defn response-for2 [phrase]\n (some (fn [[trigger-set response]]\n (when (trigger-set phrase)\n response))\n\n [[sure-triggers sure]\n [chill-out-triggers chill-out]\n [whatever-triggers whatever]\n [#{\"\" \" \"} fine]]))\n</code></pre>\n\n<p>Now, in this particular example, I wouldn't recommend doing this. It's not as clear as what you already had. I have used <code>(some #(when ...))</code> before though, and it works great in some cases. I just thought I'd show you it here in case you run into a similar problem where this can be applied.</p>\n\n<p>I'm sure something could be done using a map mapping triggers to responses, but I just did another Clojure review, and my brain's tapped out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T13:00:22.483",
"Id": "415302",
"Score": "0",
"body": "Thank you for the thorough review, I learnt a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T01:24:22.770",
"Id": "214740",
"ParentId": "214734",
"Score": "2"
}
},
{
"body": "<p>For some reason I can't open the link to the question site. But \"Returns [X] if given phrase is one of the following inputs\", to me, does not mean it only returns that for that inputs.\nIt also doesn't say you should return <code>nil</code> otherwise.</p>\n\n<p>If we take the listed inputs to be test cases; then baking them in the implementation is not good.</p>\n\n<p>I understand the cases to be as such:\n- blank (nothing but whitespace)\n- question (ends with <code>\\?</code>, as hinted in example)\n- shouting (all letters are uppercase)\n- anyhing else</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T12:59:22.467",
"Id": "415301",
"Score": "0",
"body": "Oh I had not thought about that. Now that you say it, it seems kind of obvious that this is probably the right thing to do..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T11:03:59.070",
"Id": "214756",
"ParentId": "214734",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214740",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T23:16:29.800",
"Id": "214734",
"Score": "3",
"Tags": [
"beginner",
"clojure"
],
"Title": "What does the Bob say? (clojure version)"
} | 214734 |
<p>Given a string of size 9 that represents a tic tac toe board, determine if X or O has won, or if the board is in an invalid state. Any other character aside from <code>x</code>, <code>X</code>, <code>o</code>, <code>O</code> represents an empty spot on the board.</p>
<pre><code>Input: 012345678
Board:
0 1 2
3 4 5
6 7 8
</code></pre>
<h2>TicTacToe.cpp</h2>
<pre class="lang-cpp prettyprint-override"><code>#include "tictactoe.h"
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
using std::string;
using std::vector;
const int kBoardSize = 9;
const int kBoardLength = std::sqrt(kBoardSize);
TicTacToeState CheckTicTacToeBoard(std::string board) {
if (board.size() != kBoardSize) {
return TicTacToeState::InvalidInput;
}
std::transform(board.begin(), board.end(), board.begin(), ::tolower);
size_t numberOfO = std::count(board.begin(), board.end(), 'o');
size_t numberOfX = std::count(board.begin(), board.end(), 'x');
if (numberOfO > numberOfX || numberOfX > numberOfO + 1) {
return TicTacToeState::UnreachableState;
}
bool xWon = winDetection(board, 'x');
bool oWon = winDetection(board, 'o');
if (xWon && oWon) {
return TicTacToeState::UnreachableState;
} else if (xWon) {
return TicTacToeState::Xwins;
} else if (oWon) {
return TicTacToeState::Owins;
}
return TicTacToeState::NoWinner;
}
bool winDetection(string board, char marker) {
bool rowWin = false, colWin = false, rightDiagWin = true, leftDiagWin = true;
for (int i{0}, rightDiagIndex{0}, leftDiagIndex{kBoardLength - 1};
i < kBoardLength; ++i, rightDiagIndex += (kBoardLength + 1),
leftDiagIndex += (kBoardLength - 1)) {
bool row = true, col = true;
int rowIndex = kBoardLength * i, colIndex = i;
for (int j{0}; j < kBoardLength; ++j) {
col &= (board[colIndex] == marker);
row &= (board[rowIndex] == marker);
rowIndex++;
colIndex += kBoardLength;
}
colWin |= col;
rowWin |= row;
rightDiagWin &= board[rightDiagIndex] == marker;
leftDiagWin &= board[leftDiagIndex] == marker;
}
return (rowWin || colWin || rightDiagWin || leftDiagWin);
}
</code></pre>
<h2>TicTacToe.h</h2>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <string>
enum TicTacToeState { UnreachableState, Xwins, Owins, NoWinner, InvalidInput };
TicTacToeState CheckTicTacToeBoard(std::string board);
bool winDetection(std::string board, char marker);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T10:40:30.323",
"Id": "415289",
"Score": "0",
"body": "event if the underlying representation of a board is a string, you shouldn't be using that directly every where."
}
] | [
{
"body": "<ol>\n<li><p>Computing a square-root is unnecessary; further, it only works when <code>kBoardSize</code> is a perfect square. Prefer</p>\n\n<pre><code>const int kBoardLength = 3;\nconst int kBoardSize = kBoardLength * kBoardLength;\n</code></pre></li>\n<li><p>Your test for unreachability is not complete. You verify that O has made no more moves than X, but you really need to check that the winner made the last move. If X won, then should have <code>numberOfX = numberOfO + 1</code>; if O won then should have <code>numberOfO = numberOfX</code>. It should be clear how to add these checks to your <code>CheckTicTacToeBoard</code> method.</p></li>\n<li><p>A more overarching tension in this code is: should the board size really be a constant? The code is written so abstractly as to support any board size. But then the board size is fixed to a constant. I would choose one of the following directions to proceed in:</p>\n\n<ul>\n<li>Commit to a board size of 9. In this case, I would recommend hard-coding the win conditions in <code>winDetection</code>. There are only 8 ways to win, so the resulting code would be a lot cleaner.</li>\n<li><p>Allow arbitrary board sizes. In this case, you should accept a <code>boardLength</code> argument. Further, you will have to refine the notion of an <code>UnreachableState</code>. For example, in 5-by-5 tic tac toe, the following state is unreachable, your code would return <code>Xwins</code>:</p>\n\n<pre><code>x x x x x\no . o . o\nx x x x x\no . o . o\no o x o o\n</code></pre></li>\n</ul></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T02:12:05.153",
"Id": "214741",
"ParentId": "214737",
"Score": "5"
}
},
{
"body": "<p>Adding to the review of <a href=\"https://codereview.stackexchange.com/a/214741/40063\">Benjamin Kuykendall</a>, pay attention especially to const correctness to protect from unintended errors and to possible allow the compiler to optimize better.</p>\n\n<ul>\n<li><p>For <code>winDetection</code>, pass the board by const-ref. I see you didn't do this for <code>CheckTicTacToeBoard</code> because the function modifies the input by converting to lowercase.</p></li>\n<li><p>In <code>CheckTicTacToeBoard</code>, make <code>numberOfO</code> and <code>numberOfX</code> const. Similarly, make <code>xWon</code> and <code>oWon</code> const.</p></li>\n<li><p>In <code>winDetection</code>, since we are writing C++ and not C, there is no reason to declare variables at the beginning of the scope of the function unless they are not needed. In particular, <code>rightDiagWin</code> and <code>leftDiagWin</code> should be declared just before returning, and you can also make both of them const as well.</p></li>\n<li><p>In e.g., your for-loop, you use preincrement for the loop variable <code>i</code>, but inside the loop you do postincrement as <code>rowIndex++</code>. Prefer to always use the preincrement since it is not returning a copy of the variable (though I believe this should always be optimized away by the compiler if it's not needed, but it doesn't hurt to be safe).</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T09:02:11.047",
"Id": "214751",
"ParentId": "214737",
"Score": "4"
}
},
{
"body": "<p>Over all, it's not bad. Here are some things that may help you improve your program.</p>\n\n<h2>Use const references where practical</h2>\n\n<p>The <code>board</code> arguments for both the <code>CheckTicTacToeBoard()</code> and <code>winDetection()</code> functions could both actually be <code>const std::string&</code> instead of <code>std::string</code> with a small change to the code shown below.</p>\n\n<h2>Make a single pass through the data where practical</h2>\n\n<p>The current code makes three passes through the data just counting the number of X's and O's. </p>\n\n<pre><code>std::transform(board.begin(), board.end(), board.begin(), ::tolower);\nsize_t numberOfO = std::count(board.begin(), board.end(), 'o');\nsize_t numberOfX = std::count(board.begin(), board.end(), 'x');\n</code></pre>\n\n<p>I'd suggest instead that one can accomplish this in a single pass without needing to alter the passed <code>board</code>:</p>\n\n<pre><code>size_t numberOfO{0};\nsize_t numberOfX{0};\nfor (auto ch : board) {\n switch (ch) {\n case 'O':\n case 'o':\n ++numberOfO;\n break;\n case 'X':\n case 'x':\n ++numberOfX;\n break;\n default:\n break;\n }\n}\n</code></pre>\n\n<h2>Check the winning condition more thoroughly</h2>\n\n<p>Once the counts have both been obtained, we can determine which player must have most recently played. If <code>numberOfO == numberOfX</code>, then O just played, otherwise X did. If the game is in a valid state, only the player that just played could possibly be the winner, which suggests that if O just played and X is the winner, the board is actually in an invalid state.</p>\n\n<h2>Add a condition to the return</h2>\n\n<p>There is one more condition that it would be useful to check for, which is a tie game. Right now the routine just returns <code>NoWinner</code> which is technically correct, but if all the squares are filled and no further moves are possible, it would make more sense to specially identify and return that unique state.</p>\n\n<h2>Use only necessary <code>#include</code>s</h2>\n\n<p>The <code>#include <vector></code> line is not necessary and can be safely removed.</p>\n\n<h2>Eliminate the need for <code><cmath></code></h2>\n\n<p>The only reason that <code><cmath></code> is needed is the use of <code>std::sqrt</code> but I'd suggest that it would be better to instead define the constants like this:</p>\n\n<pre><code>static constexpr int kBoardLength = 3;\nstatic constexpr int kBoardSize = kBoardLength * kBoardLength;\n</code></pre>\n\n<p>The use of <code>constexpr</code> can allow the compiler to make even better optimizations that would be available with <code>const int</code> and the use of <code>static</code> tells the compiler that the constant is local to this file. Also the way this is constructed, the board is always square which might not be the case otherwise.</p>\n\n<h2>Consider an alternate strategy</h2>\n\n<p>Another possible way to do this would be to minimize the number of iterations throught the data structure, keeping track of which wins are possible and which are not. Here's one way that might be written:</p>\n\n<pre><code>#include \"TicTacToe.h\"\n#include <string>\n\nstatic constexpr int kBoardLength = 3;\nstatic constexpr int kBoardSize = kBoardLength * kBoardLength;\n\nenum class Token { isX, isO, isEmpty };\n\nstatic Token classify(char square) {\n switch (square) {\n case 'O':\n case 'o':\n return Token::isO;\n break;\n case 'X':\n case 'x':\n return Token::isX;\n break;\n }\n return Token::isEmpty;\n}\n\nTicTacToeState CheckTicTacToeBoard(const std::string& board) {\n if (board.size() != kBoardSize) {\n return TicTacToeState::InvalidInput;\n }\n auto state{TicTacToeState::NoWinner};\n size_t numberOfO{0};\n size_t numberOfX{0};\n for (std::size_t i{0}; i < kBoardLength; ++i) {\n bool orow{classify(board[i * kBoardLength]) == Token::isO};\n if (orow) {\n ++numberOfO;\n }\n bool ocol{classify(board[i]) == Token::isO};\n bool xrow{classify(board[i * kBoardLength]) == Token::isX};\n if (xrow) {\n ++numberOfX;\n }\n bool xcol{classify(board[i]) == Token::isX};\n bool odiag{i==0 && classify(board[0]) == Token::isO};\n bool orevdiag{i==0 && classify(board[kBoardLength - 1]) == Token::isO};\n bool xdiag{i==0 && classify(board[0]) == Token::isX};\n bool xrevdiag{i==0 && classify(board[kBoardLength - 1]) == Token::isX};\n for (std::size_t j{1}; j < kBoardLength; ++j) {\n switch(classify(board[i * kBoardLength + j])) {\n case Token::isO:\n xrow = false;\n ++numberOfO;\n break;\n case Token::isX:\n orow = false;\n ++numberOfX;\n break;\n default:\n xrow = false;\n orow = false;\n }\n switch(classify(board[i + j * kBoardLength])) {\n case Token::isO:\n xcol = false;\n break;\n case Token::isEmpty:\n xcol = false;\n case Token::isX:\n ocol = false;\n break;\n }\n if (i==0) {\n switch(classify(board[j + j * kBoardLength])) {\n case Token::isO:\n xdiag = false;\n break;\n case Token::isEmpty:\n xdiag = false;\n case Token::isX:\n odiag = false;\n break;\n }\n switch(classify(board[j * kBoardLength + kBoardLength - j - 1])) {\n case Token::isO:\n xrevdiag = false;\n break;\n case Token::isEmpty:\n xrevdiag = false;\n case Token::isX:\n orevdiag = false;\n break;\n }\n }\n }\n if (orow || ocol || odiag || orevdiag) {\n if (state == TicTacToeState::Xwins) {\n return TicTacToeState::UnreachableState;\n }\n state = TicTacToeState::Owins;\n }\n if (xrow || xcol || xdiag || xrevdiag) {\n if (state == TicTacToeState::Owins) {\n return TicTacToeState::UnreachableState;\n }\n state = TicTacToeState::Xwins;\n }\n }\n if ((numberOfO == numberOfX && state == TicTacToeState::Xwins) ||\n (numberOfO + 1 == numberOfX && state == TicTacToeState::Owins) || \n (numberOfX - numberOfO > 1) \n ) {\n return TicTacToeState::UnreachableState;\n }\n if (numberOfX + numberOfO == kBoardSize && state == TicTacToeState::NoWinner) {\n state = TicTacToeState::TieGame;\n }\n return state;\n}\n</code></pre>\n\n<h2>Write a test harness</h2>\n\n<p>Writing a test harness is a good way to test the code and to provide for reviewers of your code because it shows which things you've considered and also provides an example of how you expect the code to be used. Here's the test harness I wrote for the version of the code shown above:</p>\n\n<pre><code>#include \"TicTacToe.h\"\n#include <iostream>\n\nstd::ostream& operator<<(std::ostream &out, const TicTacToeState& state) {\n switch (state) {\n case UnreachableState:\n out << \"Unreachable\";\n break;\n case Xwins:\n out << \"X wins\";\n break;\n case Owins:\n out << \"O wins\";\n break;\n case NoWinner:\n out << \"no winner\";\n break;\n case InvalidInput:\n out << \"invalid input\";\n break;\n case TieGame:\n out << \"Tie Game\";\n break;\n default:\n out << \"I don't even know what this is?!\";\n break;\n }\n return out;\n}\n\nstruct Test {\n const char *s;\n TicTacToeState result;\n};\n\nstd::ostream& operator<<(std::ostream& out, const Test& t) {\n auto result{CheckTicTacToeBoard(t.s)};\n if (result == t.result) {\n return out << \"OK \" << t.s << \" ==> \" << result;\n } \n return out << \"bad \" << t.s << \" ==> \" << result << \", expected \" << t.result;\n}\n\nint main(int argc, char *argv[]) {\n Test tests[]{\n {\"012345678\", NoWinner},\n {\"0123456789\", InvalidInput},\n {\"\", InvalidInput},\n {\"xXx345678\", UnreachableState},\n {\"xXxo4o67o\", UnreachableState},\n {\"ooox4x6xx\", UnreachableState},\n {\"xoxoxxoxo\", TieGame},\n {\"x...x...x\", UnreachableState},\n {\"xo..xo.ox\", UnreachableState}, // diagonal\n {\".ox.xoxo.\", UnreachableState}, // reverse diagonal\n {\"xo..xo..x\", Xwins}, // diagonal\n {\".ox.xox..\", Xwins}, // reverse diagonal\n {\"ox..ox.xo\", Owins}, // diagonal\n {\".xo.oxox.\", Owins}, // reverse diagonal\n {\"ox..ox..o\", UnreachableState}, // diagonal\n {\".xo.oxo..\", UnreachableState}, // reverse diagonal\n {\".o.......\", UnreachableState}, \n {\".x.......\", NoWinner}, \n {\"xxx...ooo\", UnreachableState}, \n {\"xx....ooo\", UnreachableState}, \n {\"xxx...oo.\", Xwins}, // row\n {\"..x..xoox\", Xwins}, // col\n };\n for (const auto &t : tests) {\n std::cout << t << '\\n';\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T16:57:48.203",
"Id": "214778",
"ParentId": "214737",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T23:41:39.287",
"Id": "214737",
"Score": "3",
"Tags": [
"c++",
"tic-tac-toe"
],
"Title": "Simple C++ program to check win in TicTacToe"
} | 214737 |
<p>I have trained a polygon detector neural network to recognize the mask of "quadrilateral" (the mask generates curvy lines so it's not exactly a quadrilateral). I would like to get the corners of the quadrilateral.</p>
<p>I believe the best approach is to get the points in the mask that are closest to the corners of the image. First question is, are these valid assumptions? Second question is, is this the best approach?</p>
<ul>
<li>Top-Left is minimum distance between (0,0) and mask.</li>
<li>Top-Right is minimum distance between (width, 0) and mask.</li>
<li>Bottom-Left is minimum distance between (0, height) and mask.</li>
<li>Bottom-Right is minimum distance between (width, height) and mask.</li>
</ul>
<p>The last question is, is my implementation slow? The Neural network generates the mask in .7 seconds, but it's taking my loop ~2 seconds to find the corners. Can this be sped up?</p>
<pre><code>def predict(self,img):
# Read image
image = img
height,width,channels=img.shape
# Detect objects
r = self.model.detect([image], verbose=0)[0]
mask=r['masks']
print(mask)
x1=0
x2=0
x3=0
x4=0
y1=0
y2=0
y3=0
y4=0
minDistanceTopLeft=999999
minDistanceTopRight=999999
minDistanceBottomLeft=999999
minDistanceBottomRight=999999
xAverage=0.0
yAverage=0.0
for x in range(0, len(mask)):
for y in range(0, len(mask[x])):
if(mask[x][y]):
distToTopLeft=(x-0)*(x-0)+(y-0)*(y-0)
if(distToTopLeft<minDistanceTopLeft):
minDistanceTopLeft=distToTopLeft
x1=x
y1=y
distToTopRight=(x-width)*(x-width)+(y-0)*(y-0)
if(distToTopRight<minDistanceTopRight):
minDistanceTopRight=distToTopRight
x2=x
y2=y
distToBottomLeft=(x-0)*(x-0)+(y-height)*(y-height)
if(distToBottomLeft<minDistanceBottomLeft):
minDistanceBottomLeft=distToBottomLeft
x4=x
y4=y
distToBottomRight=(x-width)*(x-width)+(y-height)*(y-height)
if(distToBottomRight<minDistanceBottomRight):
minDistanceBottomRight=distToBottomRight
x3=x
y3=y
toReturn=np.array([x1, y1, x2, y2, x3, y3, x4, y4, 1])
return [toReturn.tolist()]
</code></pre>
<p>Mask is a numpy array of booleans:</p>
<pre><code>[[[False]
[False]
[False]
...
[False]
[False]
[False]]
[[False]
[False]
[False]
...
[False]
[False]
[False]]
[[False]
[False]
[False]
...
[False]
[False]
[False]]
...
[[False]
[False]
[False]
...
[False]
[False]
[False]]
[[False]
[False]
[False]
...
[False]
[False]
[False]]
[[False]
[False]
[False]
...
[False]
[False]
[False]]]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T00:00:07.380",
"Id": "415236",
"Score": "0",
"body": "Is my understanding correct, that you want to find an axis-aligned bounding box that encompasses all of the `True` values in `mask`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T00:03:55.833",
"Id": "415237",
"Score": "0",
"body": "Could be, I guess I need to do more research into what axis-aligned mean - I don't know if its considered a bounding box since those are normally rectangles right? Mine can be a parallelogram. Thank you for this comment though, it has given me search terms I can look into. But yes True values in mask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T00:07:31.370",
"Id": "415238",
"Score": "1",
"body": "My mistake, then. It looks like you're looking for an arbitrary bounding quadrilateral (not necessarily a rectangle, and not axis-aligned)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T15:19:16.993",
"Id": "459987",
"Score": "0",
"body": "Please describe `mask`. Is it an image with all pixel set within a (convex?) quadrangle? Any restrictions on the quadrangle (square, rectangular, ...). Any restriction on the alignment? Please describe what you try to find. The corners of the input quadrangle?"
}
] | [
{
"body": "<p>assorted findings</p>\n\n<ul>\n<li>your code does not <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">document</a> what <code>predict()</code> accomplishes<br>\n• I don't even get how the name <em>predict</em> is telling/helpful<br>\n• your code documents neither the approach chosen nor alternatives disregarded</li>\n<li>comparing a cheaper monotone function of Euclidean distance: nice<br>\n• naming the variables without fussing that it's equivalent Euclidean at the end of the day rather than equal to or sum/Manhattan or max: nice, again</li>\n<li>camelCase is not pythonic</li>\n<li>initial value for minDistances should be <code>height*height+width*width+1</code></li>\n<li>the approach visits each and every element of <code>mask</code></li>\n<li>no <code>mask[x].index(True)</code> (careful with <code>mask[x].reverse().index(True)</code>)</li>\n<li>the squares get computed time and again<br>\nlooks especially off with <code>x</code></li>\n<li>code for the four pairs looks repetitive<br>\nnaming too, come to think of it</li>\n<li>the mask example is useless for showing one value, only</li>\n</ul>\n\n<p><strong>context provided is lacking: what <em>is</em> <code>get the corners of [not-exactly-]quadrilateral</code></strong>? </p>\n\n<p>alternative approaches to find <code>closest to the [image] corners</code></p>\n\n<ul>\n<li>start from the middle<br>\nwhen you find an element set, you still have to inspect all the element closer to the corner, up to the corner itself<br>\njust complicates iteration</li>\n<li>proceed in order of increasing distance from the corners<br>\n+: you find elements set close to the corner early on<br>\n you don't need to look any further for that corner<br>\n-: even with at least one element set, there may be more than two visits on average (solitary <code>True</code> in one corner)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-05T11:38:33.587",
"Id": "235111",
"ParentId": "214738",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T23:46:25.430",
"Id": "214738",
"Score": "2",
"Tags": [
"python",
"performance",
"algorithm",
"image",
"numpy"
],
"Title": "Retrieval of the corners of a mask"
} | 214738 |
<p>Following is based on a problem description from a Codility test, as a task in an interview.</p>
<hr>
<h2>DeepestPit - problem description</h2>
<p>A non-empty zero-indexed array <code>B</code> consisting of <code>M</code> integers is given. A <em>pit</em> in this array is any triplet of integers <code>(X, Y, Z)</code> such that:</p>
<ul>
<li><code>0 ≤ X < Y < Z < M</code></li>
<li>sequence <code>[B[X], B[X+1], ..., B[Y]]</code> is strictly decreasing, i.e. <code>B[X] > B[X+1] > ... > B[Y]</code></li>
<li>sequence <code>B[Y], B[Y+1], ..., B[Z]</code> is strictly increasing, i.e. <code>B[Y] < B[Y+1] < ... < B[Z]</code></li>
</ul>
<p>The <em>depth</em> of a pit <code>(X, Y, Z)</code> is the number <code>min{B[X] − B[Y], B[Z] − B[Y]}</code>.</p>
<p>For example, consider array <code>B</code> consisting of 10 elements such that:</p>
<pre><code>B[0] = 0
B[1] = 2
B[2] = 7
B[3] = -4
B[4] = 0
B[5] = 4
B[6] = 0
B[7] = -6
B[8] = 4
B[9] = 6
</code></pre>
<p>Triplet <code>(2, 3, 4)</code> is one of pits in this array, because sequence <code>[B[2], B[3]]</code> is strictly decreasing (7 > −4) and sequence <code>[B[3], B[4]]</code> is strictly increasing (−4 < 0). Its depth is <b>min</b>{B[2] − B[3], B[4] − B[3]} = 4. Triplet <code>(2, 3, 5)</code> is another pit with depth 8. Triplet <code>(5, 7, 8)</code> is yet another pit with depth 10. There is no pit in this array deeper (i.e. having depth greater) than 10.</p>
<p>Write a function:</p>
<pre><code>function deepest_pit(B)
</code></pre>
<p>that, given a non-empty zero-indexed array <code>B</code> consisting of <code>M</code> integers, returns the depth of the deepest pit in array <code>B</code>. The function should return −1 if there are no pits in array <code>B</code>.</p>
<p>For example, for the above array <code>B</code>, the function should return 10, as explained above.</p>
<p>Write an efficient algorithm for the function.</p>
<p>Assume that:</p>
<blockquote>
<ul>
<li>M is an integer within the range <code>[1..1,000,000]</code>;</p><p></li>
<li>each element of array B is an integer within the range
<code>[−100,000,000..100,000,000]</code>.</li>
</ul>
</blockquote>
<p>(A previous test instead stated the complexity conditions as follows.)
<p>Complexity:</p>
<blockquote><p>· expected worst-case time complexity is O(M);</p><p>· expected worst-case space complexity is O(M), beyond input storage (not counting the storage required for input arguments).</p></blockquote>
<hr>
<p>My solution, as follows, gets a task score of 100% (100% for correctness and 100% for performance). (A previous version only got 26%, with 44% correctness and 0% performance.)</p>
<pre><code>function deepest_pit(B) {
// write your code in JavaScript (Node.js 8.9.4)
var M = B.length,
depth = -1;
if (M < 3) {
return depth;
}
var X, Y, Z;
var i = 0, j, k;
while (i < M - 2) {
X = B[i];
// console.log("i = ", i, "X = ", X)
j = i + 1;
while (B[j] < B[j - 1] && j < M - 1) {
j++;
}
if (j === i + 1) {
i++;
continue;
}
j = j - 1;
Y = B[j];
// console.log("i = ", i, "Y = ", Y)
k = j + 1;
while (B[k] > B[k - 1] && k < M) {
k++;
}
if (k === j + 1) {
i++;
continue;
}
k = k - 1;
Z = B[k];
depth = Math.max(depth, Math.min(p - Y, Z - Y));
// console.log("depth is", depth)
i++;
}
return depth;
}
</code></pre>
<p><a href="https://jsfiddle.net/jamesray/3e8ab69w/45" rel="nofollow noreferrer">JSFiddle with the above code, plus tests.</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:41:26.320",
"Id": "415276",
"Score": "1",
"body": "I think this could make a good Code Review question once the bugs have been resolved. Please finish debugging it and update the question with *working* code, then you'll likely get some good reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T23:50:54.930",
"Id": "415429",
"Score": "0",
"body": "I have edited the while loops to check the previous element (j-1 and k-1, not q and r, respectively). I think this will work now. I will do some more testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T00:45:09.320",
"Id": "415437",
"Score": "1",
"body": "Edited accordingly, I am getting a 100% task score now: 100% for correctness and 100% for performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T03:54:59.997",
"Id": "415442",
"Score": "0",
"body": "The most recent edit implies that you don't want the question to be posted."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T03:18:53.283",
"Id": "214743",
"Score": "3",
"Tags": [
"javascript",
"performance",
"algorithm",
"programming-challenge",
"array"
],
"Title": "Deepest pit of an array"
} | 214743 |
<p>I write a web app that shows events on a multi room scheduler. I use VueJS for the first time on a real project.</p>
<p>Here, I loop through the events array every room column (two nested v-for). In jQuery I need to loop once through this array to fill all columns at once.</p>
<p>My question: is there any other more efficient way to write this code that fills rooms divs with events in Vue?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var vm = new Vue({
el: '#app',
data: {
rooms: [
{id: 1, title: 'Room 1' },
{id: 2, title: 'Room 2' }
],
events: [
{ id: 1, start: 230, duration: 30, title: 'Event 1', room_id: 2},
{ id: 2, start: 400, duration: 45, title: 'Event 2', room_id: 1}
]
}
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.agenda-wrapper { max-width: 100%; overflow-x: scroll; }
.agenda { padding-top: 50px; overflow: hidden; }
.room {
width:300px;
height:1170px;
padding: 0 10px;
margin-left: 5px;
background:#ECECEC;
position:relative;
float: left;
}
.room span {
position: absolute;
top: -20px;
height: 10px;
text-align: center;
width: 300px;
font-weight: bold;
}
.event {
display: block;
background:#fff;
color:#4B6EA8;
border:1px solid #ccc;
border-left:4px solid #c4183c;
position:absolute;
padding:0 10px;
font-weight:bold;
font-size:13px;
border-radius: 5px;
width: 280px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="agenda-wrapper" id="app">
<div class="agenda" :style="{ width: (rooms.length * 350) + 'px' }">
<div class="room" v-for="room in rooms" :key="room.id">
<span>{{ room.title }}</span>
<div class="event"
:style="{ top: event.start + 'px', height: event.duration + 'px'}"
v-for="event in events"
v-if="event.room_id === room.id">
<h5>{{ event.title }}</h5>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:44:09.880",
"Id": "415277",
"Score": "0",
"body": "Hi and welcome to Code Review! I'm planning on answering your question later, but just out of curiousity: How would you do it in jQuery?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T09:02:32.867",
"Id": "415279",
"Score": "0",
"body": "Hi, thank you for your reply! I think it would be something like that: '$.each(events, function(event){\n var el = $(\"<div></div>\").addClass(\"event\").css({ \"height\": event.duration + \"px\", \"top\": event.start + \"px\" }).text(event.title);\n $('.room').data('place', event.place_id).append(el);\n });'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T09:03:45.943",
"Id": "415280",
"Score": "0",
"body": "I also think that maybe I need to do it on backend to make a rooms array look like that: { id: 1, title: 'Room 1', events: [{ id: 1, title: 'Event 1', start: 90, duration: 30 }] }"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T13:34:08.010",
"Id": "415310",
"Score": "0",
"body": "Yes, backend is Laravel app. It has two models: Room and Event. Event belongsTo Room."
}
] | [
{
"body": "<p>I asked you how you would do it in jQuery and you said that you would do something like:</p>\n\n<blockquote>\n<pre><code>$.each(events, function(event){\n var el = $(\"<div></div>\")\n .addClass(\"event\")\n .css({ \"height\": event.duration + \"px\", \"top\": event.start + \"px\" })\n .text(event.title);\n $('.room').data('place', event.place_id).append(el);\n});\n</code></pre>\n</blockquote>\n\n<p>And sure, this would only loop through the <code>events</code> array once. But what happens in every iteration? It does a jQuery search for <code>$('.room').data('place', event.place_id)</code>, which is not a constant-time lookup operation, so this approach might be slower than what you think it is.</p>\n\n<hr>\n\n<p>Now, for your Vue approach. You said:</p>\n\n<blockquote>\n <p>maybe I need to do it on backend to make a rooms array look like that: <code>{ id: 1, title: 'Room 1', events: [{ id: 1, title: 'Event 1', start: 90, duration: 30 }] }</code> </p>\n</blockquote>\n\n<p>And yes, I agree with this. Putting the <code>events</code> inside your rooms makes much more sense.</p>\n\n<p>As for your Vue template, overall the code looks fine. I'm not a CSS expert so I don't know if there's something you can improve there, but there probably is. Maybe consider using <a href=\"https://css-tricks.com/snippets/css/complete-guide-grid/\" rel=\"nofollow noreferrer\">CSS Grids</a>, where each room could be one column, and time-slots could be rows? The current approach of having 1px = 1 minute seems a bit unnatural to me.</p>\n\n<p>As for this part:</p>\n\n<pre><code><div class=\"room\" v-for=\"room in rooms\" :key=\"room.id\">\n <span>{{ room.title }}</span>\n <div class=\"event\" \n :style=\"{ top: event.start + 'px', height: event.duration + 'px'}\" \n v-for=\"event in events\" \n v-if=\"event.room_id === room.id\">\n <h5>{{ event.title }}</h5>\n</div>\n</code></pre>\n\n<p>The only thing I would change is to put <code>v-for</code> and <code>v-if</code> before your <code>:style</code>-binding, as they are more important to be aware about, this is mostly my personal opinion though.</p>\n\n<pre><code><div class=\"room\" v-for=\"room in rooms\" :key=\"room.id\">\n <span>{{ room.title }}</span>\n <div class=\"event\" \n v-for=\"event in events\" \n v-if=\"event.room_id === room.id\"\n :style=\"{ top: event.start + 'px', height: event.duration + 'px'}\" \n >\n <h5>{{ event.title }}</h5>\n</div>\n</code></pre>\n\n<p>It would be nicer if your events would be inside the rooms, as then you could write:</p>\n\n<pre><code><div class=\"room\" v-for=\"room in rooms\" :key=\"room.id\">\n <span>{{ room.title }}</span>\n <div class=\"event\" \n v-for=\"event in room.events\" \n :style=\"{ top: event.start + 'px', height: event.duration + 'px'}\" \n >\n <h5>{{ event.title }}</h5>\n</div>\n</code></pre>\n\n<p>I would recommend in the future to use a <code>Room</code> component and a <code>RoomEvent</code> component so that you could write:</p>\n\n<pre><code><Room v-for=\"room in rooms\" :key=\"room.id\" />\n</code></pre>\n\n<p>And the room-component:</p>\n\n<pre><code><div class=\"room\">\n <span>{{ room.title }}</span>\n <RoomEvent v-for=\"event in room.events\" />\n</div>\n</code></pre>\n\n<p>I think that the <code><h5>{{ event.title }}</h5></code> belongs inside the <code>RoomEvent</code></p>\n\n<hr>\n\n<p>Overall a nice job!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T07:22:46.890",
"Id": "415567",
"Score": "0",
"body": "Thank you so much for such a great review! I rewrote backend as I mentioned. Now the code is a bit faster. As for CSS, I will look at CSS Grids one more time, but I'm afraid it's more complicated and less supportive by old browsers way. Anyway, thanks for your advice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T07:24:26.957",
"Id": "415569",
"Score": "0",
"body": "Another small question: I have some plugins that need jQuery. Is it a good idea to use both jQuery (UI components like Select2) and Vue in same code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:05:04.690",
"Id": "415597",
"Score": "0",
"body": "@Alex Yes unfortunately CSS Grids are not supported by older browsers. Regarding jQuery: I have never used it together with Vue myself but I would recommend to try to get rid of jQuery. There is probably Vue alternatives that you can use instead, if you are looking for UI-components then I can recommend [Vuetify](https://vuetifyjs.com) for example."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T22:40:21.410",
"Id": "214799",
"ParentId": "214749",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T08:26:18.737",
"Id": "214749",
"Score": "5",
"Tags": [
"javascript",
"vue.js"
],
"Title": "Showing events on a multi room scheduler"
} | 214749 |
<p>I have 2 dates that I would like to have the difference between them in days and if less than a one day simply show "less than a day".</p>
<pre><code>remainingTime() {
// Scientific notation of 8.64e+7
const DAY_IN_MILLISECONDS = 8.64 * (10 ** 7);
const date1 = new Date('2019-02-28T01:22:06.671Z').getTime();
const date2 = new Date('2019-02-28T04:01:06.671Z').getTime();
const differenceInMS = date2 - date1;
const days = Math.floor(differenceInMS / DAY_IN_MILLISECONDS);
return (days > 1) ? `They have ${days} days` : (days === 1) ? `They have ${days} day` : `you have less than a day left`;
}
</code></pre>
<p>Is this way correct if localization is taken into account?</p>
<p>what exactly is the difference between <code>getTime ()</code>, <code>getMilliseconds ()</code> and <code>getUTCMilliseconds ()</code>?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T14:47:43.377",
"Id": "415322",
"Score": "1",
"body": "You can use Exponentiation number notation for numbers. eg `8.64 * 10 ** 7 === 8.64e7` or '8.64E7' also `**` has precedence over `*` so you don't need the `()` around `10 ** 7`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T15:19:00.157",
"Id": "415330",
"Score": "1",
"body": "What localization? Your code isn't internationalized."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T16:41:37.287",
"Id": "415355",
"Score": "0",
"body": "Considering that you have hard-coded English strings, this is obviously not correct, taking localization into account..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T17:21:58.837",
"Id": "415361",
"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>Your code looks good to me. I think <code>1000 * 60 * 60 * 24</code> would be more intuitive than the scientific notation, but either way gets the job done. </p>\n\n<p>The script doesn't actually take localization into account because <code>Date</code>'s <code>getTime</code> method is not localized. To account for time zone, you'd want to get the \"timezone offset\" of the user's location. (Note that <code>getTimezoneOffset</code> returns a number of minutes, and that number isn't a property of the date object but just an indication of what timezone the code is running in.)</p>\n\n<p>As for the other methods<br>\n - <code>getTime</code> returns the actual \"timestamp\", a big integer showing how many milliseconds have passed since the 60s ended in London<br>\n - <code>getUTCMilliseconds</code> is just the last three digits of that timestamp (ie how many milliseconds it's been since the last full second since the \"epoch\", as it's called.)<br>\n - Leaving out the <code>UTC</code> bit (as in <code>getMilliseconds</code>, or in any of the similar <code>get</code> methods, excepting <code>getTime</code>) makes javascript calculate the local version for you (and in the case of milliseconds, I'd be pretty surprised if it were different from the universal version.) </p>\n\n<p>...You can see the whole buffet on MDN:\n <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Date.prototype_Methods\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Date.prototype_Methods</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T12:36:57.930",
"Id": "214762",
"ParentId": "214754",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214762",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T09:35:43.670",
"Id": "214754",
"Score": "0",
"Tags": [
"javascript",
"datetime",
"typescript",
"localization"
],
"Title": "JavaScript - Difference between two dates in days or less"
} | 214754 |
<p>I'm a junior developer (couple years into it) and very new to AJAX.</p>
<p>I'm writing an internal inventory application built on MVC and right now I'm dealing with adding and removing items to/from a cart. When the user select an item to take in or out, s/he is brought to the cart page, where they can choose to add or diminish the number of item to charge or dismiss. This is the appearance of part of the page (just for reference: "Marca" stands for Manufacturer, "Modello" for Model) <a href="https://i.stack.imgur.com/ouyx4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ouyx4.png" alt="enter image description here"></a></p>
<p>This is the cshtml code for the whole partial view:</p>
<pre><code>@using Magazzino.Domain.Entities
@model Magazzino.WebUI.Models.CarrelloViewModel
@{
ViewBag.Title = "Carrello";
}
<h2>Carrello</h2>
<table class="table carrello">
<thead>
<tr>
<th>Categoria</th>
<th>Marca</th>
<th>Modello</th>
<th>Colore</th>
<th>Note</th>
<th>Quantità</th>
</tr>
</thead>
<tbody>
@foreach (Articolo articolo in Model.Carrello.Articoli)
{
<tr>
<td class="text-left">@articolo.Item.Categoria</td>
<td class="text-left">@articolo.Item.Marca</td>
<td class="text-left">@articolo.Item.Modello</td>
<td class="text-left">@articolo.Item.Colore</td>
<td class="text-left">@articolo.Item.Note</td>
<td class="carrello-qta">
<div class="qtaAggiungi btn btn-success" data-action-url="@Url.Action("AumentaODiminuisci", "Carrello")" data-item-marca="@articolo.Item.Marca" data-item-modello="@articolo.Item.Modello">+</div>
<input class="form-control" type="text" data-item-marca="@articolo.Item.Marca" data-item-modello="@articolo.Item.Modello" value="@articolo.Qta" name="Qta" />
<div class="qtaDiminuisci btn btn-success" data-action-url="@Url.Action("AumentaODiminuisci", "Carrello")" data-item-marca="@articolo.Item.Marca" data-item-modello="@articolo.Item.Modello">-</div>
</td>
</tr>
}
</tbody>
</table>
<div class="text-center">
<a class="btn btn-primary" href="@Model.ReturnUrl">Prosegui la consultazione</a>
</div>
</code></pre>
<p>while this is the page ViewModel:</p>
<pre><code>public class CarrelloViewModel
{
public Carrello Carrello { get; set; }
public string ReturnUrl { get; set; }
}
</code></pre>
<p>and this is the cart class</p>
<pre><code>public class Carrello
{
private List<Articolo> ElencoArticoli = new List<Articolo>();
public void AggiungiArticolo(Item item, int qta)
{
Articolo articolo = ElencoArticoli.Where(i => i.Item == item).FirstOrDefault();
if (articolo == null)
{
ElencoArticoli.Add(new Articolo { Item = item, Qta = qta });
}
}
public void RimuoviArticolo(Item item)
{
ElencoArticoli.RemoveAll(i => i.Item == item);
}
public void CancellaTutto()
{
ElencoArticoli.Clear();
}
public void ModificaArticolo(Item item, int qta)
{
Articolo articolo = ElencoArticoli.Where(i => i.Item == item).FirstOrDefault();
if (articolo == null) throw new ArgumentOutOfRangeException("L'articolo non è presente nel carrello");
articolo.Qta = qta;
}
public void AumentaODiminuisciArticolo(Item item, int qta)
{
Articolo articolo = ElencoArticoli.Where(i => i.Item == item).FirstOrDefault();
if (articolo == null) throw new ArgumentOutOfRangeException("L'articolo non è presente nel carrello");
articolo.Qta += qta;
}
public List<Articolo> Articoli
{
get { return ElencoArticoli; }
}
}
public class Articolo
{
public Item Item { get; set; }
public int Qta { get; set; }
}
</code></pre>
<p>The buttons in the page are each bound to the relevant AJAX post, both within the classic <code>$(document).ready(function() {})</code></p>
<pre><code>$('.qtaAggiungi').on('click', function () {
self = $(this);
// get the corrispondent quantity textbox element
var qtaCorrente = $("input[name='Qta']").filter(function () {
return ($(this).data()["itemMarca"] === self.data()["itemMarca"])
&& ($(this).data()["itemModello"] === self.data()["itemModello"]);
});
var ajaxRequest = $.ajax({
url: $(this).data()["actionUrl"],
type: "post",
data: {
marca: $(this).data()["itemMarca"],
modello: $(this).data()["itemModello"],
qta: 1,
}
}).done(function (data) {
qtaCorrente.val(data);
});
})
$('.qtaDiminuisci').on('click', function () {
self = $(this);
var qtaCorrente = $("input[name='Qta']").filter(function () {
return ($(this).data()["itemMarca"] === self.data()["itemMarca"]) && ($(this).data()["itemModello"] === self.data()["itemModello"]);
});
if (qtaCorrente.val() > 1) {
var ajaxRequest = $.ajax({
url: $(this).data()["actionUrl"],
type: "post",
data: {
marca: $(this).data()["itemMarca"],
modello: $(this).data()["itemModello"],
qta: -1,
}
}).done(function (data) {
qtaCorrente.val(data);
});
}
})
</code></pre>
<p>and this is the action method in the controller (comments added her for clarity because of translation):</p>
<pre><code>public int AumentaODiminuisci(string marca, string modello, int qta)
{
// getting the inventory List from repository
List<ElementoInventario> inventario = Repository.GetInventario();
// getting the correspondent item in the inventory
Item itemDaModificare = inventario
.Where(i => i.Item.Marca == marca && i.Item.Modello == modello)
.FirstOrDefault().Item;
if (itemDaModificare != null)
{
// modify the quantity of that item in the cart
GetCarrello().AumentaODiminuisciArticolo(itemDaModificare, qta);
}
// return the update quantity
return GetCarrello().Articoli
.Where(i => i.Item.Marca == marca && i.Item.Modello == modello)
.FirstOrDefault().Qta;
}
private Carrello GetCarrello()
{
Carrello carrello = (Carrello)Session["Carrello"];
if (carrello == null)
{
carrello = new Carrello();
Session["Carrello"] = carrello;
}
return carrello;
}
</code></pre>
<p>My main doubt is the fact that I initially loaded the value of the quantity textbox through Razor, but after every modification, the displayed value and the model are -let's say- "disjointed". Sure, the Model gets updated and so is the displayed value and they are (or should be!) always equal, but I'm questioning myself whether it is fine to call a method that returns a simple integer value and then update the textbox with that value, or is a bad practice that might lead to bugs (I also see now that I have a method that might throw an exception but I'm not catching it).</p>
<p>Also, I feel like the way I find the textbox in the beginning of the javascript function is way too "hacky" and not very performing.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T16:24:14.813",
"Id": "415349",
"Score": "1",
"body": "`.FirstOrDefault().Item;` doesn't make sense. The `OrDefault()` implies the result can be null, but your `.Item` always assumes it isn't."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T11:05:59.483",
"Id": "214757",
"Score": "3",
"Tags": [
"c#",
"javascript",
"ajax",
"asp.net-mvc",
"e-commerce"
],
"Title": "AJAX shopping cart with quantity +/- buttons"
} | 214757 |
<p>I need to get length of the longest sequence of numbers with the same sign. Assumes that zero is positive. For example:</p>
<pre><code>{10, 1, 4, 0, -7, 2, -8, 4, -2, 0} → 4
{0, 1, 2, 3, -2, -4, 0} → 4
{1, -2, 0, -1} → 1
</code></pre>
<p>I wrote a function:</p>
<pre><code>unsigned getLongestSameSignSequenceLength(std::vector<int> const& a)
{
unsigned maxlen = 1;
/* Assumes that zero is positive. */
#define SIGN(a) (a >= 0)
for (size_t i = 1, len = 1; i < a.size(); i++, len++) {
if (SIGN(a[i]) != SIGN(a[i - 1])) {
maxlen = std::max(maxlen, len);
len = 0;
} else {
if (i == a.size() - 1)
return std::max(maxlen, len + 1);
}
}
#undef SIGN
return maxlen;
}
</code></pre>
<p>Can you please give me tips to improve my code?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T15:29:20.450",
"Id": "415334",
"Score": "4",
"body": "This only merits a comment (not a full answer) but since I *just* read [the essay by Bob Nystrom](http://journal.stuffwithstuff.com/2016/06/16/long-names-are-long/) it behooves me to note that *your function name is too long*. Shorten it to make it more readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T16:25:04.240",
"Id": "415350",
"Score": "3",
"body": "*Naming things* is often described as one of the Two Hard Problems in Programming (along with *Cache Invalidation* and *Off-by-One Errors*). \"Shorten it\" is easier said than done! We can obviously remove the `get` prefix, but after that, it gets more difficult. My best effort is `maxSameSignRunLength()` but that's still not very concise..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T18:59:21.910",
"Id": "415374",
"Score": "4",
"body": "Realistically, this is a toy function; in the context of particular business domain, the values likely have meaning beyond \"positive/negative number\" and so the function would similarly be named based on those higher-level semantics. Something like \"maxTemperatureSpan\", for example."
}
] | [
{
"body": "<p>Since this is C++ and not C, macros should generally be avoided. Define a function or create a named lambda expression might be better.</p>\n\n<p>If you are going to use a macro define it before the function (outside the function) and undefine it after the function.</p>\n\n<p>The code isn't using most of what a container class provides, there is no use of iterators, and the vector is being treated like a C language array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T16:28:51.827",
"Id": "415351",
"Score": "2",
"body": "It's obviously a personal preference, but I see no need to enclose the entire function between `#define` and `#undef`; indeed, on the rare occasions I need macros like this, I prefer to keep them local to a block as in the original code. I agree that in this case, a function or lambda expression is more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T16:32:03.053",
"Id": "415353",
"Score": "3",
"body": "I think I would recommend (if not eliminating the macro) to fully parenthesize the macro arguments in the expansion, i.e. `((a) >= 0)`. Even though the usages here are safe without that, it still causes a slowdown every time I read it and have to check."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T13:07:20.067",
"Id": "214765",
"ParentId": "214758",
"Score": "5"
}
},
{
"body": "<p>I would raise at least the following points:</p>\n\n<ul>\n<li><p>Instead of taking as input an <code>std::vector</code>, you could rather take two iterators pointing to the beginning and end of a range. In this way, you can also nicely operate on ranges.</p></li>\n<li><p>To avoid <a href=\"https://stackoverflow.com/q/14041453/551375\">all sorts of evil associated with macros</a>, you can use a lambda function here instead. So just define e.g., <code>const auto sign = [](int v) { return v >= 0; };</code> and use this instead of <code>SIGN</code>.</p></li>\n<li><p>You might run into compilation problems with <code>std::max</code> and its arguments being <code>unsigned</code> and <code>size_t</code> (happens on MSVC'15 at least). So you should use the same type for both arguments.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T13:07:27.490",
"Id": "214766",
"ParentId": "214758",
"Score": "7"
}
},
{
"body": "<p>A small portability bug: <code>std::size_t</code> is in the <code>std</code> namespace, assuming it's declared by including <code><cstddef></code> (recommended).</p>\n\n<p>No unit tests are included, but I'd expect one that tests that the result is zero when the input collection is empty. We need to initialize <code>maxlen</code> to zero for that test to pass.</p>\n\n<p>When comparing consecutive elements of a collection, always consider using <code>std::adjacent_find()</code>. With a suitable predicate function, we can find changes from negative to non-negative and vice versa without needing to code our own loop or do any indexing.</p>\n\n<p>(More advanced) Consider making your algorithm generic, templated on an iterator type, so that it can be applied to any collection (or even to an input stream directly).</p>\n\n<p>Here's a version that applies all of these suggestions (and some from other answers that I've not repeated above):</p>\n\n<pre><code>#include <algorithm>\n#include <cmath>\n#include <cstddef>\n#include <iterator>\n\ntemplate<typename ForwardIt>\nstd::size_t getLongestSameSignSequenceLength(ForwardIt first, ForwardIt last)\n{\n auto const signdiff =\n [](auto a, auto b){ return std::signbit(a) != std::signbit(b); };\n\n std::size_t maxlen = 0;\n\n while (first != last) {\n ForwardIt change = std::adjacent_find(first, last, signdiff);\n if (change != last) { ++change; }\n\n std::size_t len = std::distance(first, change);\n if (len > maxlen) { maxlen = len; }\n\n first = change;\n }\n\n return maxlen;\n}\n</code></pre>\n\n<p>// tests:</p>\n\n<pre><code>#include <vector>\n\nint main()\n{\n struct testcase { std::size_t expected; std::vector<int> inputs; };\n std::vector<testcase> tests\n {\n {0, {}},\n {1, {1}},\n {1, {1, -2}},\n {1, {1, -2, 3}},\n {1, {-1, 2, -3}},\n {2, {1, 2}},\n {2, {1, 2, -3}},\n {2, {-1, -2, 3}},\n {2, {-1, 2, 3}},\n {2, {-1, 2, 3, -4}},\n };\n\n int failures = 0;\n for (auto const& [e, v]: tests) {\n failures += getLongestSameSignSequenceLength(v.begin(), v.end()) != e;\n }\n\n return failures;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T23:39:32.063",
"Id": "415426",
"Score": "0",
"body": "[`std::size_t`](https://en.cppreference.com/w/cpp/types/size_t) is not defined in [`<cstdint>`](https://en.cppreference.com/w/cpp/header/cstdint). Your test should at least cover sequences in which there are more negatives than positives (\\$\\{-1\\}, \\{1, -2, -3\\}\\$)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T06:28:27.170",
"Id": "415448",
"Score": "0",
"body": "You should be using `std::signbit`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T09:33:35.193",
"Id": "415465",
"Score": "0",
"body": "@Cody, yes. For the original code, visiting only integers, there's no real advantage to `std::signbit`. But having made the code generic, then that is a sensible choice (because we might now be seeing NaN or -0)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T10:21:25.730",
"Id": "415468",
"Score": "0",
"body": "@Snowhawk - right on both counts; I've edited. I made sure that the tests had longest run at beginning and at end, but never considered varying the sign of the longest run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:51:21.957",
"Id": "415512",
"Score": "0",
"body": "The advantages are increased readability and a potential for better optimization. Clang and ICC generate the same code, but GCC's is slightly better for `std::signbit` (it rearranges the code, and thus is able to reduce one of the shifts to a bitwise-AND). The major disadvantage is, as far as I can tell, no support for `std::signbit` on MSVC. I'm not sure if it's non-compliant, or the version for integer types is a non-standard extension."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T18:12:51.500",
"Id": "415519",
"Score": "0",
"body": "@Cody: The integer version of [`std::signbit`](https://en.cppreference.com/w/cpp/numeric/math/signbit) - overload **(4)** - should be available in `<cmath>`, assuming the platform conforms to C++11 or later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T18:16:30.940",
"Id": "415521",
"Score": "0",
"body": "I agree that it *should* be, but it isn't available in MSVC 19 (or earlier versions), which is expected to be fully compliant with C++11. I consulted the same reference for verification, but I thought it was possible there was a mistake. MSVC does have the floating-point overloads, but not integer overload 4. See [Godbolt](https://gcc.godbolt.org/z/LbNkQX) for example."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T13:12:52.277",
"Id": "214768",
"ParentId": "214758",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "214768",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T12:08:18.683",
"Id": "214758",
"Score": "4",
"Tags": [
"c++",
"vectors"
],
"Title": "Get length of the longest sequence of numbers with the same sign"
} | 214758 |
<p>Scientists have found that a text can still be read even if only the first and last letter of a word are in their right place. The remaining characters within the word can be arranged randomly.</p>
<p>Suppose you want to send a text whose content is checked for specific words by a filter. Instead of encrypting it, one could also use this algorithm. But actually that's just a fun program.</p>
<p>I would like to know how professionals rate my code. Can you write parts of the source code more readable?</p>
<p><strong>Example Output</strong></p>
<pre><code>Sntecistis hvae fnuod taht a txet can sltil be read eevn if only the fsrit and lsat
lteter of a wrod are in teihr rghit plcae. The rinnimaeg caartcehrs witihn the wrod
can be araergnd rdnlomay.
Sppuose you want to sned a text wsohe cnteont is cehcekd for seipcfic wdros by a
ftelir. Intsead of enintrpcyg it, one cuold aslo use this aorltihgm. But aallucty
that's jsut a fun prraogm.
I would like to know how pnarloofesiss rtae my code. Can you wtrie ptars of the
suorce cdoe mroe rabdleae?
</code></pre>
<p><strong>Another Example</strong></p>
<pre><code>iormpt jvaa.uitl.Scenanr;
imorpt java.io.Flie;
improt jvaa.io.FdeliRaeer;
import jvaa.io.BfeaeudfeRrder;
ipomrt java.io.IxptiEeOcon;
pilubc cslas Main {
pilubc siattc viod main(String[] args) {
SignldetrBuir text = new SeuitdrBginlr();
if (agrs.lgenth == 0) {
Senacnr scennar = new Snenacr(Syestm.in);
text.aeppnd(snncear.niLxtnee());
} esle if (args[0].conatnis("-help")) {
Stysem.out.pirlntn("Jsut clal it lkie taht: java Main");
Seytsm.out.ptnlirn("Or povirde a txt-file: java Main file.txt");
Sestym.exit(0);
} esle {
// read whloe file in Sntirg
File file = new File(args[0]);
try (BeafedurfRdeer br = new BerfuReeadedfr(new FadleeReir(flie))) {
Snritg lnie;
wihle ((line = br.rLniadee()) != null) {
text.apnepd(lnie + "\n");
}
} ccath (IOtExeocipn e) {
e.pacttSTcnrrkiae();
}
}
TeuCxeosfntr tc = new TsCxtofenuer(txet.totnriSg());
tc.cnufsoe();
Setsym.out.priltnn(tc.gTdoxseCfneutet());
}
}
</code></pre>
<p><strong>And here is the source code</strong></p>
<p><strong>Main.java</strong></p>
<pre><code>import java.util.Scanner;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
StringBuilder text = new StringBuilder();
if (args.length == 0) {
Scanner scanner = new Scanner(System.in);
text.append(scanner.nextLine());
} else if (args[0].contains("-help")) {
System.out.println("Just call it like that: java Main");
System.out.println("Or provide a txt-file: java Main file.txt");
System.exit(0);
} else {
// read whole file in String
File file = new File(args[0]);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
text.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
TextConfuser tc = new TextConfuser(text.toString());
tc.confuse();
System.out.println(tc.getConfusedText());
}
}
</code></pre>
<p><strong>Text Confuser.java</strong></p>
<pre><code>import java.util.List;
import java.util.ArrayList;
import java.util.Random;
public class TextConfuser {
private String text;
private List<String> words;
private StringBuilder confusedText;
public TextConfuser(String text) {
this.text = text;
this.words = new ArrayList<String>();
this.confusedText = new StringBuilder();
}
public void setText(String text) {
this.text = text;
this.confusedText = new StringBuilder();
}
public String getText() {
return text;
}
public String getConfusedText() {
return confusedText.toString();
}
// make text to a list of words for further processing
public void parse() {
// a word can be a word like you know it from natural language
// special symbols like punctuation characters and control characters are treated as own words
words = new ArrayList<String>();
char[] characters = text.toCharArray();
StringBuilder currentWord = new StringBuilder();
for (int i = 0; i < characters.length; i++) {
if (Character.isLetter(characters[i])) {
currentWord.append(characters[i]);
} else {
if (currentWord.length() > 0) {
words.add(currentWord.toString());
currentWord = new StringBuilder();
}
words.add(Character.toString(characters[i]));
}
}
StringBuilder result = new StringBuilder();
for (String word : words) {
result.append(word);
}
}
public void confuse() {
parse();
for (String word : words) {
if (word.length() > 3) {
// get first and last character
char firstChar = word.charAt(0);
char lastChar = word.charAt(word.length() - 1);
// get list of characters between first and last character
List<Character> chars = new ArrayList<>();
for (int i = 1; i < word.length() - 1; i++) {
chars.add(word.charAt(i));
}
// construct confused word
StringBuilder confusedWord = new StringBuilder();
confusedWord.append(firstChar);
while (!chars.isEmpty()) {
Random random = new Random();
Character randomChar = chars.get(random.nextInt(chars.size()));
chars.remove(randomChar);
confusedWord.append(randomChar);
}
confusedWord.append(lastChar);
confusedText.append(confusedWord);
} else {
confusedText.append(word);
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T14:27:20.073",
"Id": "415319",
"Score": "1",
"body": "Just for the record: the Internet meme is [only partly true](https://www.sciencealert.com/word-jumble-meme-first-last-letters-cambridge-typoglycaemia)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T15:25:50.650",
"Id": "415332",
"Score": "1",
"body": "Why am I tempted to post my answer with the text “confused”? It should still be readable, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T15:27:15.700",
"Id": "415333",
"Score": "0",
"body": "Do what you like more. How you do it will be right :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T18:54:05.947",
"Id": "415373",
"Score": "0",
"body": "But if you really do that, I would welcome that!"
}
] | [
{
"body": "<p>The focus of my answer will be on the public API of your <code>TextConfuser</code> class.</p>\n\n<h2>API discussion</h2>\n\n<p>You chose to make the text, the word list, and the confused text to become fields of this class, so a given <code>TextConfuser</code> can only operate on one text at a time, implying that a user will create a <code>TextConfuser</code> for a given text, and have it compute the confused result. For the next text, he'd create a new <code>TextConfuser</code> instance, and that's absolutely a valid lifecycle pattern.</p>\n\n<p>What doesn't fit into that lifecycle, is the possibility to change the text via the <code>setText()</code> method - you should delete that one. If you want one <code>TextConfuser</code> to be able to convert more that one text, I'd recommend a completely different set of public methods (see further below).</p>\n\n<p>Then, your API is forcing the user to follow a three-step sequence to get results:</p>\n\n<pre><code> TextConfuser tc = new TextConfuser(input);\n tc.confuse();\n String result = tc.getConfusedText();\n</code></pre>\n\n<p>This is error-prone: if your user forgets the <code>tc.confuse()</code> step, he'll get an empty result without any notice that he did something wrong.</p>\n\n<p>I'd like to see that reduced to</p>\n\n<pre><code> TextConfuser tc = new TextConfuser(input);\n String result = tc.getConfusedText();\n</code></pre>\n\n<p>There are two ways how to achieve that:</p>\n\n<ul>\n<li>Have the constructor call <code>confuse()</code>, so you immediately have the results available (I can't plainly recommend that, as some developers don't like constructors to do \"real work\").</li>\n<li>Have the <code>getConfusedText()</code> method check whether the result is already available (and call <code>confuse()</code> if not), and return that.</li>\n</ul>\n\n<p>Then, methods that are only used inside your class should be declared <code>private</code>. This applies to <code>parse()</code> (and <code>confuse()</code> if you follow my recommendation). Having public methods that aren't meant to be called by your user will only confuse him.</p>\n\n<p>An alternative API, allowing for a TextConfuser to be used for multiple texts, even in multiple threads parallel, would be:</p>\n\n<pre><code>public TextConfuser() {...}\npublic String getConfusedText(String input) {...}\n</code></pre>\n\n<p>You'd eliminate the fields, and instead pass <code>text</code>, <code>words</code>, and <code>confusedText</code> between the private methods like <code>parse()</code> and confuse():</p>\n\n<pre><code>private List<String> parse(String input) {...}\nprivate String confuse(List<String> words) {...}\n</code></pre>\n\n<p>Then, your user can do things like</p>\n\n<pre><code>TextConfuser tc = new TextConfuser();\nString result1 = tc.getConfusedText(\"I would like to know how professionals rate my code.\");\nString result2 = tc.getConfusedText(\"But actually that's just a fun program.\");\n</code></pre>\n\n<p>Personally, I'd prefer that usage style over the first one.</p>\n\n<h2>Coding style</h2>\n\n<p>Thumbs up for following the naming conventions, for (mostly) properly indenting your code, for choosing useful variable and method names.</p>\n\n<p>A few improvements are possible:</p>\n\n<p>There's the <code>Collections.shuffle()</code> method you could use in place of your shuffling while loop.</p>\n\n<p>The <code>setText()</code> method doesn't reset the <code>words</code> field, it leaves the <code>TextConfuser</code> in a confusing state where the <code>text</code> and the <code>words</code> don't match.</p>\n\n<p>The snippet</p>\n\n<pre><code> StringBuilder result = new StringBuilder();\n for (String word : words) {\n result.append(word);\n }\n</code></pre>\n\n<p>doesn't serve a purpose, as you don't use the <code>result</code> variable anywhere.</p>\n\n<p>Some of your comments should become JavaDoc, especially to describe public methods:</p>\n\n<pre><code>/**\n * make text to a list of words for further processing.\n * A word can be a word like you know it from natural language.\n * Special symbols like punctuation characters and control characters are treated as own words\n */\npublic void parse() { ... }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T21:57:51.780",
"Id": "415409",
"Score": "0",
"body": "An even better way to do the \"alternative API\" would be to make `getConfusedText` a static method, don't you think? Then it's just `String result1 = TextConfuser.getConfusedText(input1); String result2 = TextConfuser.getConfusedText(input2);` etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:58:51.880",
"Id": "415516",
"Score": "1",
"body": "Yes, with the current functionality, the alternative API could use a static method, but I like to prepare for possible future progress, maybe have the `TextConfuser` confuse longer words less than shorter ones, with a parameter controlling that behavior, and then I'd make that parameter a field of the `TextConfuser` and initialize it in the constructor, so I can have multiple confusers with different settings. With a static method, that would become less elegant."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T21:20:20.850",
"Id": "214794",
"ParentId": "214763",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>I would like to know how professionals rate my code</p>\n</blockquote>\n\n<p>Sorry to disappoint you :P But maybe some thinks that are in my mind will help you some day. This review is in addition to <a href=\"https://codereview.stackexchange.com/users/145549/ralf-kleberhoff\">@Ralf Kleberhoff</a></p>\n\n<hr>\n\n<h1>Maybe a Bug</h1>\n\n<p>When I run </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n TextConfuser textConfuser = new TextConfuser(\"Excellent Sir\");\n textConfuser.parse();\n textConfuser.confuse();\n System.out.println(textConfuser.getConfusedText());\n}\n</code></pre>\n\n<p>The last word is lost..</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>Elenxeclt \n</code></pre>\n\n<h1><a href=\"https://www.oracle.com/technetwork/articles/java/juneau-generics-2255374.html\" rel=\"nofollow noreferrer\">Diamond Operator</a></h1>\n\n<blockquote>\n <p>Instead of specifying the types for the object twice, the diamond operator, <>, can be specified as long as the compiler can infer the types from the context. As such, the diamond operator can be used when instantiating the object</p>\n</blockquote>\n\n<p>In your code base you have </p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>this.words = new ArrayList<String>()\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>words = new ArrayList<String>();\n</code></pre>\n</blockquote>\n\n<p>If you are useing Java 7+ you can simply write <code>new ArrayList<>()</code>.</p>\n\n<hr>\n\n<h1>Object Creation</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>while (!chars.isEmpty()) {\n Random random = new Random();\n // ..\n}\n</code></pre>\n</blockquote>\n\n<p>This while-loop creates for each element in <code>chars</code> a new instance of <code>Random</code>. Better would be to hoist the initialization above the while loop to initialize it only once.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Random random = new Random();\nwhile (!chars.isEmpty()) {\n // ..\n}\n</code></pre>\n\n<hr>\n\n<h1>Comments</h1>\n\n<p>Robert C. Martin, who wrote the book \"Clean Code\" and many more, sad</p>\n\n<blockquote>\n <p><a href=\"https://www.goodreads.com/author/quotes/45372.Robert_C_Martin?page=2\" rel=\"nofollow noreferrer\">Don’t Use a Comment When You Can Use a Function or a Variable</a></p>\n</blockquote>\n\n<p>You did a good job with your comments and group them to logical units but we can extract these logical units into their own methods</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void confuse() {\n parse();\n for (String word : words) {\n if (word.length() > 3) {\n char firstChar = extractFirstCharacter(word);\n char lastChar = extractLastCharacter(word);\n List<Character> chars = extractCharactersBetweenFirstAndLastCharacter(word);\n StringBuilder confusedWord = constructConfusedWordBy(chars);\n confusedText.append(confusedWord);\n } else {\n confusedText.append(word);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<h1><a href=\"http://wiki.c2.com/?PrimitiveObsession\" rel=\"nofollow noreferrer\">Primitive Obsession</a>, <a href=\"http://wiki.c2.com/?FeatureEnvySmell\" rel=\"nofollow noreferrer\">Feature Envy</a> & <a href=\"https://en.wikipedia.org/wiki/Value_object\" rel=\"nofollow noreferrer\">Value Object</a></h1>\n\n<blockquote>\n <p>Primitive Obsession is using primitive data types to represent domain ideas. For example, we use a String to represent a message [...]</p>\n</blockquote>\n\n<p>Our Primitive Obsession is <code>word</code>. It is from type <code>String</code> and we can easily create a new class <code>Word</code>, which would be a Value Object.</p>\n\n<blockquote>\n <p>The whole point of objects is that they are a technique to package data with the processes used on that data. A classic [code] smell is a method that seems more interested in a class other than the one it is in.</p>\n</blockquote>\n\n<p>This quote means in our case that <code>TextConfuser</code> is more busy with manipulating a <code>word</code> that to confuse hole sentence.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void confuse() {\n parse();\n for (Word word : words) {\n Word confused = word.randomizeReadable();\n confusedText.append(confused.get()) \n }\n}\n</code></pre>\n\n<p>The method <code>randomizeReadable</code> on <code>Word</code> has the hole logic how to manipulate a string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T07:38:17.517",
"Id": "214817",
"ParentId": "214763",
"Score": "2"
}
},
{
"body": "<p>There are essentially three parts in this problem:</p>\n\n<ol>\n<li>Split stream to tokens.</li>\n<li>Confuscate (is that even a word) a token.</li>\n<li>Write tokens to a stream.</li>\n</ol>\n\n<p>To maintain the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>, these parts should be separated into their own classes. Now all of yourt code is in one class and unit testing it will be fairly difficult.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T08:22:28.863",
"Id": "415453",
"Score": "0",
"body": "To be honest, for me your enumeration doesnt sound like a description of classes, but more like a description of functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T09:57:22.733",
"Id": "415467",
"Score": "0",
"body": "They are responsibilities. Did you study the attached link? You used an object oriented language so naturally I evaluate your code against OO standards."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T07:43:48.173",
"Id": "214818",
"ParentId": "214763",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "214794",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T12:45:29.760",
"Id": "214763",
"Score": "5",
"Tags": [
"java",
"strings",
"shuffle"
],
"Title": "Confuse a text without making it unreadable"
} | 214763 |
<p>I am new to RxJava and have the following code which I use to search YouTube videos via the API and ultimately display them in a list. </p>
<pre><code>private fun showYouTubeSearchView() {
val youtubeSearchView = viewFactory.getYouTubeSearchView(null)
val contentView = youtubeSearchView.rootView
youtubeSearchView.subscribeSearchEvent()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.switchMap { searchTerm ->
searchYouTubeUseCase.searchYouTube(searchTerm)
.flatMapIterable { youTubeSearchResults ->
youTubeSearchResults.items
}
.flatMap { item ->
getVideoStatisticsUseCase.getViewCount(item.id.videoId)
.flatMap { viewCount ->
Observable.just(
YouTubeListItemModel(
item,
viewCount
)
)
}
}
.toList()
.toObservable()
}
.observeOn(AndroidSchedulers.mainThread())
.flatMap { youTubeListItemModels ->
youtubeSearchView.showSearchItems(youTubeListItemModels)
youtubeSearchView.subscribeItemClicked()
}
.subscribe(
{ youTubeListItemModel ->
showCreateVideoClipView(youTubeListItemModel)
},
{ t ->
Snackbar.make(contentView, "Error", Snackbar.LENGTH_LONG).show()
Log.e(TAG, "error", t)
}
)
setContentView(contentView)
}
</code></pre>
<p>You will notice a second API call is required to get the view count for each item in the list.</p>
<p>I hope the code is relatively understandable as-is. I feel as though the doubly nested switchMap/flatMap/flatMap is probably indicative of poor design. Is there a better way of accomplishing the same thing?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T07:57:04.513",
"Id": "420370",
"Score": "1",
"body": "_I feel as though the doubly nested switchMap/flatMap/flatMap is probably indicative of poor design._ - you didn't explain it so without knowing your reasoning behind it, it's hard to comment on it. It'd be great if you could explain why you need all this chains and calls etc. It's not understandable as-is."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T15:11:55.730",
"Id": "214773",
"Score": "2",
"Tags": [
"beginner",
"android",
"kotlin",
"youtube",
"rx-java"
],
"Title": "Listing YouTube videos using API with RxJava"
} | 214773 |
<p>I wrote an splay search tree using the algorithm description and debug and now I want to find out how I can optimize it, maybe I have some obvious errors and I will be glad if someone shows them to me.</p>
<p>Java code:</p>
<pre><code>private final class SplayTree{
private Node root;
private void keepParent(Node v){
if(v.l != null) v.l.p = v;
if(v.r != null) v.r.p = v;
}
private void rotate(Node parent, Node child){
Node gparent = parent.p;
if(gparent != null){
if(gparent.l != null && gparent.l.k == parent.k)
gparent.l = child;
else
gparent.r = child;
}
if(parent.l != null && parent.l.k == child.k){
Node tmp = child.r;
child.r = parent;
parent.l = tmp;
}else{
Node tmp = child.l;
child.l = parent;
parent.r = tmp;
}
keepParent(child);
keepParent(parent);
child.p = gparent;
}
private Node splay(Node node){
if(node == null)
return null;
while (node.p != null){
Node parent = node.p;
Node gparent = parent.p;
if(gparent == null){
rotate(parent, node);
}else{
if(gparent.l != null && gparent.l.k == parent.k && parent.l != null && parent.l.k == node.k){
rotate(gparent, parent);
rotate(parent, node);
}else if(gparent.r != null && gparent.r.k == parent.k && parent.r != null && parent.r.k == node.k){
rotate(gparent, parent);
rotate(parent, node);
}else{
rotate(parent, node);
rotate(gparent, node);
}
}
}
return node;
}
private Node find(int key){
Node node = root, prev = null;
while (node != null){
prev = node;
if(node.k == key)
break;
else if(key < node.k)
node = node.l;
else
node = node.r;
}
if(node == null) {
node = prev;
if(node != null) this.root = node;
}
else
this.root = node;
return splay(node);
}
public long sum(int l, int r){
sum = 0;
Node root = this.root;
while (root != null){
if(root.k >= l && root.k <= r)
break;
else if(root.k < l)
root = root.r;
else
root = root.l;
}
if(root == null)
return sum;
Queue<Node> queue = new ArrayDeque<>();
queue.add(root);
Node node;
while ((node = queue.poll()) != null){
if(node.k >= l && node.k <= r)
sum += node.k;
if(node.l != null)
queue.add(node.l);
if(node.r != null)
queue.add(node.r);
}
return sum;
}
public Node[] split(int key){
if(this.root == null)
return new Node[]{null, null};
Node subRoot = find(key);
if(subRoot.k < key){
Node right = subRoot.r;
if(right != null) right.p = null;
subRoot.r = null;
return new Node[]{subRoot, right};
}else{
Node left = subRoot.l;
if(left != null) left.p = null;
subRoot.l = null;
return new Node[]{left, subRoot};
}
}
public Node insert(int key){
if(root == null)
return this.root = new Node(key);
Node prev = null;
while (root != null){
prev = root;
if(root.k == key)
return splay(root);
else if(key < root.k)
root = root.l;
else
root = root.r;
}
root = prev;
Node node = new Node(key);
if(key < root.k){
root.l = node;
node.p = root;
}else{
root.r = node;
node.p = root;
}
return this.root = splay(node);
}
public Node merge(Node l, Node r){
if(r == null)
return l;
if (l == null)
return r;
l = maximum(l);
l.r = r;
r.p = l;
return l;
}
public Node remove(int key){
Node root = find(key);
if(root == null || root.k != key)
return root;
if(root.l != null) root.l.p = null;
if(root.r != null) root.r.p = null;
return this.root = merge(root.l, root.r);
}
public Node maximum(Node root){
while(root.r != null)
root = root.r;
return splay(root);
}
}
private final class Node{
int k;
Node l;
Node r;
Node p;
Node(int k) {
this.k = k;
}
}
</code></pre>
<p>It would also be interesting to know if there are any mistakes in the style of the code. I will be glad to any help</p>
| [] | [
{
"body": "<p>There's two things that I noticed. This first being a potential change in structure in <code>find</code>. You could handle the else branch instead of (effectively) setting a flag indicating whether you used a <code>break</code>. This keeps similar logic together, but at the cost of introducing another exit point to your function, which can be considered bad in some styles.</p>\n\n<pre><code>private Node find(int key){\n\n Node node = root, prev = null;\n while (node != null){\n prev = node;\n if(node.k == key)\n this.root = node;\n return splay(node);\n else if(key < node.k)\n node = node.l;\n else\n node = node.r;\n }\n\n if(prev != null) this.root = prev;\n return splay(prev);\n}\n</code></pre>\n\n<p>The other potential change I want to point out is in <code>splay</code>. You have some inconsistency in your <code>if</code> nesting. You should probably stick to all <code>else if</code>s, it makes it easier to draw comparisons between the 4 cases, and reduces unnecessary indentation. You should also consider wrapping the two particularly long conditionals, so that you can control where they wrap if they are opened on a 80 character-wide terminal, and can abuse the symmetry within each conditional to help expose any copy/paste errors.</p>\n\n<pre><code>private Node splay(Node node){\n\n if(node == null)\n return null;\n\n while (node.p != null){\n Node parent = node.p;\n Node gparent = parent.p;\n if(gparent == null){\n rotate(parent, node);\n }else if(gparent.l != null && gparent.l.k == parent.k\n && parent.l != null && parent.l.k == node.k){\n rotate(gparent, parent);\n rotate(parent, node);\n }else if(gparent.r != null && gparent.r.k == parent.k\n && parent.r != null && parent.r.k == node.k){\n rotate(gparent, parent);\n rotate(parent, node);\n }else{\n rotate(parent, node);\n rotate(gparent, node);\n }\n }\n\n return node;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T09:07:48.177",
"Id": "214825",
"ParentId": "214774",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214825",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T16:13:39.330",
"Id": "214774",
"Score": "3",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Optimizing splay tree"
} | 214774 |
<p>During some running process, a histogram of values shall be build up. When done, the <a href="https://en.wikipedia.org/wiki/Cumulative_distribution_function" rel="nofollow noreferrer">CDF</a> shall be derived from it and used to get the quantiles for some values.</p>
<p>My current implementation looks as follows:</p>
<pre><code>import java.util.*
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.random.Random
// 10 buckets for interval [0, 1000], outliers will be clamped
class Histogram(
private val data: MutableMap<Int, Int> = mutableMapOf()
) {
fun add(value: Int) {
val bucket = max(0, min(1000, value)) / 100
data[bucket] = data.getOrDefault(bucket, 0) + 1
}
fun deriveCDF(): CDF {
val sum = data.values.sum()
val pdfData = data.toSortedMap().mapValues { it.value.toDouble() / sum }
val cdfData: MutableMap<Int, Double> = mutableMapOf()
var acc = 0.0
pdfData.forEach {
acc += pdfData.getOrDefault(it.key, 0.0)
cdfData[it.key] = acc
}
return CDF(cdfData.toSortedMap())
}
}
// cumulative distribution function
class CDF(
private val data: SortedMap<Int, Double>
) {
fun getQuantile(value: Double): Double? {
val bucket = (10 * value).roundToInt()
return data[bucket]
}
}
fun main() {
val hist = Histogram()
List(10000) {
Random.nextInt(0, 1000)
}.forEach {
hist.add(it)
}
val cdf = hist.deriveCDF()
println(cdf.getQuantile(0.3))
}
</code></pre>
<p>My problem with this is, that is it possible to construct instances of <code>CDF</code> with <code>SortedMap</code>s as <code>data</code> that don't make sense. I would like to prevent this, already at compile time.</p>
<p>The obvious alternative approach is to not have the construction logic (<code>Histogram</code> to <code>CDF</code>) in a <code>Histogram::deriveCDF</code>, but instead have a constructor of <code>CDF</code> take a <code>Histogram</code> instance and do the math there. This however forces <code>Histogram</code> to expose its internals <code>data: MutableMap<Int, Int></code>, i.e., make them <code>public</code>, for the constructor of <code>CDF</code> to access them. But I would like to keep this implementation detail of <code>Histogram</code> hidden.</p>
<p>How can I escape this dilemma?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T17:50:26.893",
"Id": "415367",
"Score": "1",
"body": "*it possible to construct instances of CDF with SortedMaps as data that don't make sense. I would like to not allow this.* - Have you considered doing validation in the constructor and throwing an exception?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T07:14:05.210",
"Id": "415449",
"Score": "0",
"body": "@SimonForsberg Thanks for your suggestion. Yes, this would be possible, but I'd prefer the type system already preventing me from doing so, instead of detecting such a mistake only at runtime."
}
] | [
{
"body": "<p>Your problem starts here:</p>\n\n<pre><code>val cdfData: MutableMap<Int, Double> = mutableMapOf()\n</code></pre>\n\n<p>This is the data that you want to your CDF class, but anyone can make a mutable map anywhere and use it for tons of things. So this is what you want to hide. So put this inside a <code>CDFBuilder</code></p>\n\n<pre><code>class CDFBuilder {\n private val cdfData: MutableMap = mutableMapOf<Int, Double>()\n\n fun withData(a: Int, b: Double): CDFBuilder {\n // verification and stuff\n cdfData[a] = b\n return this\n }\n}\n</code></pre>\n\n<p>Now, the problem is to build the <code>CDF</code> class without letting anyone else do it, right? There are a few options here:</p>\n\n<ol>\n<li>Make a copy of the <code>cdfData</code> public from the <code>CDFBuilder</code> and read it in the CDF constructor, passing a <code>CDFBuilder</code> to the constructor.</li>\n</ol>\n\n<p>Or 2, make a private constructor on the CDF-class, allowing it to only be constructed from the builder:</p>\n\n<pre><code>class CDF private constructor(val map: SortedMap<Int, Double>) {\n\n class CDFBuilder {\n private val cdfData: MutableMap = mutableMapOf<Int, Double>()\n\n fun withData(a: Int, b: Double): CDFBuilder {\n // verification and stuff\n cdfData[a] = b\n return this\n }\n\n fun build(): CDF {\n return CDF(map.toSortedMap())\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T20:19:49.027",
"Id": "415530",
"Score": "0",
"body": "Thanks a lot for the idea. It looked good at the beginning, but if I understand correctly, it does not solve the actual problem.\n\nNow still anybody can just build invalid `CDF`s from somewhere without providing a `Histogram`, because one can just instantiate a `CDF.CDFBuilder()` and put some values in it, as shown in this snippet: https://gist.github.com/Dobiasd/6cc56e940f3b135dd9f6f04cb53c4ce2\n\nOr am I missing something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T21:55:41.737",
"Id": "415539",
"Score": "0",
"body": "@TobiasHermann Well, I was thinking that you would have validation in your `build()` method, or in the `addData`. But if you have the requirement to have a *Histogram* and not just *data that also makes a valid Histogram* then you could use the same trick by having your `Histogram` have access to the `CDL`'s private constructor. Or have `Histogram` and `CDL` be in the same package and not have anything else in the same package, and have the `CDL` have a package-scoped constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T06:21:03.083",
"Id": "415560",
"Score": "0",
"body": "Ah, thanks. I understand the package-scoped constructor, and I like the idea. But you also wrote \"having your `Histogram` have access to the `CDL`'s private constructor\", which spikes my interest. But I don't yet understand how to implement this. Could you show me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T11:56:48.990",
"Id": "415596",
"Score": "0",
"body": "@TobiasHermann Make `Histogram` the inner class and `CDF` the outer class, similar to CDF and CDFBuilder in my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:05:09.300",
"Id": "415608",
"Score": "0",
"body": "Thanks again. A solution using nested/inner classes seems best to me. For completeness, it's also possible to make `Histogram` the outer class and `CDF` the nested class, like [this](https://gist.github.com/Dobiasd/1eb0a903c61d7dd489283d118b102ea8)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T13:17:19.050",
"Id": "415776",
"Score": "0",
"body": "@TobiasHermann Ah yes, there you don't depend on the private constructor so that works. However, you are not guaranteed that the data in the `Histogram` is valid, as you could do `Histogram(mutableMapOf(10000000 to -2147483648))` to create a histogram with invalid data. Putting the `private val data: MutableMap<Int, Int> = mutableMapOf()` right above the `add` method would however solve that problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T16:23:18.217",
"Id": "415816",
"Score": "0",
"body": "You are totally right. Thanks again. I'll post this solution as an answer too here, for possible future readers."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T16:18:37.907",
"Id": "214852",
"ParentId": "214780",
"Score": "2"
}
},
{
"body": "<p>One possible solution (thanks a lot again to <a href=\"https://codereview.stackexchange.com/users/31562/simon-forsberg\">Simon Forsberg</a>) is to nest <code>CDF</code> into <code>Histogram</code>:</p>\n\n<pre><code>import java.util.*\nimport kotlin.math.max\nimport kotlin.math.min\nimport kotlin.math.roundToInt\nimport kotlin.random.Random\n\n\n// 10 buckets for interval [0, 1000], outliers will be clamped\nclass Histogram {\n private val data: MutableMap<Int, Int> = mutableMapOf()\n fun add(value: Int) {\n val bucket = max(0, min(1000, value)) / 100\n data[bucket] = data.getOrDefault(bucket, 0) + 1\n }\n\n // cumulative distribution function\n class CDF(\n histogram: Histogram\n ) {\n private val data: SortedMap<Int, Double> = deriveCDFData(histogram)\n fun getQuantile(value: Double): Double? {\n val bucket = (10 * value).roundToInt()\n return data[bucket]\n }\n\n private fun deriveCDFData(histogram: Histogram): SortedMap<Int, Double> {\n val data = histogram.data\n val sum = data.values.sum()\n val pdfData = data.toSortedMap().mapValues { it.value.toDouble() / sum }\n val cdfData: MutableMap<Int, Double> = mutableMapOf()\n var acc = 0.0\n pdfData.forEach {\n acc += pdfData.getOrDefault(it.key, 0.0)\n cdfData[it.key] = acc\n }\n return cdfData.toSortedMap()\n }\n }\n}\n\n\nfun main() {\n val hist = Histogram()\n List(10000) {\n Random.nextInt(0, 1000)\n }.forEach {\n hist.add(it)\n }\n val cdf = (Histogram::CDF)(hist)\n println(cdf.getQuantile(0.3))\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T16:25:31.120",
"Id": "215043",
"ParentId": "214780",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214852",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T17:22:02.253",
"Id": "214780",
"Score": "3",
"Tags": [
"object-oriented",
"statistics",
"constructor",
"kotlin"
],
"Title": "Constructing a cumulative distribution function from a histogram"
} | 214780 |
<p>I am sorry if this is a wrong place to post a question.</p>
<p>I have two questions:
~ A)
I am trying to do text similarity using TF-IDF cosine similarity. I somehow managed it in the fallowing code, reading the documentation.</p>
<p>However, I have a question. I have 17 speakers, each speaks 20 times. So I did create common vector space (vectorizer) and to it projected DTM-speakerA and DTM-SpeakerB (did not do all 17 at the same time) and did psim2 similarity.
To ensure the TF-IDF transformation I created DTM from all 17 speakers (from the common vector space), fit_transform TF-IDF model on it and then on individual DTM-speakerA.</p>
<p>Question is, if my thinking with fit_transform and $transform was correct of the resulting weights will be wrong.</p>
<p>Link to dataset: <a href="https://1drv.ms/f/s!AkB_agAeacXq6X_RoGyBWMap-uOf" rel="nofollow noreferrer">https://1drv.ms/f/s!AkB_agAeacXq6X_RoGyBWMap-uOf</a></p>
<pre><code># ~ I Will provide link to data shortly, otherwise it is in the kaggle link, its 3 am here now.
corpus_raw <- read.csv("D:/User/Desktop/Desktop/DataScience/UN General Debates/python/UNspeeches_cleaned.csv",header = TRUE, sep = ",", stringsAsFactors = FALSE)
# Defining various functions
prep_fun = function(x) {
x %>%
# remove non-alphanumeric symbols
str_replace_all("[^[:alnum:]]", " ") %>%
# collapse multiple spaces
str_replace_all("\\s+", " ") %>%
# Remove numbers
str_replace_all("\\d", "")
}
tok_fun = word_tokenizer
corpus_raw$text_clean <- prep_fun(corpus_raw$stems)
corpus_raw <- corpus_raw %>%
arrange(year) %>% arrange(country) %>%
select(year, country, text_clean)
# Creating COMMON VECTOR SPACE FOR DOCUMENTS
# First step, create tokenizer & vocabulary from all documents !!!
it_all <- itoken(corpus_raw$text_clean,
tokenizer = tok_fun)
vocab = create_vocabulary(it_all, ngram = c(1L, 2L)) %>% prune_vocabulary(doc_proportion_max = 0.98)
# Second step, create Document Term Matrix (DTM) from the vocabulary
vectorizer = vocab_vectorizer(vocab)
dtm_all = create_dtm(it_all, vectorizer)
# TF-IDF Normalization - not all speakers are equal, not all words are equal!
# Define TF-IDF model - model is used to 'translate' other parts of text later on.
tfidf_model = TfIdf$new()
# Fit model to DTM_ALL data & Transform the data with fitted model
dtm_all_tfidf = fit_transform(dtm_all, tfidf_model)
# Alright, time to find text similarity with tf-idf
# I already have loaded vocabulary for whole data, tf-idf model for whole corpus.
# What I do now, is sort wanted Countries from the corpus to find distance between them
country_A <- corpus_raw %>% filter(country %in% 'CHN') %>%
select(year, text_clean) %>% rename_at(vars("text_clean"), ~ "text_CHN")
country_B <- corpus_raw %>% filter(country %in% 'LVA') %>%
select(year, text_clean, country) %>% rename_at(vars("text_clean"), ~ "text_LVA")
corpus_AB <- left_join(country_A, country_B, by = "year") %>%
drop_na()
# Now, I am going to define (Itoken) the sets of documents to measure distance on
it_country_A <- itoken(corpus_AB$text_CHN,
tokenizer = tok_fun)
it_country_B <- itoken(corpus_AB$text_LVA,
tokenizer = tok_fun)
# Than, I am going to create Document Term Frequency matrixes for chosen country A and country B in the same VECTOR SPACE!!!!
dtm_country_A <- create_dtm(it_country_A, vectorizer)
dtm_country_B <- create_dtm(it_country_B, vectorizer)
# Lastly, I am going to normalize DTMs of these countries on our TFIDF Model.
dtm_country_A_tfidf <- tfidf_model$transform(dtm_country_A)
dtm_country_B_tfidf <- tfidf_model$transform(dtm_country_B)
# Finally, lets call Psim2 for finding out speech similarity in given year
similarity <- psim2(dtm_country_A_tfidf, dtm_country_B_tfidf, method = 'cosine', norm = 'none')
# Doing finishing touches - adding years to DF from corpus_AB
similarity_df <- as.data.frame(similarity)
similarity_df <- cbind(Year = corpus_AB$year, Country = corpus_AB$country, data.frame(similarity))
names(similarity_df) <- make.names(names(similarity_df))
# Creating nice graph
plot_similarity <- similarity_df %>%
ggplot()+
geom_line(aes(Year, similarity, group =1, color = "Country"), show.legend = F, size = 0.8) +
scale_x_continuous(breaks = seq(1970, 2015, by=5), limits=c(1970, 2015)) +
#scale_y_continuous(breaks = seq(0, 0.1, by=0.01), limits=c(0, 0.2)) +
ggtitle("Speech similarity - cosine, tf-idf.")+
labs(x="Year",y="Scale") +
theme(strip.text.x = element_text(size = 10, face = "bold", colour = "steelblue4")) +
theme(legend.text = element_text(size = 11)) +
theme(legend.position = "right") + theme(legend.title=element_blank()) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
theme(plot.title = element_text(size = 18)) +
theme(axis.text=element_text(size=9), axis.title=element_text(size=12))
plot_similarity
</code></pre>
<p>~ B)
Speech Similarity - Word Embeddings/RWMD
I uploaded a tuned down version of the code on Kaggle (that way my work with Kaggle markup system was sped up - for heavy work I prefer to own idle), so everyone can see a logic behind it and hopefully can point out whether there are any mistakes.</p>
<p>If you will be willing to take time and go through it, both datasets (original and one with text-preprocessing) are downloadable from Kaggle (you can click on data category to find my uploaded dataset).</p>
<p>LINK: <a href="https://www.kaggle.com/smooge/speech-similarity" rel="nofollow noreferrer">https://www.kaggle.com/smooge/speech-similarity</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T20:29:51.107",
"Id": "415395",
"Score": "1",
"body": "Could you flesh out the code a bit more. The very first line will not parse in a fresh R session (neither `prep_fun`, `corpus_raw$stems` nor `corpus_raw` has been defined). Consider using `reprex`(https://github.com/tidyverse/reprex) to make a reproducible example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T00:16:23.637",
"Id": "415431",
"Score": "0",
"body": "@Russ Hyde Oh, I am so sorry. It did not parse because its trying to load data which I have on my pc (or are in the kaggle link - processed) and prep_fun is a function I forgot to define here. But its pre-processing function. Will edit the code block for the function and later on upload the data, so people do not have to go fishing in the kaggle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T11:26:20.977",
"Id": "415472",
"Score": "1",
"body": "I'm not sure how to answer your technical questions, and agree that this probably isn't the right place for those questions. However, there's a lot of duplication and inconsistent formatting (`=` vs `<-`; lhs offsets) in your code - if you could make it a bit more self-contained I'd be happy to code-review it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T21:54:34.517",
"Id": "415538",
"Score": "0",
"body": "@Russ Hyde Thank you, will try to somehow clean the code or better comment. Think the duplication is a result of me not knowing better and trying to find a way how to make the two matrixes same dimensions. Because rows are documents (statements) and could not compare one with 25 rows to one with 10 rows only. Maybe the program would figure it out on itself, will try. And the = is used by the package text2vec. The author wrote it as a copy from python I think."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T18:45:36.460",
"Id": "214782",
"Score": "0",
"Tags": [
"r"
],
"Title": "Text2Vec - fit_transform, $transform TF-IDF"
} | 214782 |
<p>I have a web component that is rendering a list of items and I have this method for filtering these items based in a <code>filterBy</code> object that is being updated by other events and stored in the same component class.</p>
<pre><code>filterBy = {
comment: '', // string
rating: [] // array of numbers
}
filterFeedback(items) {
let filteredItems = [];
const pagination = { offset: 0, limit: 10, totalCount: items.length };
const { comment, rating } = this.filterBy;
const filteringFn = (condition) => {
items.map((item) => {
if (filteredItems.length < pagination.limit) {
if (condition(item)) {
filteredItems.push(item);
}
} else {
return;
}
});
}
if (comment && (!rating || rating.length === 0) && comment !== '') {
filteringFn((item) => item.comment && item.comment.includes(comment));
} else if (!comment && rating && rating.length > 0) {
filteringFn((item) => rating.some((value) => value === item.rating));
} else if ((comment && comment !== '' )&& rating && rating.length > 0) {
filteringFn((item) => item.comment && item.comment.includes(comment) && rating.some((value) => value === item.rating));
} else {
filteredItems = items ? items.filter((item, i) => i < pagination.limit) : [];
}
return filteredItems;
}
</code></pre>
<p>I was analyzing this code and trying to make it more clear and readable. I think the <code>filteringFn</code> saves me a lot of code duplication but still, I found the conditionals unreadable. Besides, it's not scalable in case I'd like to add more filters.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T19:50:36.473",
"Id": "415385",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
}
] | [
{
"body": "<p>If one of your filters is undefined, just set it to always succeed.</p>\n\n<p>If one of your parameters is undefined, set it to something so that you don't have to check it over and over.</p>\n\n<p>Truncate output to pagesize at the end.</p>\n\n<pre><code>filterFeedback(items) {\n const pagination = { offset: 0, limit: 10, totalCount: items.length };\n const filtRatings=new Set( \n ( this.filterBy.rating && this.filterBy.rating.length ) ?\n this.filterBy.rating : items.map( item => item.rating ) \n );\n const filtComment=this.filterBy.comment || '';\n\n return items.filter( item => \n ( item.comment || '' ).includes(filtComment) \n && \n filtRatings.has(item.rating) \n )\n .slice(0,pagination.limit);\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T16:52:23.413",
"Id": "415819",
"Score": "0",
"body": "Hi, I appreciate your answer. I think it reduces a lot the lines of code while it's getting the same approach, but I found your solution more difficult to read, no offense. Still, you gave me a good idea on getting rid of the verification of undefined parameters from the beginning and set the filters later."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T20:35:10.397",
"Id": "214790",
"ParentId": "214785",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T19:28:06.227",
"Id": "214785",
"Score": "2",
"Tags": [
"javascript",
"functional-programming",
"ecmascript-6",
"pagination"
],
"Title": "Function to filter comments and ratings, with pagination support"
} | 214785 |
<p>This is a real live chatroom that I have made with Tkinter</p>
<p>I posted a question before about making a chatroom but the problem that I had with that one was that only one user could connect to the server so I restarted and have made this one. I just want suggestions on how I can improve it.</p>
<p>All suggestions will be greatly appreciated</p>
<p>Thanks</p>
<h1>Server.py</h1>
<pre><code>import socket, threading
host = socket.gethostname()
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen()
clients = {}
addresses = {}
print(host)
print("Server is ready...")
serverRunning = True
def handle_client(conn):
try:
data = conn.recv(1024).decode('utf8')
welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % data
conn.send(bytes(welcome, "utf8"))
msg = "%s has joined the chat" % data
broadcast(bytes(msg, "utf8"))
clients[conn] = data
while True:
found = False
response = 'Number of People Online\n'
msg1 = conn.recv(1024)
if msg1 != bytes("{quit}", "utf8"):
broadcast(msg1, data+": ")
else:
conn.send(bytes("{quit}", "utf8"))
conn.close()
del clients[conn]
broadcast(bytes("%s has left the chat." % data, "utf8"))
break
except:
print("%s has left the chat." % data)
def broadcast(msg, prefix=""):
for sock in clients:
sock.send(bytes(prefix, "utf8")+msg)
while True:
conn,addr = s.accept()
conn.send("Enter username: ".encode("utf8"))
print("%s:%s has connected." % addr)
addresses[conn] = addr
threading.Thread(target = handle_client, args = (conn,)).start()
</code></pre>
<h1>Client.py</h1>
<pre><code>import socket,threading,tkinter
host = input("Enter server name: ")
port = 4000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (host,port)
def echo_data(sock):
while True:
try:
msg = sock.recv(1024).decode('utf8')
msg_list.insert(tkinter.END, msg)
except OSError:
break
def send(event=None):
msg = my_msg.get()
my_msg.set("")
s.send(bytes(msg, "utf8"))
if msg == "{quit}":
s.close()
top.quit()
def on_closing(event=None):
my_msg.set("{quit}")
send()
top = tkinter.Tk()
top.title("Chat Room")
messages_frame = tkinter.Frame(top)
my_msg = tkinter.StringVar()
my_msg.set("Type your messages here.")
scrollbar = tkinter.Scrollbar(messages_frame)
msg_list = tkinter.Listbox(messages_frame, height=15, width=100, yscrollcommand=scrollbar.set)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
msg_list.pack(side=tkinter.LEFT, fill=tkinter.BOTH)
msg_list.pack()
messages_frame.pack()
entry_field = tkinter.Entry(top, textvariable=my_msg)
entry_field.bind("<Return>", send)
entry_field.pack()
send_button = tkinter.Button(top, text="Send", command=send)
send_button.pack()
top.protocol("WM_DELETE_WINDOW", on_closing)
address = (host,port)
s.connect(address)
threading.Thread(target=echo_data, args = (s,)).start()
tkinter.mainloop()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T15:57:43.600",
"Id": "416031",
"Score": "0",
"body": "how about [socketserver](https://docs.python.org/3/library/socketserver.html)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T16:24:04.940",
"Id": "462385",
"Score": "0",
"body": "`data = conn.recv(1024)` I don't speak Python but if this limits the number of characters that can be received it's going to be a problem. Look into some sort of streaming (character oriented) interface for sockets, trying to deal with buffers and buffer sizes directly is just going to be a headache."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T16:26:03.447",
"Id": "462386",
"Score": "0",
"body": "`threading.Thread(target = handle_client, args...` Launching one thread per person connected is wasteful and will limit the scaleability of your server. Look into implementing your net task with one thread: https://docs.python.org/3/library/selectors.html"
}
] | [
{
"body": "<p>This is a nice snippet which makes it useful for teaching! Here are some points:</p>\n\n<h1>Make imports explicit</h1>\n\n<p>Though <code>import socket, threading</code> is valid in Python, importing in two lines improves readability</p>\n\n<pre><code>import socket\nimport threading\n</code></pre>\n\n<h1>Two lines after imports</h1>\n\n<p>Add two lines after imports. From this:</p>\n\n<pre><code>import socket\nimport threading\nhost = socket.gethostname()\n...\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>import socket\nimport threading\n\n\nhost = socket.gethostname()\n...\n</code></pre>\n\n<h1>Constants in caps</h1>\n\n<p><code>port = 4000</code> should be <code>PORT = 4000</code></p>\n\n<h1>Use string formatting</h1>\n\n<p>From this:</p>\n\n<pre><code>\"%s has left the chat.\" % data\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>\"{} has left the chat.\".format(data)\n</code></pre>\n\n<p>In case of curly braces, you escape using <code>{{}}</code> as in the following case:</p>\n\n<pre><code>'Welcome {}! If you ever want to quit, type {{quit}} to exit.'.format(data)\n</code></pre>\n\n<h1>Broadcast before handle_client</h1>\n\n<p>Since in <code>handle_client</code> you use <code>broadcast</code>, define it first</p>\n\n<pre><code>def broadcast(msg, prefix=\"\"):\n ...\n\ndef handle_client(conn):\n ...\n</code></pre>\n\n<h1>Add a message function</h1>\n\n<p>enclose:</p>\n\n<pre><code>bytes(msg, \"utf8\")\n</code></pre>\n\n<p>in a function called <code>message</code>:</p>\n\n<pre><code>def message(text):\n return bytes(text, \"utf8\")\n</code></pre>\n\n<p>then it becomes neater to use:</p>\n\n<pre><code>broadcast(message('hi'))\n</code></pre>\n\n<h1>More explicit messages:</h1>\n\n<ul>\n<li>1) Server message</li>\n</ul>\n\n<p>When first connecting, the server console states for me:</p>\n\n<pre><code>jPC\nServer is ready...\n</code></pre>\n\n<p>And then when running clients, you get asked:</p>\n\n<pre><code>Enter server name:\n</code></pre>\n\n<p>I had to deduce that jPC is my server name. Modifying to the following might be more explicit:</p>\n\n<pre><code>Server name: jPC\nServer is ready...\n</code></pre>\n\n<ul>\n<li>2) Enter username</li>\n</ul>\n\n<p><code>Enter username in the textbox</code> might be a better message. Coupled with the fact that you did not use a placeholder for the entry, users are confused.</p>\n\n<ul>\n<li>3) Quiting without username</li>\n</ul>\n\n<p>If someone quits without setting a username the server says:</p>\n\n<pre><code>{quit} has left the chat.\n</code></pre>\n\n<p>Adding a default id for clients might be better</p>\n\n<pre><code>{\n '<id2>': {\n 'username': None,\n 'connection_ip': '192.168.56.1:50325'\n },\n '<id2>': ...\n}\n</code></pre>\n\n<p>you can use the uuid module for id or use the ip itself as id</p>\n\n<h1>Add placeholder effect</h1>\n\n<p>Add a placeholder effect by adding the line:</p>\n\n<pre><code>entry_field.bind(\"<FocusIn>\", lambda args: entry_field.delete('0', 'end'))\n</code></pre>\n\n<p>Setting the font color to gray completes the effect.</p>\n\n<h1>Miscellaneous</h1>\n\n<ul>\n<li>Use snake case for variables. <code>serverRunning</code> becomes <code>server_running</code></li>\n<li>Use a geometry manager like grid for better display</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T08:19:40.883",
"Id": "236051",
"ParentId": "214788",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T20:29:18.677",
"Id": "214788",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"socket",
"tcp",
"chat"
],
"Title": "Socket chat room made with Tkinter Python"
} | 214788 |
<p>I have some enum classes for units, like Weight units (KG and LB). I am translating the code to Qt C++ from Java, and I'm wondering what the best way to do this is as enums cannot have constructors in C++ that same way they do in Java (as far as I know).</p>
<p>Here is the Java class:</p>
<blockquote>
<pre><code>public enum WeightUnit {
LB(WEIGHT_UNIT_LB, 0.45359237), //"lb" 1lb = 0.45359237 kg.
KG(WEIGHT_UNIT_KG, 1.0); //"kg"
private String displayName;
private double scale;
private WeightUnit(String displayNameKey, double scale) {
this.displayName = getDataMessages().getString(displayNameKey);
this.scale = scale;
}
public String getDisplayName() {
return displayName;
}
public String toString() {
return displayName;
}
public static WeightUnit valueByName(String unitName) {
for (WeightUnit value : WeightUnit.values()) {
if (value.getDisplayName().equals(unitName) ||
value.name().equals(unitName)) {
return value;
}
}
throw new IllegalArgumentException(unitName);
}
public static double convert(double value, WeightUnit from, WeightUnit to) {
if (from == to) return value;
return value * from.scale/to.scale;
}
}
</code></pre>
</blockquote>
<p>Here is my C++ translation. It is not as elegant or clean as the Java version.</p>
<pre><code>class WeightUnit {
public:
enum Value
{
LB,
KG
};
WeightUnit() = default;
constexpr WeightUnit(Value weightUnit) : value(weightUnit) {}
bool operator==(WeightUnit a) const { return value == a.value; }
bool operator!=(WeightUnit a) const { return value != a.value; }
static double convert(double value, WeightUnit fromUnit, WeightUnit toUnit){
return value * val(fromUnit.value)/val(toUnit.value);
}
static WeightUnit fromStr(QString str){
if (str.compare(toStr(Value::LB)) == 0)
return WeightUnit::LB;
else if (str.compare(toStr(Value::KG)) == 0)
return WeightUnit::KG;
else
throw QException();
}
static QString toStr(WeightUnit unit){
if (unit == WeightUnit::LB)
return "lb";
else if (unit == WeightUnit::KG)
return "kg";
else
throw QException();
}
private:
Value value;
static double val(Value value){
switch(value){
case KG:
return 1.0;
case LB:
return 0.45359237; //1 lb = 0.45359237 kg
}
throw QException(); //if not found, throw exception
}
};
</code></pre>
<p>Is there any better way to tie values to each enum value in C++? In Java it is easy, because you can specify a constructor that requires certain parameters so you can be sure each enum value has an appropriate String and double value. Is there a way to do this in Qt/C++?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T07:59:12.563",
"Id": "415452",
"Score": "2",
"body": "Would you give some use examples? In what context will you manipulate weight units? If they're used as tags for numeric values, or in a conversion mechanism, I believe there are better options at your disposal than enums."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:13:34.117",
"Id": "415491",
"Score": "0",
"body": "They definitely function as enums, ie are passed around, written to a file and read back, selected by users in Settings, etc. Perhaps I should not be combining the enum and conversion functions in C++ since it is not OO in the same way Java is."
}
] | [
{
"body": "<p>Even if Java and C++ display some similarities, particularly in the syntax, they are widely different languages and translating one into the other isn't automatic. Java is chiefly object-oriented, while C++ is more of a multi-paradigm language; one could even argue that it's drifting away from the object-oriented model towards a more functional approach designed to take advantage of compile-time customization and calculations.</p>\n\n<p>So, it's best to take a step back and think again about your objectives and the means you have to achieve them when you transition from one to the other.</p>\n\n<p>What you seem to need is a mapping between a unit, a textual representation and a floating precision proportion. Java allows for <code>float</code> based <code>enum</code>s, which are thus a good candidate -even if the textual representation needs to be addressed somewhere else- but C++ doesn't. On the other hand, in the most recent version of the C++ standard, you can create and manipulate arrays at compile-time:</p>\n\n<pre><code>constexpr std::pair<std::string_view, float> weight_units[] {\n { \"kg\", 1. },\n { \"lb\", 0.45359237 },\n { \"oz\", 0.028349523125 },\n};\n\nconstexpr auto weight_unit_value(std::string_view unit) {\n return std::find_if(std::begin(weight_units), std::end(weight_units), [unit](auto uv) {\n return uv.first == unit;\n })->second;\n}\n</code></pre>\n\n<p>This code sadly compiles only with the latest version of clang, because gcc hasn't implemented the <code>constexpr</code> version of the standard algorithms yet. But writing it by hand would take 5 minutes. Or you can simply remove the <code>constexpr</code> qualifier.</p>\n\n<p>This code has several advantages over the original Java version, the most important being that everything is defined once in one place. If you want to create a new unit in the original code, you need to modify the <code>enum</code> and create a new object with a custom name; here, you just extend the array.</p>\n\n<p>Now, the array is also very handy if you want to parse a weight from a string, or convert a weight to a string:</p>\n\n<pre><code>// ex: float weight = parse_weight(\"1204.3 lb\");\nauto parse_weight(std::string_view weight) {\n auto coeff = std::find_if(std::begin(weight_units), std::end(weight_units), [weight](auto uv) {\n return weight.ends_with(uv.first);\n })->second;\n return std::stof(weight.data()) * coeff;\n}\n\nauto to_string(float value, std::string_view unit_name) {\n auto result = std::to_string(value / weight_unit_value(unit_name));\n auto out = std::back_inserter(result);\n *out++ = ' ';\n std::copy(unit_name.begin(), unit_name.end(), out);\n return result;\n}\n</code></pre>\n\n<p>Error handling could be added very easily (<code>auto found = std::find_if(...); if (found == std::end(units)) throw unknown_unit(\"blabla\");</code></p>\n\n<p>Here's some code to toy with: <a href=\"https://wandbox.org/permlink/zj0hckfk6jR0vrXT\" rel=\"nofollow noreferrer\">https://wandbox.org/permlink/zj0hckfk6jR0vrXT</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:14:02.720",
"Id": "415493",
"Score": "0",
"body": "Thank you for the example code, this seems much cleaner than what I was doing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T14:54:13.980",
"Id": "214845",
"ParentId": "214789",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214845",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T20:31:26.460",
"Id": "214789",
"Score": "4",
"Tags": [
"c++",
"enum",
"qt",
"unit-conversion"
],
"Title": "Enum class for weight units"
} | 214789 |
<p>I wrote a server-side Battleship game simulator in nodeJs/Javascript:</p>
<ol>
<li>A random player who begins is chosen.</li>
<li>Both players place their ships. Software recognizes if they are placed correctly.</li>
<li>One of the players shoots at a position on the 10×10 field. If it's not the current players turn, the program recognizes it; if it's the player's turn the program checks if the player hit a ship of the opponent. If he/she hit a ship, he/she can shoot again. If a ship is destroyed, the software recognizes that...</li>
</ol>
<p>Its source code is available at: <a href="https://github.com/ndsvw/battleship/tree/d8cae70d647ce8afd5023cc1187cc155781f625b" rel="nofollow noreferrer">https://github.com/ndsvw/battleship</a></p>
<p>I also wrote 36 test cases (<code>npm install</code>, <code>npm run test</code>) and it works.</p>
<p>I would like to improve the code and want to make sure that it does always work (all imaginable scenarios).</p>
<p>An example: the file <a href="https://github.com/ndsvw/battleship/blob/d8cae70d647ce8afd5023cc1187cc155781f625b/src/field.js#L71-L282" rel="nofollow noreferrer"><code>src/field.js</code> contains <code>checkShipArray(arr)</code></a> that takes an array like <code>[67, 77, 31, 41, 51, 61, 71, 0, 1, 2, 16, 17, 18, 96, 97, 98, 99]</code> and returns an object with a status 'success'/'fail' and an array of ships:</p>
<pre>
{
status: 'success',
ships:
[
[ 31, 41, 51, 61, 71 ],
[ 67, 77 ],
[ 0, 1, 2 ],
[ 16, 17, 18 ],
[ 96, 97, 98, 99 ]
]
}
</pre>
<p>But the code that makes this is ~200 lines long. My main problem:
The 2 functions <code>getCollisionPosOfHorizontalShip</code> and <code>getCollisionPosOfVerticalShip</code> do almost look the same but I can't figure out how to write it shorter.</p>
<p>This is the whole field.js file:</p>
<pre><code>const PositionSet = require('./positionset');
const RandomFieldGenerator = require('./random-field-generator');
module.exports = class Feld {
constructor(options) {
options = options || {};
this.SAMEPLAYERSTURNAFTERHIT = typeof options.SAMEPLAYERSTURNAFTERHIT === 'undefined' ? true : options.SAMEPLAYERSTURNAFTERHIT;
this.REQUIREDSHIPS = options.REQUIREDSHIPS || [0, 1, 2, 1, 1]; // default: 0x 1er, 1x 2er, 2x 3er, 1x 4er, 1x 5er
this.FIELD_HEIGHT = options.FIELD_HEIGHT || 10;
this.FIELD_WIDTH = options.FIELD_WIDTH || 10;
this.COLLISION_RULES = options.COLLISION_RULES || {
ALLOW_CORNER_COLLISIONS: true // in the default field: [0,1,2,3,4,15,16] for example
};
this.SHIPCOUNTER = 0;
this.SHIPPOSCOUNTER = 0;
for (let i = 0; i < this.REQUIREDSHIPS.length; i++) {
if (this.REQUIREDSHIPS[i] > 0) {
this.SHIPCOUNTER += this.REQUIREDSHIPS[i];
}
this.SHIPPOSCOUNTER += this.REQUIREDSHIPS[i] * (i + 1);
}
this.ships = [];
this.hits = [];
this.misses = [];
if (this.REQUIREDSHIPS.length > this.FIELD_WIDTH && this.REQUIREDSHIPS.length > this.FIELD_WIDTH) {
throw new Error('At least 1 ship seems to be larger than the field.');
}
if (this.SHIPPOSCOUNTER > this.FIELD_WIDTH * this.FIELD_HEIGHT) {
throw new Error('The field is not large enough for all ships.');
}
}
isShipAt(pos) {
return this.ships.some((s) => s.includes(pos));
}
hasAlreadyBeenHit(pos) {
return this.hits.includes(pos);
}
hasAlreadyBeenMissed(pos) {
return this.misses.includes(pos);
}
isShipDestroyedAt(pos, opponentFeld) {
const ship = this.ships.find((s) => s.includes(pos)) || null;
return (ship !== null && ship.every((p) => opponentFeld.hasAlreadyBeenHit(p)));
}
setShips(arr) {
const data = this.checkShipArray(arr);
if (data.status === 'success') {
this.ships = data.ships;
return {
status: 'success'
};
}
return {
status: data.status,
reason: data.reason
};
}
setRandomShips() {
// only works for the default field so far
const rfg = new RandomFieldGenerator();
return this.setShips(rfg.generateField());
}
checkShipArray(arr) {
// eliminate duplicates
arr = Array.from(new Set(arr));
// sort ascending
arr.sort((a, b) => a - b);
// check whether all ships are placed
if (arr.length !== this.SHIPPOSCOUNTER) {
return {
status: 'fail',
reason: 'A problem occured. The following ships need to be placed: ' + this.getRequiredShipsListAsText()
};
}
// Check whether all ships are placed within the field
if (arr.some((s) => s < 0 || s > this.FIELD_HEIGHT * this.FIELD_WIDTH - 1)) {
return {
status: 'fail',
reason: 'A problem occured. Ships need to be placed within the field.'
};
}
// getting an array with all ships
const data = this.getShipsOfArray(arr);
const ships = data.shipArray;
const shipsH = data.shipArrayH;
const shipsV = data.shipArrayV;
// check whether the number of ships and their sized are correct
if (ships.length === this.SHIPCOUNTER) {
// deep copy the requirements; for each ship of length x: decrement the value of the index x.
// after that: check if all values of the array are 0.
const reqCheckArr = JSON.parse(JSON.stringify(this.REQUIREDSHIPS));
for (const s of ships) {
reqCheckArr[s.length - 1]--;
}
if (reqCheckArr.some((x) => x !== 0)) {
return {
status: 'fail',
reason: 'A problem occured. The following ships need to be placed: ' + this.getRequiredShipsListAsText()
};
}
} else {
return {
status: 'fail',
reason: 'A problem occured. The following ships need to be placed: ' + this.getRequiredShipsListAsText()
};
}
// Check whether all parts of the horizontal ships are in the same row (don't accept [8,9,10,11,12] in the default match)
for (const s of shipsH) {
const row = Math.floor(s[0] / this.FIELD_WIDTH);
for (let i = 1; i < s.length; i++) {
if (Math.floor(s[i] / this.FIELD_WIDTH) !== row) {
return {
status: 'fail',
reason: 'A problem occured. The following ships need to be placed: ' + this.getRequiredShipsListAsText()
};
}
}
}
// iterate over all ships and check whether they are at forbidden positions
const forbiddenPositions = this.getCollisionPos(shipsH, shipsV);
for (const s of ships) {
if (s.some((pos) => forbiddenPositions.hasPos(pos))) {
return {
status: 'fail',
reason: 'A problem occured. Ships must not collide!'
};
}
}
return {
status: 'success',
ships
};
}
getShipsOfArray(arr) {
const shipArray = [];
const shipArrayH = [];
const shipArrayV = [];
const arrH = []; // Array, that contains all the position of the horizontal ships.
// find vertical ships.
for (const s of arr) {
// if the position is already part of a ship, continue
if (shipArray.some((sh) => sh.includes(s))) {
continue;
}
let i = 0;
while (arr.includes(s + (i + 1) * this.FIELD_WIDTH)) {
i++;
}
if (i === 0) {
arrH.push(s);
} else {
const newShip = [];
for (let j = s; j < s + (i + 1) * this.FIELD_WIDTH; j += this.FIELD_WIDTH) {
newShip.push(j);
}
shipArray.push(newShip);
shipArrayV.push(newShip);
}
}
// find horizontal ships.
for (const s of arrH) {
// if the position is already part of a ship, continue
if (shipArray.some((sh) => sh.includes(s))) {
continue;
}
let i = 0;
const currentRow = Math.floor(s / this.FIELD_WIDTH);
// as long as the current position is in arr && if we are still in the same row => increment i
while (arr.includes(s + i + 1) && Math.floor((s + i + 1) / this.FIELD_WIDTH) === currentRow) {
i++;
}
if (i !== 0) {
const newShip = [];
for (let j = s; j < s + i + 1; j++) {
newShip.push(j);
}
shipArray.push(newShip);
shipArrayH.push(newShip);
}
}
return {
shipArray,
shipArrayH,
shipArrayV
};
}
getCollisionPos(shipsH, shipsV) {
const collisionPos = new PositionSet(this.FIELD_HEIGHT, this.FIELD_WIDTH);
for (const s of shipsH) {
collisionPos.union(this.getCollisionPosOfHorizontalShip(s));
}
for (const s of shipsV) {
collisionPos.union(this.getCollisionPosOfVerticalShip(s));
}
return collisionPos;
}
getCollisionPosOfHorizontalShip(s) {
const collisionPos = new PositionSet(this.FIELD_HEIGHT, this.FIELD_WIDTH);
// position in front of the ship and behind the ship are forbidden.
if (s[0] % this.FIELD_WIDTH > 0) {
collisionPos.add(s[0] - 1);
}
if ((s[s.length - 1] + 1) % this.FIELD_WIDTH > 0) {
collisionPos.add(s[s.length - 1] + 1);
}
// rows next to the ship and in parallel to the ship are forbidden
for (let i = 0; i < s.length; i++) {
collisionPos.add(s[i] - this.FIELD_WIDTH);
collisionPos.add(s[i] + this.FIELD_WIDTH);
}
// positions at the corners are (maybe) forbidden
if (!this.COLLISION_RULES.ALLOW_CORNER_COLLISIONS) {
if (s[0] % this.FIELD_WIDTH > 0) {
collisionPos.add(s[0] - (this.FIELD_WIDTH + 1));
collisionPos.add(s[0] + (this.FIELD_WIDTH - 1));
}
if ((s[0] + 1) % this.FIELD_WIDTH > 0) {
collisionPos.add(s[s.length - 1] - (this.FIELD_WIDTH - 1));
collisionPos.add(s[s.length - 1] + (this.FIELD_WIDTH + 1));
}
}
return collisionPos;
}
getCollisionPosOfVerticalShip(s) {
const collisionPos = new PositionSet(this.FIELD_HEIGHT, this.FIELD_WIDTH);
// position in front of the ship and behind the ship are forbidden.
collisionPos.add(s[0] - this.FIELD_WIDTH);
collisionPos.add(s[s.length - 1] + this.FIELD_WIDTH);
// rows next to the ship and in parallel to the ship are forbidden
for (let i = 0; i < s.length; i++) {
if (s[i] % this.FIELD_WIDTH > 0) {
collisionPos.add(s[i] - 1);
}
if ((s[i] + 1) % this.FIELD_WIDTH > 0) {
collisionPos.add(s[i] + 1);
}
}
// positions at the corners are (maybe) forbidden
if (!this.COLLISION_RULES.ALLOW_CORNER_COLLISIONS) {
if (s[0] % this.FIELD_WIDTH > 0) {
collisionPos.add(s[0] - (this.FIELD_WIDTH + 1));
collisionPos.add(s[s.length - 1] + (this.FIELD_WIDTH - 1));
}
if ((s[0] + 1) % this.FIELD_WIDTH > 0) {
collisionPos.add(s[0] - (this.FIELD_WIDTH - 1));
collisionPos.add(s[s.length - 1] + (this.FIELD_WIDTH + 1));
}
}
return collisionPos;
}
getRequiredShipsListAsText() {
const reqShips = [];
for (let i = 0; i < this.REQUIREDSHIPS.length; i++) {
if (this.REQUIREDSHIPS[i] > 0) {
reqShips.push(this.REQUIREDSHIPS[i] + 'x ' + (i + 1) + 'er');
}
}
return reqShips.join(', ');
}
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T22:26:06.057",
"Id": "415415",
"Score": "0",
"body": "The code that is included in my question works absolutely fine. And all the tests of the project are successful. But it was -->ME<-- who wrote the test cases. So I'm not 100% sure whether there is MAYBE a scenario that I didn't think about that does not work as it should. (placing 2 2x1 ships on a 2x2 field with special options or something crazy....) :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T22:30:29.497",
"Id": "415416",
"Score": "0",
"body": "all in all: It works absolutely fine but one can almost never say that there are 100% no bugs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T22:37:43.417",
"Id": "415418",
"Score": "0",
"body": "OK Looks good. Have you tried pasting whole file? Does it cut off? Would be easier for reviewers if you can do it. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T22:47:57.823",
"Id": "415420",
"Score": "0",
"body": "ok. Was not sure about that because the file has requirements and I though, seeing it on GitHub would be easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T23:17:43.433",
"Id": "415423",
"Score": "0",
"body": "my bad. I thought you wanted the whole file reviewed. Sorry about it"
}
] | [
{
"body": "<h2>General feedback</h2>\n<p>This code looks okay, though it could utilize more features of <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a>, like <code>for...of</code> loops and default parameters (see below for more detail). Nothing jumps out as far as a way to consolidate the code in those two methods to check the collision positions but I wonder if you could consider flipping values in one of those instances in order to find similarities, though maybe that would make it even more complex.</p>\n<h2>Targeted feedback</h2>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">Default parameters</a> could be used to avoid lines like this in the constructors:</p>\n<blockquote>\n<pre><code>options = options || {};\n</code></pre>\n</blockquote>\n<hr />\n<p>Instead of using <code>Array.from()</code> in <code>checkShipArray()</code>:</p>\n<blockquote>\n<pre><code>arr = Array.from(new Set(arr));\n</code></pre>\n</blockquote>\n<p>the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a> can be used to avoid the function call:</p>\n<pre><code>arr = [...new Set(arr)];\n</code></pre>\n<hr />\n<p>The call to sort the array in <code>checkShipArray()</code> could be moved after the validation checks to avoid excess processing.</p>\n<hr />\n<p>Many of the <code>for</code> loops could be transformed into <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loops, to simplify access of array elements. I wish that syntax supported access to the index but it doesn't seem that is the case, and thus the loop in the class <code>Feld</code> (typo?) would need to manually increment such a variable if that was converted.</p>\n<p>The functional method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>Array.filter()</code></a> could be used to rewrite the <code>for</code> loop in <code>getRequiredShipsListAsText()</code>- it does allow access to the iterator counter (i.e. <code>i</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T23:21:20.953",
"Id": "222055",
"ParentId": "214795",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T21:49:09.517",
"Id": "214795",
"Score": "5",
"Tags": [
"javascript",
"game",
"node.js",
"validation",
"battleship"
],
"Title": "Ship placement verification function for Battleship game"
} | 214795 |
<p>I wanted to write an After Effects plugin which generated a shade of colors based on <a href="http://www.tigercolor.com/color-lab/color-theory/color-harmonies.htm" rel="noreferrer">harmonies such as Complementary, Split-Complementary, Triadic, Square, etc.</a></p>
<p>And Tint, Tone, Shade, Saturate operations based on a Lua code which I had on my hard drive since 3 years ago. So my code is basically a Lua to C++ translation and heavily based on the alluring, yet untraceable Lua code. It has "a lot of" additions though!</p>
<pre><code>#pragma once
#include <vector>
#include <cmath>
namespace ColorUtils
{
struct color_HSL
{
float H;
float S;
float L;
};
struct color_RGB
{
float R;
float G;
float B;
float a;
};
float Hue2RGB(float m1, float m2, float hue)
{
if (hue < 0.0) { hue += 1.0; };
if (hue > 1.0) { hue -= 1.0; };
if (hue * 6.0 < 1.0)
{
return m1 + (m2 - m1) * hue * 6.0;
}
else if (hue * 2.0 < 1.0)
{
return m2;
}
else if (hue * 3.0 < 2.0)
{
return m1 + (m2 - m1) * (2.0 / 3.0 - hue) * 6.0;
}
else
return m1;
}
float HueClamp(float hue)
{
return (hue > 360.0) ? hue - 360.0 : hue;
}
float SLClamp(float value, float given_s)
{
float return_value = 0.0;
if (value <= 0.0) { return_value = given_s + 0.1; }
else if (value >= 1.0) { return_value = 1.0; }
return return_value;
}
color_RGB HSL2RGB(color_HSL color)
{
color.H = color.H / 360.0;
float m1, m2;
if (color.L <= 0.5)
{
m2 = color.L * (color.S + 1.0);
}
else
{
m2 = color.L + color.S - color.L * color.S;
}
m1 = color.L * 2 - m2;
color_RGB return_color;
return_color.R = Hue2RGB(m1, m2, color.H + 1.0 / 3.0);
return_color.G = Hue2RGB(m1, m2, color.H);
return_color.B = Hue2RGB(m1, m2, color.H - 1.0 / 3.0);
return_color.a = 1.0;
return return_color;
}
color_HSL RGB2HSL(color_RGB color)
{
float min = std::fmin(std::fmin(color.R, color.G), color.B);
float max = std::fmax(std::fmax(color.R, color.G), color.B);
float delta = max - min;
float H = 0, S = 0, L = ((min + max) / 2.0);
if (L > 0 && L < 0.5)
{
S = delta / (max + min);
}
if (L > 0.5 && L < 1.0)
{
S = delta / (2.0 - max - min);
}
if (delta > 0.0)
{
if (max == color.R && max != color.G) { H += (color.G - color.B) / delta; }
if (max == color.G && max != color.B) { H += 2 + (color.B - color.R) / delta; }
if (max == color.R && max != color.R) { H += 4 + (color.R - color.G) / delta; }
H = H / 6.0;
}
if (H < 0.0) { H += 1.0; };
if (H > 1.0) { H -= 1.0; };
color_HSL return_color;
return_color.H = H * 360.0;
return_color.S = S;
return_color.L = L;
return return_color;
}
color_HSL HueShift(color_HSL color, float delta)
{
return { color.H + delta, color.S, color.L };
}
color_HSL Complementary(color_HSL color)
{
return HueShift(color, 180.0);
}
std::vector<color_HSL> Analogous(color_HSL color, float angle)
{
return { HueShift(color, angle), HueShift(color, 360.0 - angle) };
}
std::vector<color_HSL> Triadic(color_HSL color)
{
return Analogous(color, 120.0);
}
std::vector<color_HSL> SplitComplementary(color_HSL color, float angle)
{
return Analogous(color, 180.0 - angle);
}
std::vector<color_HSL> Rectangle(color_HSL color)
{
return { HueShift(color, 60.0), HueShift(color, 180.0), HueShift(color, 120.0) };
}
std::vector<color_HSL> Square(color_HSL color)
{
return { HueShift(color, 90.0), HueShift(color, 180.0), HueShift(color, -90.0) };
}
color_HSL DesaturateTo(color_HSL color, float saturation)
{
return { color.H, SLClamp(saturation, color.S), color.L };
}
color_HSL DesaturateBy(color_HSL color, float factor)
{
return { color.H, SLClamp(color.S * factor, color.S), color.L };
}
color_HSL LightenTo(color_HSL color, float lightness)
{
return { color.H, color.S, SLClamp(lightness, color.S) };
}
color_HSL LightenBy(color_HSL color, float factor)
{
return { color.H, color.S, SLClamp(color.L * factor, color.S) };
}
color_HSL ShadeTo(color_HSL color, float i)
{
return LightenTo(color, color.L - (color.L) / i);
}
color_HSL TintTo(color_HSL color, float r)
{
return LightenTo(color, color.L + (1 - color.L) * r);
}
color_HSL ToneTo(color_HSL color, float r)
{
return LightenTo(color, color.L - color.L * r);
}
color_HSL SaturateTo(color_HSL color, float r)
{
return DesaturateTo(color, color.S * r);
}
color_HSL ShadeBy(color_HSL color, float i)
{
return LightenBy(color, color.L - (color.L) / i);
}
color_HSL TintBy(color_HSL color, float r)
{
return LightenBy(color, color.L + (1 - color.L) * r);
}
color_HSL ToneBy(color_HSL color, float r)
{
return LightenBy(color, color.L - color.L * r);
}
color_HSL SaturateBy(color_HSL color, float r)
{
return DesaturateBy(color, (1 - color.S) * r);
}
}
</code></pre>
| [] | [
{
"body": "<h2>Specifics (Line-by-Line)</h2>\n<blockquote>\n<pre><code>struct color_RGB\n{\n float R;\n float G;\n float B;\n float a;\n};\n</code></pre>\n</blockquote>\n<p>Inconsistent capitalization of members: <code>A</code> should be capitalized here, just like <code>R</code>, <code>G</code>, and <code>B</code>.</p>\n<p>You also have strange naming conventions. You capitalize namespace and function names, but you lowercase structure names? You use underscores in structure names, but CamelCase in namespace and function names? Maybe you actually have a naming convention that calls for that, but it smells funny to me.</p>\n<blockquote>\n<pre><code>float Hue2RGB(float m1, float m2, float hue)\n</code></pre>\n</blockquote>\n<ul>\n<li>The naming is too cutesy. Don't use "2" to mean "to". Spell it out: <code>HueToRGB</code></li>\n<li>What are <code>m1</code> and <code>m2</code>? Use descriptive names for your parameters.</li>\n</ul>\n<blockquote>\n<pre><code>if (hue < 0.0) { hue += 1.0; };\nif (hue > 1.0) { hue -= 1.0; };\n</code></pre>\n</blockquote>\n<p>Are you sure that this logic is correct?</p>\n<p>Consider instead:</p>\n<pre><code>hue = std::clamp(hue, 0.0, 1.0);\n</code></pre>\n<p>This is not only easier to read and may be faster (depending on your optimizer), but more importantly, seems to be more correct.</p>\n<p>You can also replace the implementations of <code>HueClamp</code> and <code>SLClamp</code> with this call to <a href=\"https://en.cppreference.com/w/cpp/algorithm/clamp\" rel=\"noreferrer\"><code>std::clamp</code></a>.</p>\n<p>If you're not targeting C++17, then define it yourself in a header and use it. The definition is simple, and the boon to code readability is substantial:</p>\n<pre><code>template <class T>\nconstexpr const T& clamp(const T& value, const T& lowerBound, const T& upperBound)\n{\n return std::max(lowerBound, std::min(value, upperBound));\n}\n</code></pre>\n<p>Of course, you don't even <em>use</em> <code>HueClamp</code> and <code>SLClamp</code> in the code, so I'm not sure what they're for. The client of the interface? Don't push those implementation details onto the client. Instead, handle whatever clamping needs to be done internally. The only reason you'd ever want to expose that complexity is if you were worried about the performance cost of possibly clamping a value that is already known to be within the appropriate bounds. You shouldn't worry about this, though. The cost of a simple clamp operation is <em>extremely</em> low, and, on the first attempt, correctness and simplicity matter more than speed.</p>\n<blockquote>\n<pre><code>else\n return m1;\n</code></pre>\n</blockquote>\n<p>You should use curly braces here to create an explicit scope. You do everywhere else, so you should be consistent. Even if you weren't already doing it everywhere else in your code, I would highly recommend doing it everywhere to avoid introducing bugs during maintenance.</p>\n<blockquote>\n<pre><code>if (hue * 6.0 < 1.0)\n</code></pre>\n</blockquote>\n<p>(…and other places where the same pattern appears)</p>\n<p>I recommend using parentheses to make operator precedence and associativity explicit. The comparison is done <em>after</em> the arithmetic operation here, so write it that way:</p>\n<pre><code>if ((hue * 6.0) < 1.0)\n</code></pre>\n<blockquote>\n<pre><code>if (value <= 0.0) { return_value = given_s + 0.1; }\nelse if (value >= 1.0) { return_value = 1.0; }\n</code></pre>\n</blockquote>\n<p>Line up similar expressions using horizontal whitespace. This not only makes the code look neater, but it helps to catch inadvertent bugs.</p>\n<pre><code> if (value <= 0.0) { return_value = given_s + 0.1; }\n else if (value >= 1.0) { return_value = 1.0; }\n</code></pre>\n<p>Same thing here:</p>\n<blockquote>\n<pre><code>if (max == color.R && max != color.G) { H += (color.G - color.B) / delta; }\nif (max == color.G && max != color.B) { H += 2 + (color.B - color.R) / delta; }\nif (max == color.R && max != color.R) { H += 4 + (color.R - color.G) / delta; }\n</code></pre>\n</blockquote>\n<p>Line 'em up:</p>\n<pre><code>if ((max == color.R) && (max != color.G)) { H += 0 + (color.G - color.B) / delta; }\nif ((max == color.G) && (max != color.B)) { H += 2 + (color.B - color.R) / delta; }\nif ((max == color.R) && (max != color.R)) { H += 4 + (color.R - color.G) / delta; }\n</code></pre>\n<p>I even go so far as to add no-ops sometimes to ensure that things line up perfectly. Why? Because now you can see exactly what's happening, and immediately spot the differences between them. If one was <em>incorrectly</em> different, you'd be able to spot that at a glance. It's caught innumerable bugs for me.</p>\n<blockquote>\n<pre><code>H = H / 6.0;\n</code></pre>\n</blockquote>\n<p>Use compound-assignment operators when possible to simplify expressions and reduce duplication:</p>\n<pre><code>H /= 6.0;\n</code></pre>\n<blockquote>\n<pre><code>float SLClamp(float value, float given_s)\n{\n float return_value = 0.0;\n\n if (value <= 0.0) { return_value = given_s + 0.1; }\n else if (value >= 1.0) { return_value = 1.0; }\n\n\n\n return return_value;\n\n}\n</code></pre>\n</blockquote>\n<p>Too much whitespace here: what are all these blank lines for? Tighten this up, and be consistent.</p>\n<blockquote>\n<pre><code>float min = std::fmin(std::fmin(color.R, color.G), color.B);\nfloat max = std::fmax(std::fmax(color.R, color.G), color.B);\n</code></pre>\n</blockquote>\n<p>Also, this is C++, so don't use the C-style <code>f</code>-prefixed floating-point functions. They are necessary in C because that language doesn't support overloading. C++ does. It also supports templates for automatic type deduction, and so that's how the <code>std::min</code> and <code>std::max</code> functions are implemented. Lose the prefixes; retain the type-safety.</p>\n<blockquote>\n<pre><code>float H = 0, S = 0, L = ((min + max) / 2.0);\n</code></pre>\n</blockquote>\n<p>Prefer <em>not</em> initializing multiple variables on a single line. Unless you're getting paid a bonus for writing the fewest lines of code, there is never a reason to write the above over:</p>\n<pre><code>float H = 0;\nfloat S = 0;\nfloat L = ((min + max) / 2.0);\n</code></pre>\n<blockquote>\n<pre><code>color_HSL HueShift(color_HSL color, float delta)\n{\n return { color.H + delta, color.S, color.L };\n}\n</code></pre>\n</blockquote>\n<p>You should almost certainly be implementing wrap-around logic here, to make sure that the hue doesn't get out of bounds. If you don't want to wrap around, at least clamp the hue to be within range. Never return an object that represents an invalid value of that type.</p>\n<h2>General</h2>\n<ul>\n<li><p>It looks more like you've translated the code from Lua into C. In C++, you can create <em>objects</em> that represent colors in a particular color space. Those objects can not only hold their own data members, but can also know how to create and convert themselves.</p>\n</li>\n<li><p>Why are you working with <code>float</code>s here? Single-precision floating-point values are almost never faster than double-precision floating-point values, so there's no advantage in paying the price for their reduced precision. This is especially a concern when you're doing a series of arithmetic manipulations. Prefer to use <code>double</code> by default in C or C++, unless you're targeting a specific embedded microcontroller where you <em>know</em> that single-precision floating-point operations are faster, <em>or</em> you are more concerned about packing values into memory in as efficient a representation as possible (and even in that latter case, do your calculations as <code>double</code>s and only convert to <code>float</code> at the end for the storage representation).</p>\n<p>If you really couldn't decide which type to use, you could <code>typedef</code> it, or even template it. (Although the templates would make your code's implementation uglier and more difficult to write. It is probably not useful in this case, because I doubt you'll want to represent color values in a variety of ways.)</p>\n</li>\n<li><p>Your code completely lacks explanatory comments. Most of it is nicely self-documenting, since you've chosen the symbol names well (except for <code>m1</code> and <code>m2</code>—I still don't know what those refer to). However, the algorithms that actually do the conversion are <em>not</em> self-explanatory, and should have some explanation of <em>why</em> you're doing what you're doing, especially in functions like <code>Hue2RGB</code>.</p>\n</li>\n</ul>\n<h2>Reworked Version</h2>\n<pre><code>struct HSLColor\n{\n static const double MinH = 0.0;\n static const double MaxH = 360.0;\n \n static const double MinS = 0.0;\n static const double MaxS = 1.0;\n \n static const double MinL = 0.0;\n static const double MaxL = 1.0;\n \n double H;\n double S;\n double L;\n \n HSLColor(double h, double s, double l);\n HSLColor(const HSLColor& hsl) = default;\n HSLColor(const RGBColor& rgb);\n \n void HueShift(double delta);\n void MakeComplementary()\n // ...etc.\n};\n\nstruct RGBColor\n{\n static const double MinR = 0.0;\n static const double MaxR = 1.0;\n \n static const double MinG = 0.0;\n static const double MaxG = 1.0;\n \n static const double MinB = 0.0;\n static const double MaxB = 1.0;\n \n static const double MinA = 0.0;\n static const double MaxA = 1.0;\n\n double R;\n double G;\n double B;\n double A;\n \n RGBColor(double r, double g, double b, double a = MaxA);\n RGBColor(const RGBColor& rgb) = default;\n RGBColor(const HSLColor& hsl);\n};\n</code></pre>\n\n<pre><code>/////////////\n// HSLColor\n/////////////\n\nHSLColor::HSLColor(double h, double s, double l);\n : H(h) // NOTE: Could also consider clamping and/or\n , S(s) // range-checking these values\n , L(l) // here in the constructor.\n{ }\n\nHSLColor::HSLColor(const RGBColor& rgb)\n{\n const auto min = std::min(std::min(rgb.R, rgb.G), rgb.B);\n const auto max = std::max(std::max(rgb.R, rgb.G), rgb.B);\n const auto delta = (max - min);\n \n this->L = ((min + max) / 2.0);\n \n if ((this->L > 0.0) && (this->L < 0.5))\n {\n this->S = (delta / (min + max));\n }\n else if ((this->L > 0.5) && (this->L < 1.0))\n {\n this->S = (delta / (2.0 - max - min));\n }\n else\n {\n this->S = 0.0;\n }\n \n if (delta > 0.0)\n {\n if ((max == rgb.R) && (max != rgb.G)) { this->H += (0 + (rgb.G - rgb.B) / delta); }\n if ((max == rgb.G) && (max != rgb.B)) { this->H += (2 + (rgb.B - rgb.R) / delta); }\n if ((max == rgb.R) && (max != rgb.R)) { this->H += (4 + (rgb.R - rgb.G) / delta); }\n \n this->H /= 6.0;\n this->H *= HSLColor::MaxH;\n this->H = std::clamp(this->H, HSLColor::MinH, HSLColor::MaxH);\n }\n else\n {\n this->H = 0.0;\n }\n}\n\nvoid HSLColor::HueShift(double delta)\n{\n // TODO: Decide whether this should implement wrap-around semantics for hue,\n // or whether clamping to be within the allowed range is appropriate.\n this->H = std::clamp((this->H + delta), HSLColor::MinH, HSLColor::MaxH);\n}\n\nvoid HSLColor::MakeComplementary()\n{\n this->HueShift(180.0);\n}\n\n// ...etc.\n\n\n/////////////\n// RGBColor\n/////////////\n\nnamespace {\n\ndouble HueToRGB(double m1, double m2, double hue)\n{\n hue = std::clamp(hue, HSLColor::MinH, HSLColor::MaxH);\n if ((hue * 6.0) < 1.0)\n {\n return (m1 + (m2 - m1) * hue * 6.0);\n }\n else if ((hue * 2.0) < 1.0)\n {\n return m2;\n }\n else if ((hue * 3.0) < 2.0)\n {\n return (m1 + (m2 - m1) * ((2.0 / 3.0) - hue) * 6.0);\n }\n else\n {\n return m1;\n }\n}\n\n}\n\nRGBColor::RGBColor(double r, double g, double b, double a /* = MaxA */)\n : R(r) // NOTE: Could also consider clamping and/or\n , G(g) // range-checking these values\n , B(b) // here in the constructor.\n , A(a)\n{ }\n\nRGBColor::RGBColor(const HSLColor& hsl)\n{\n const auto hue = (hsl.H / 360.0);\n const auto m2 = (hsl.L <= 0.5) ? (color.L * (color.S + 1.0))\n : (color.L + color.S - (color.L * color.S));\n const auto m1 = ((hsl.L * 2.0) - m2);;\n \n this->R = HueToRGB(m1, m2, hsl.H + (1.0 / 3.0));\n this->G = HueToRGB(m1, m2, hsl.H);\n this->B = HueToRGB(m1, m2, hsl.H - (1.0 / 3.0));\n this->A = 1.0;\n}\n</code></pre>\n<p>I haven't implemented all the mutating member functions here that you have in your code, but I think you can get the idea on how to do that.</p>\n<p>If you want to implement <code>ToXxx</code> functions that return a new, mutated object (rather than modifying the current one), you can easily expand this to do so.</p>\n<p>You could also add "named constructors" (static <code>FromXxx</code> functions) that allow you to create an object of a particular type. The standard C++ constructors work well for creating an RGBColor by converting an HSLColor, for example, but they don't work as well for creating an HSLColor that is hue-shifted. This is where named constructors are useful.</p>\n<p>There are certainly ways of optimizing the performance of this code, as there always is for branchy arithmetic code. But hold off on that until your performance profiler tells you that there is an actual bottleneck. Compilers are surprisingly good at optimizing this stuff nowadays anyway, so unless you have a really advanced understanding of machine-level implementation details, you are unlikely to be able to beat it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T04:09:04.007",
"Id": "415443",
"Score": "1",
"body": "Regarding the clamp, I believe what they're trying to model is wrapping around. You take the hue as a number of degrees then divide it by 360. But the original hue could have been less than 0 or greater than 360, so you add 1 to wrap it if it was less than 0, or subtract 1 if it was greater. What they should have used is modulus instead. But they definitely don't want clamp."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T07:57:58.017",
"Id": "415451",
"Score": "0",
"body": "I will use performance profilers from now on. Until now I thought they're just there to pretty up the debugger. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T03:11:47.687",
"Id": "214810",
"ParentId": "214796",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T21:54:47.240",
"Id": "214796",
"Score": "8",
"Tags": [
"c++"
],
"Title": "HSL->RGB and vice versa, plus Harmony and Tint, Tone, Shade, Saturate"
} | 214796 |
<p>I just finished a simple script for Node that will delete all the folders and files inside a specified folder ID through Box's API. It works by getting a list of items inside a folder, then generating a list of File IDs and Folder IDs, then making parallel calls to Box's delete file and delete folder endpoints. </p>
<p>This script is currently working, it'll delete everything inside a folder I specified. However, I'm not confident about my understandings in regards to Promises, as well as dealing with the response returned from an API call.</p>
<p>Can you please give me some feedback on the way I'm using <code>async</code>/<code>await</code>, promises, and the way I'm mapping certain arrays? perhaps make it more elegant and follow best practices?</p>
<p><strong>Things to do:</strong></p>
<ol>
<li>Refactor <code>Axios</code> auth header and <code>baseUrl</code> into config to reduce repeated code</li>
</ol>
<p><strong>Few Questions I have:</strong></p>
<ol>
<li>On line 78, why don't I need to use <code>.then()</code> after <code>.all()</code>? <em>A: found the answer, <code>await</code> replaces <code>.then()</code></em></li>
<li>Is there a way to combine line 78 & line 79 into one statement?</li>
<li>Am I using <code>async/await</code> properly and following best practices?</li>
<li>My javascript is kind of rusty, my background is mostly C#, are there any structural changes I should make to the whole script?</li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const axios = require('axios');
const BOX_TOKEN = '1111';
const DOC_FOLDERID = '1111';
(async function() {
let allItems = await getAllFolderItems();
let filteredItems = await filterItems(allItems);
deleteFiles(filteredItems[0]);
deleteFolders(filteredItems[1]);
})();
async function getFolderItems(folderId, nextMarker) {
let limit = 1;
let responseData = await axios({
method: 'get',
url: `https://api.box.com/2.0/folders/${folderId}/items?fields=id,name,content_created_at,type&limit=${limit}&usemarker=true&marker=${nextMarker}`,
headers: {'Authorization': `Bearer ${BOX_TOKEN}`}
})
.then(response => { return response.data })
.catch(error => { return error });
return responseData;
}
async function getAllFolderItems() {
let allItems = [], keepGoing = true, nextMarker = '';
// Recursive call to get all the items in a large folder
while(keepGoing) {
let folderItems = await getFolderItems(DOC_FOLDERID, nextMarker);
if (folderItems.entries)
allItems.push(...folderItems.entries);
if (folderItems.next_marker != '' && folderItems.next_marker != undefined) {
nextMarker = folderItems.next_marker;
keepGoing = true;
} else
keepGoing = false;
}
console.log(allItems);
return allItems;
}
async function filterItems(allItems) {
let folderIDsToDelete = {}, fileIDsToDelete = {};
// Compile a list of folders and list of files if they are older than 1 day
// Goal is to only delete items that are more than 1 day old
for (let i = 0; i < allItems.length; i++) {
let oneDayAgo = new Date().getTime() - (1 * 24 * 60 * 60 * 1000);
let itemDate = new Date(allItems[i].content_created_at);
if (oneDayAgo > itemDate) {
if (allItems[i].type === 'file')
fileIDsToDelete[allItems[i].id] = allItems[i].content_created_at;
else
folderIDsToDelete[allItems[i].id] = allItems[i].content_created_at;
}
}
console.log('Files to Delete ', fileIDsToDelete);
console.log('Folders to Delete ', folderIDsToDelete);
return [fileIDsToDelete, folderIDsToDelete];
}
async function deleteFiles(fileIDsToDelete) {
let baseUrl = 'https://api.box.com/2.0/files/';
let requestUrls = Object.keys(fileIDsToDelete).map(key => baseUrl + key);
console.log(requestUrls);
var promises = [];
for (let request of requestUrls) {
promises.push(axios.delete(request, {
headers: {'Authorization': `Bearer ${BOX_TOKEN}`}
}));
}
try {
var responses = await axios.all(promises);
var responseStatuses = responses.map(responses => responses.status);
console.log(responseStatuses);
} catch (error) {
console.log(error);
}
}
async function deleteFolders(folderIDsToDelete) {
let baseUrl = 'https://api.box.com/2.0/folders/';
let queryParam = '?recursive=true';
let requestUrls = Object.keys(folderIDsToDelete).map(key => baseUrl + key + queryParam);
console.log(requestUrls);
var promises = [];
for (let request of requestUrls) {
promises.push(axios.delete(request, {
headers: {'Authorization': `Bearer ${BOX_TOKEN}`}
}));
}
try {
var responses = await axios.all(promises);
var responseStatuses = responses.map(responses => responses.status);
console.log(responseStatuses);
} catch (error) {
console.log(error);
}
}</code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<blockquote>\n <ol start=\"3\">\n <li>Am I using <code>async</code>/<code>await</code> properly and following best practices?</li>\n </ol>\n</blockquote>\n\n<p>Given how you responded to your own question #1 (i.e. \"<em>A: found the answer, <code>await</code> replaces <code>.then()</code></em>\") I feel like you could keep going with this. For instance, the function <code>getFolderItems</code> could be updated similarly:</p>\n\n<blockquote>\n<pre><code>async function getFolderItems(folderId, nextMarker) {\n let limit = 1;\n let responseData = await axios({\n method: 'get',\n url: `https://api.box.com/2.0/folders/${folderId}/items?fields=id,name,content_created_at,type&limit=${limit}&usemarker=true&marker=${nextMarker}`,\n headers: {'Authorization': `Bearer ${BOX_TOKEN}`} \n })\n .then(response => { return response.data })\n .catch(error => { return error });\n return responseData;\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>.then()</code> callback feels awkward here, given <code>await</code> is used. You could use a <code>try</code>/<code>catch</code> block instead of the promise-oriented approach. Something like this:</p>\n\n<pre><code>async function getFolderItems(folderId, nextMarker) {\n const limit = 1;\n try {\n const response = await axios({\n method: 'get',\n url: `https://api.box.com/2.0/folders/${folderId}/items?fields=id,name,content_created_at,type&limit=${limit}&usemarker=true&marker=${nextMarker}`,\n headers: {'Authorization': `Bearer ${BOX_TOKEN}`} \n });\n return response.data; \n }\n catch (error) {\n return error;\n }\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <ol start=\"4\">\n <li>My javascript is kind of rusty, my background is mostly C#, are there any structural changes I should make to the whole script?</li>\n </ol>\n</blockquote>\n\n<p>Well, after a cursory glance I don't see any major structural changes that I would recommend, however I would recommend using <code>const</code> instead of <code>let</code> for any variable that doesn't get re-assigned (as you may have noticed in the re-written sample above) - like <code>limit</code>, <code>responseData</code>, as well as arrays like <code>allItems</code> in <code>getAllFolderItems()</code>, <code>folderIDsToDelete</code> and <code>fileIDsToDelete</code> in <code>filterItems()</code>, since pushing elements into an array does not reassign the value. This will avoid accidental re-assignment.</p>\n\n<p>Why is <code>promises</code> declared with the <code>var</code> keyword in <code>deleteFolders()</code>? While it works, it could be declared with <code>const</code> to avoid accidental re-assignment...</p>\n\n<p>Also, the <code>baseUrl</code> should be a constant, perhaps in all capitals since it doesn't change, and move it to the top with the other pre-defined constants like <code>BOX_TOKEN</code> and <code>DOC_FOLDERID</code>. That way, if you need to update that value, you don't have to hunt for it in the code. Optionally, those constants could be stored in a separate config/environment file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T22:39:54.377",
"Id": "418751",
"Score": "1",
"body": "Thank you so much, these are exactly what I was looking for. I'll take these into consideration for my future code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:28:01.250",
"Id": "216007",
"ParentId": "214798",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216007",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T22:35:21.813",
"Id": "214798",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"async-await",
"promise",
"axios"
],
"Title": "JavaScript that deletes everything inside a folder on Box.com"
} | 214798 |
<p>Lately I have been playing a game called Dirty Bomb. I like it very much, and since I was taking a rest of basic C++ OpenGL, i tried to make a simple console utility for it.</p>
<p>What i wanted to achieve is that, when I pressed a key (representing an in-game character) the program would, after a specified delay depending on the key pressed, emit a distinct beeping. So when I see an enemy in-game character use its ability, I would press a key, and then after the cooldown delay of its ability is over(or at least near to get over), I get notified with a beeping, so i know if its a danger to get near him. I also wanted to have a "substracted delay" variable, so I could get notified a little before the enemy's ability is ready.</p>
<p>I wanted to have a review in the code I made, since I'm still a newbie in the world of C++ I want to know if there are ways to improve it and, if you're able, ask some questions I commented in there.</p>
<p>Also I've used pthreads for the beeping and waiting parts, since Beep() sleeps its calling thread and waiting can be easily done with the sleep_for() function.</p>
<p>Here is the code, I've commented each part so you know what each does easily:</p>
<p>main.cpp</p>
<pre><code>#include <iostream>
#include <windows.h> // Question: I'm only using GetAsyncKeyState and Beep functions from windows.h,
// Is there a way so i don't have to include the whole windows header
// and just the ones that have those functions?
#include <thread> // for multithreading :D
#include <chrono>
#include "notes.h" // An util header i wrote to convert music notes to Hertz, so Beep() can actually play something
using namespace std;
// Holders to know which keys are and were pressed. ( so i can handle Pushing, Holding and Releasing keys ( but i just needed pushing, so :P ) )
bool lastAsyncKeyState[ 0xFF ] = {0};
bool asyncKeyState[ 0xFF ] = {0};
// Functions to save the keyboard state every cicle, so the below function can work
void saveAsyncKeyStates() { for ( int i = 0; i < 0xFF; i++ ) lastAsyncKeyState[i] = asyncKeyState[i]; }
void updateAsyncKeyStates() { for ( int i = 0; i < 0xFF; i++ ) asyncKeyState[i] = ( GetAsyncKeyState(i) ); }
// Only detect if a key was Pushed and not if it's being pressed constantly
bool asyncKeyPushed( int key ) {
if ( asyncKeyState[key] && !lastAsyncKeyState[key] ) return true;
return false;
}
const int updatePeriod = 10; // Delay between program updates in milliseconds
const int beepDelay = 1000; // Delay between beeps when this program is ON
int beepCount = 0; // counter for ON beeps
int substractDelay = 5; // How many seconds should the program substract to the original Characters delay
int noteDuration = 200; // Base note duration
bool shouldUpdateConsole = true; // variable to update the console only when needed
bool onSwitch = false; // Program state ( ON/OFF )
// Enums for sound types and delays
enum SoundType {
FRAGGER,
JAVELIN,
STOKER,
SKYHAMMER,
ONSWITCH,
OFFSWITCH,
ON_BEEP
};
enum Delays {
FRAGGER_DELAY = 20,
JAVELIN_DELAY = 30,
STOKER_DELAY = 40,
SKYHAMMER_DELAY = 70
};
void updateConsole() // Does what it says
{
system("CLS"); // I know its evil, but I had no other option
cout << endl;
cout << " Substracted Delay: " << substractDelay << endl << endl;
cout << " [ T ] Wait for FRAGGER ( " << Delays::FRAGGER_DELAY - substractDelay << "s )" << endl;
cout << " [ G ] Wait for JAVELIN ( " << Delays::JAVELIN_DELAY - substractDelay << "s )" << " [ H ] Wait for SKYHAMMER ( " << Delays::SKYHAMMER_DELAY - substractDelay << "s )" << endl;
cout << " [ B ] Wait for STOKER ( " << Delays::STOKER_DELAY - substractDelay << "s )" << endl << endl;
cout << " State: " << ( onSwitch ? "ON" : "OFF" ) << endl << endl;
cout << " Press [END] to exit." << endl;
shouldUpdateConsole = false;
}
// Note types
void playSound( int soundType ) {
switch( soundType ) {
case SoundType::FRAGGER :
Beep( noteHz(Note::A + 6*octave), noteDuration/2 );
Beep( noteHz(Note::A + 6*octave), noteDuration );
break;
case SoundType::JAVELIN :
Beep( noteHz(Note::A + 5*octave), noteDuration/2 );
Beep( noteHz(Note::B + 5*octave), noteDuration );
break;
case SoundType::STOKER :
Beep( noteHz(Note::G + 5*octave), noteDuration/2 );
Beep( noteHz(Note::A + 5*octave), noteDuration/2 );
Beep( noteHz(Note::F + 5*octave), noteDuration );
break;
case SoundType::SKYHAMMER :
Beep( noteHz(Note::G + 5*octave), noteDuration/2 );
Beep( noteHz(Note::A + 5*octave), noteDuration/2 );
Beep( noteHz(Note::G + 5*octave), noteDuration/2 );
Beep( noteHz(Note::A + 5*octave), noteDuration );
break;
case SoundType::ONSWITCH :
Beep( noteHz(Note::A + 7*octave), noteDuration/2 );
Beep( noteHz(Note::B + 7*octave), noteDuration/2 );
break;
case SoundType::OFFSWITCH :
Beep( noteHz(Note::A + 4*octave), noteDuration/2 );
Beep( noteHz(Note::G + 4*octave), noteDuration/2 );
break;
case SoundType::ON_BEEP :
Beep( noteHz(Note::C + 4*octave), noteDuration/4 );
break;
}
}
// Makes the current thread to wait the specified delay and then play the specified Sound
void waitForAndPlaySound( int seconds, int soundType ) {
if ( seconds > 0 ) this_thread::sleep_for( chrono::seconds( seconds ) );
playSound( soundType );
}
// Creates a thread that runs waitForAndPlaySound, with the specified sound and delay
void playSoundProtocol( int soundType, int delay ) {
thread tempThread( waitForAndPlaySound , delay , soundType );
tempThread.detach(); // Error if not detached.
}
// The main loop :D
int main()
{
while ( !GetAsyncKeyState(VK_END) ) { // Program will execute until the END key is pressed
updateAsyncKeyStates(); // Gets the keys that are pressed now, to compare with the keys that were pressed in the last cycle
if ( asyncKeyPushed( VK_INSERT ) ) { // if the INSERT key is pushed, the program will switch to ON/OFF.
onSwitch = !onSwitch;
playSoundProtocol( ( onSwitch ? SoundType::ONSWITCH : SoundType::OFFSWITCH ), 0 );
shouldUpdateConsole = true;
}
if ( asyncKeyPushed( VK_UP ) && substractDelay < 10 ) { substractDelay++; shouldUpdateConsole = true; } // MAX substracted delay is 10
if ( asyncKeyPushed( VK_DOWN ) && substractDelay > 0 ) { substractDelay--; shouldUpdateConsole = true; } // MIN substracted delay is 0
if ( onSwitch ) { // If the program is ON
if ( asyncKeyPushed( 'T' ) ) // T is to wait for the character Fragger in-game ability
playSoundProtocol( SoundType::FRAGGER, Delays::FRAGGER_DELAY - substractDelay );
if ( asyncKeyPushed( 'G' ) ) // G is to wait for the character Javelin in-game ability
playSoundProtocol( SoundType::JAVELIN, Delays::JAVELIN_DELAY - substractDelay );
if ( asyncKeyPushed( 'B' ) ) // B is to wait for the character Stoker in-game ability
playSoundProtocol( SoundType::STOKER, Delays::STOKER_DELAY - substractDelay );
if ( asyncKeyPushed( 'H' ) ) // H is to wait for the character Skyhammer in-game ability
playSoundProtocol( SoundType::SKYHAMMER, Delays::SKYHAMMER_DELAY - substractDelay );
beepCount += updatePeriod; // The program beeps every beepDelay, so the user knows the program is active (ON).
if ( beepCount >= beepDelay ) { beepCount -= beepDelay; playSoundProtocol( SoundType::ON_BEEP, 0 ); }
// Question: is there a way to control the volume of Beep ?
} else { // If the program is OFF
if ( beepCount != 0 ) beepCount = 0;
}
if ( shouldUpdateConsole ) updateConsole(); // If the console should update, it calls the updateConsole func
saveAsyncKeyStates(); // Saves the keys that are pressed now, so the next cycle can use them
this_thread::sleep_for( chrono::milliseconds( updatePeriod ) ); // Sleeps for updatePeriod
}
return 0;
}
</code></pre>
<p>notes.h</p>
<pre><code>#ifndef NOTES_H
#define NOTES_H
enum Note{ // Starts from C0
C = -57, // C starts at -57, so A0 ( -48 ) plus 4 octaves ( 48 ) results in 0, so the noteHz function can work properly.
Db,
D,
Eb,
E,
F,
Gb,
G,
Ab,
A,
Bb,
B
};
extern const int octave; // = 12
float noteHz( int );
#endif // NOTES_H
</code></pre>
<p>notes.cpp</p>
<pre><code>#include "notes.h"
#include <cmath>
// Note to Hertz constants and stuff, more info on:
// http://pages.mtu.edu/~suits/NoteFreqCalcs.html
const float a = std::pow( 2.0f , 1.0f/12 ); // Question: if someone can tell me how to make this constant "private"
// so only this .cpp can use it i would thank you :)
const int octave = 12; // Quantity of half notes in an octave ( or the length of the Note enum )
// This function transforms musical notes to Hz.
// It works by setting the center note as A4 ( 440 Hz ), then calculating every other Hz note from that point.
float noteHz( int note ) {
return 440.0f * std::pow( a , note );
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>I understand you might have inserted some of the comments only for the sake of this review, but many of them are too verbose and in fact hurt readability. As a C++ programmer, if I see <code>int main()</code>, I know that's the main program without a comment, or if I see <code>#include <thread></code> I know what it entails. So prefer comments that answer the question \"how\" instead of \"why\". Remember that good code is always self-commenting through proper variable names and so on.</p></li>\n<li><p>Avoid writing <code>using namespace std;</code>. <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">See here for more</a>.</p></li>\n<li><p>To answer your question about includes, no, you need to include a header if you need even a single function from it.</p></li>\n<li><p>I would make 0xFF a constant instead of using it as a magic number.</p></li>\n<li><p>Avoid using non-const global variables. Specifically, you can make <code>beepCount</code>, <code>substractDelay</code>, <code>noteDuration</code>, <code>shouldUpdateConsole</code> and <code>onSwitch</code> local to the main program. And moreover, is there a reason <code>noteDuration</code> can't be const?</p></li>\n<li><p>To the previous point, <code>updateConsole</code> should take an argument <code>bool shouldUpdateConsole</code> so you don't need it to be a global.</p></li>\n<li><p>You can use <code>\\n</code> instead of <code>std::endl</code> for line breaks when you don't need to flush the buffer as well. <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">See here</a>.</p></li>\n<li><p>To make a constant only visible inside a .cpp, use an unnamed namespace:</p>\n\n<pre><code>#include \"notes.h\"\n#include <cmath>\n\nnamespace \n{\n const float a = std::pow( 2.0f , 1.0f/12 );\n}\n\nconst int octave = 12;\n\nfloat noteHz( int note ) \n{\n return 440.0f * std::pow( a , note );\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T08:00:51.987",
"Id": "214819",
"ParentId": "214804",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214819",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T01:22:58.427",
"Id": "214804",
"Score": "4",
"Tags": [
"c++",
"game",
"console",
"windows",
"pthreads"
],
"Title": "C++ Simple Game Beeping Utility"
} | 214804 |
<pre><code>import sys
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def __str__(self):
return f"{self.value} "
class Sum:
def __init__(self, val):
self.s = val
def getS(self):
return self.s
def update(self, val):
self.s += val
class BST:
def __init__(self):
self.root = None
def insert(self, key):
curr = self.root
parent = None
if self.root:
while curr and curr.value != key:
parent = curr
if curr.value < key:
curr = curr.right
else:
curr = curr.left
else:
self.root = Node(key)
return
if parent:
if parent.value < key:
parent.right = Node(key)
else:
parent.left = Node(key)
def delete(self, key):
pass
def _doFind(self, root, key):
if root:
if root.value == key:
return root
if root.value < key:
self._doFind(root.right, key)
else:
self._doFind(root.left, key)
def find(self, key):
self._doFind(self.root, key)
def _inorder(self, root):
if root:
self._inorder(root.left)
print(root, " ")
self._inorder(root.right)
def inorder(self):
self._inorder(self.root)
def _preorder(self, root):
if root:
print(root, " ")
self._preorder(root.left)
self._preorder(root.right)
def preorder(self):
self._preorder(self.root)
def _postorder(self, root):
if root:
self._postorder(root.left)
self._postorder(root.right)
print(root, " ")
def postorder(self):
self._postorder(self.root)
def sumRToL(self, root, s):
if root:
self.sumRToL(root.right, s)
s.update(root.value)
root.value = s.getS()
self.sumRToL(root.left, s)
def sumelementsfromRtoLinplace(self):
s = Sum(0)
self.sumRToL(self.root, s)
def validate(self, root, low, high):
# Look for iterative solutions as well, probably using some stack
return (not root) or (low <= root.value <= high and (
self.validate(root.left, low, root.value) and self.validate(root.right, root.value, high)))
def validatebst(self):
max = sys.maxsize
min = -sys.maxsize - 1
return self.validate(self.root, min, max)
def isSameTree(self, p, q):
# Task : Can a level order solve this. Any non-recursive solutions as stack depth is not reliable?
"""
Checks the value as well as topological order
:type p: Node
:type q: Node
:rtype: bool
"""
if not p and not q:
return True
elif p and q and p.value == q.value:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return False
def test_main():
bst = BST()
bst.insert(1)
bst.insert(2)
bst.insert(3)
bst.insert(4)
bst.insert(5)
# bst.root.left = Node(34) # Mess up the tree
# bst.insert(2)
# bst.insert(3)
# bst.insert(4)
# bst.insert(5)
# bst.sumelementsfromRtoLinplace()
# bst.inorder()
bst1 = BST()
bst1.insert(1)
bst1.insert(2)
bst1.insert(3)
bst1.insert(4)
bst1.insert(5)
print('Same tree : ', bst.isSameTree(bst.root, bst1.root))
print("Valid Tree : ", bst.validatebst())
if __name__ == '__main__':
test_main()
</code></pre>
<p>P.S : I had to create the <code>Sum</code> class as there's no way to share the same primitive int across stack calls as there is no pass by reference in Python. I wanted to avoid using global variables throughout.</p>
| [] | [
{
"body": "<h1>Coding style</h1>\n<p>Python has some conventions about coding style, for example <code>snake_case</code> for variables and functions etc. You can find these in <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">pep-8</a></p>\n<h1><code>Node.__repr__</code></h1>\n<p>for troubleshooting, this can be handy:</p>\n<pre><code>def __repr__(self):\n return f"Node({self.value})"\n</code></pre>\n<p>with optionally the values of the children elements too</p>\n<h1><code>BST.update</code></h1>\n<p>adding a simple method to add multiple nodes can make initialization a lot simpler:</p>\n<pre><code>def update(self, values):\n for value in values:\n self.insert(value)\n</code></pre>\n<p>It also allows you to do this immediately in the <code>__init__</code></p>\n<pre><code>def __init__(self, values=None):\n self.root = None\n if values is not None:\n self.update(values)\n</code></pre>\n<p>and use something like this in your tests:</p>\n<pre><code>bst = BST(range(5))\n</code></pre>\n<h1>Node</h1>\n<p>All of the methods you prepend with an <code>_</code> make more sense as methods on the <code>Node</code></p>\n<h2><code>_xxorder</code></h2>\n<p>for example <code>_inorder</code>:</p>\n<pre><code>def inorder(self):\n if self.left is not None:\n yield from self.left.inorder()\n yield self\n if self.right is not None:\n yield from self.right.inorder()\n</code></pre>\n<p>and then <code>BST.inorder</code>:</p>\n<pre><code>def inorder(self):\n return self.root.inorder()\n</code></pre>\n<p>You can easily foresee a reverse iteration too (for example to find the maximum of the tree:</p>\n<pre><code>def inorder_reverse(self):\n if self.right is not None:\n yield from self.right.inorder_reverse()\n yield self\n if self.left is not None:\n yield from self.left.inorder_reverse()\n</code></pre>\n<p>same goes for the <code>_doFind</code>. <code>Node.find</code>:</p>\n<pre><code>def find(self, key):\n if self.value == key:\n return self\n next = self.right if self.value < key else self.left\n if next is None:\n return None # or raise IndexError\n return next.find(key)\n</code></pre>\n<p>and <code>BST.find</code>:</p>\n<pre><code>def find(self, key):\n return self.root.find(key)\n</code></pre>\n<h1><code>magic</code> methods</h1>\n<p><code>isSameTree</code> compares 2 trees. Why not name it <code>__eq__</code>.\nYour implementation doesn't really use seld, so it might make more sense to transfer it to <code>Node</code> to compare subtrees</p>\n<p><code>Node.__eq__</code>:</p>\n<pre><code>def __eq__(self, other):\n if other is None:\n return False\n return (\n self.value == other.value\n and self.left == other.left\n and self.right == other.right\n )\n</code></pre>\n<p><code>BST.__eq__</code>:</p>\n<pre><code>def __eq__(self, other):\n return self.root == other.root\n</code></pre>\n<p>You can easily implement the <code>Iterator</code> protocol on <code>BST</code>:</p>\n<pre><code>__iter__ = inorder\n</code></pre>\n<p>and <code>reversed</code>:</p>\n<pre><code>__reversed__ = inorder_reverse\n</code></pre>\n<h1>Sum</h1>\n<p>You don't need the <code>Sum</code> class, you can just pass on a value. Also this method seems more appropriate under the <code>Node</code> class:</p>\n<pre><code>def sumRToL(self, partial_sum=0):\n if self.right is not None:\n partial_sum = self.right.sumRToL(partial_sum)\n self.value += partial_sum\n if self.left is not None:\n self.left.sumRTol(self.value)\n return self.value\n</code></pre>\n<p>Using this on mutable <code>value</code>s might have strange effects.</p>\n<p>on <code>BST</code>:</p>\n<pre><code>def sumelementsfromRtoLinplace(self):\n if self.root is not None:\n self.root.sumRToL()\n</code></pre>\n<h1>validate</h1>\n<p>checking whether your tree is valid can become very easy via the iterator we just implemented. Using <code>pairwise</code> from the itertool recipes:</p>\n<pre><code>def validate(self):\n return all(a > b for a, b in pairwise(self)) # or self.inorder() for extra clarity\n</code></pre>\n<h1>testing</h1>\n<p>These unit tests can be better done in another file, importing this file, and using one of the unit test frameworks. I'm quite happy with <code>py.test</code>.</p>\n<pre><code>import pytest\n\nfrom binary_tree import BST\n\n\ndef test_order():\n bst = BST(range(10))\n assert [item.value for item in bst.inorder()] == list(range(10))\n assert [item.value for item in bst] == list(range(10))\n\n\ndef test_reverse():\n bst = BST(range(10))\n\n items = list(reversed(range(10)))\n assert [item.value for item in bst.inorder_reverse()] == items\n assert [item.value for item in reversed(bst)] == items\n\n\ndef test_equal():\n bst1 = BST(range(5))\n bst2 = BST(range(5))\n bst3 = BST(range(6))\n bst4 = BST(range(-3, 6))\n\n assert bst1 == bst2\n assert bst1 != bst3\n assert bst3 != bst1\n assert bst1 != bst4\n...\n</code></pre>\n<hr />\n<h1>total code</h1>\n<pre><code>from general_tools.itertools_recipes import pairwise\n\n\nclass Node:\n def __init__(self, value):\n self.left: Node = None\n self.right: Node = None\n self.value = value\n\n def inorder(self):\n if self.left is not None:\n yield from self.left.inorder()\n yield self\n if self.right is not None:\n yield from self.right.inorder()\n\n def inorder_reverse(self):\n if self.right is not None:\n yield from self.right.inorder_reverse()\n yield self\n if self.left is not None:\n yield from self.left.inorder_reverse()\n\n def preorder(self):\n yield self\n if self.left is not None:\n yield from self.left.inorder()\n if self.right is not None:\n yield from self.right.inorder()\n\n def postorder(self):\n if self.left is not None:\n yield from self.left.inorder()\n if self.right is not None:\n yield from self.right.inorder()\n yield self\n\n def find(self, key):\n if self.value == key:\n return self\n next = self.right if self.value < key else self.left\n if next is None:\n return None # or raise IndexError\n return next.find(key)\n\n def __eq__(self, other):\n if other is None:\n return False\n return (\n self.value == other.value\n and self.left == other.left\n and self.right == other.right\n )\n\n def sumRToL(self, partial_sum=0):\n if self.right is not None:\n partial_sum = self.right.sumRToL(partial_sum)\n self.value += partial_sum\n if self.left is not None:\n self.left.sumRTol(self.value)\n\n def __str__(self):\n return f"{self.value} "\n\n def __repr__(self):\n return f"Node({self.value})"\n\n\nclass BST:\n def __init__(self, values=None):\n self.root: Node = None\n if values is not None:\n self.update(values)\n\n def insert(self, key):\n if self.root is None:\n self.root = Node(key)\n return\n curr = self.root\n parent = None\n while curr and curr.value != key:\n parent, curr = curr, curr.right if curr.value < key else curr.left\n if parent is not None:\n if parent.value < key:\n parent.right = Node(key)\n else:\n parent.left = Node(key)\n\n def update(self, values):\n for value in values:\n self.insert(value)\n\n def delete(self, key):\n pass\n\n def find(self, key):\n return self.root.find(key)\n\n def inorder(self):\n return self.root.inorder()\n\n def inorder_reverse(self):\n return self.root.inorder_reverse()\n\n def preorder(self):\n return self.root.preorder()\n\n def postorder(self):\n return self.root.postorder()\n\n def sumelementsfromRtoLinplace(self):\n if self.root is not None:\n self.root.sumRToL()\n\n def validatebst(self):\n return all(a > b for a, b in pairwise(self))\n\n __iter__ = inorder\n __reversed__ = inorder_reverse\n\n def __eq__(self, other):\n return self.root == other.root\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T10:56:50.830",
"Id": "415880",
"Score": "0",
"body": "Consistency & Compatibility are more important as stated in a [previous answer](https://stackoverflow.com/a/159745/396865), and as even stated in [PEP 8](https://www.python.org/dev/peps/pep-0008/#type-variable-names) for backward compatibility,\nI personally prefer `mixedCase` over `lower_case_with_underscores` as well"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T15:01:23.500",
"Id": "215038",
"ParentId": "214806",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T01:33:40.887",
"Id": "214806",
"Score": "0",
"Tags": [
"python",
"tree",
"reinventing-the-wheel"
],
"Title": "Binary Search Tree implementation with topological validation"
} | 214806 |
<p>I would like to see suggestions if my code could be more improved. In my controller I have a line:</p>
<pre><code>self.bool_value = False # for testing
</code></pre>
<p>which in my opinion should not be there, because I put it there only for testing purposes, but I did not find any way around. In addition I would like to know whether you guys test the <code>__init__</code> method as well, because I see no point in it. And another question would be, if you guys would test if the parameter <code>req</code> was called in the execute method. Any other suggestions to improve this code are welcomed.</p>
<p>My Controller looks like this:</p>
<pre><code>from typing import Callable
from source.controller.RequestModel import RequestModel
from source.boundaries.AbstractInputBoundary import AbstractInputBoundary
class Controller:
abstractInputBoundary: AbstractInputBoundary
bool_function: Callable[[bool], bool]
bool_value: bool
def __init__(self, abstract_input_boundary, bool_function=lambda _: True):
self.abstractInputBoundary = abstract_input_boundary
self.bool_function = bool_function
self.bool_value = True
def process_input(self) -> None:
"""
Waits for the input of the User in order to call a usecase
:rtype: None
"""
while self.bool_function(self.bool_value):
self.bool_value = False # for testing
inp: str = input()
if inp == "show data":
req = RequestModel()
req.setRequest(inp)
self.abstractInputBoundary.execute(req)
</code></pre>
<p>My Test looks like the following:</p>
<pre><code>import unittest
from source.controller.Controller import Controller
from unittest.mock import patch
from unittest.mock import MagicMock
class TestController(unittest.TestCase):
def test_process_input(self):
"""
This tests, whether after the input "show data" in the controller object a boundary object is called
"""
def switch_function(switch_bool):
if switch_bool is True:
return True
else:
return False
with patch('builtins.input') as inp:
inp.return_value = "show data"
boundary = MagicMock()
boundary.execute = MagicMock()
controller = Controller(boundary, switch_function)
controller.process_input()
assert boundary.execute.called
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T01:53:51.523",
"Id": "214808",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"unit-testing"
],
"Title": "Testing a Controller in a while loop"
} | 214808 |
<p>I have been trying to figure out how to meet space and time complexity requirements for the following leet code question. I have come up with two versions, one that meets the time requirements and another that meets the space requirements. Both versions fail on the same test case (the last test case shown below). Can anyone suggest how to reconcile both space and time requirements? What am I missing?</p>
<h1>Question and examples</h1>
<blockquote>
<p>Given a non-empty string s and a dictionary wordDict containing a list of non-empty words,
add spaces in s to construct a sentence where each word is a valid dictionary word. Return
all such possible sentences.</p>
<p>Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.</p>
<p>Example 1:</p>
<p>Input:</p>
<pre><code>s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
</code></pre>
<p>Output:</p>
<pre><code>[
"cats and dog",
"cat sand dog"
]
</code></pre>
<p>Example 2:</p>
<p>Input:</p>
<pre><code>s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
</code></pre>
<p>Output:</p>
<pre><code>[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
</code></pre>
<p>Explanation: Note that you are allowed to reuse a dictionary word.</p>
<p>Example 3:</p>
<p>Input:</p>
<pre><code>s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
</code></pre>
<p>Output:</p>
<pre><code>[]
</code></pre>
</blockquote>
<h1>Code that fails time limit</h1>
<pre><code>class Solution:
def wordBreak(self, s: str, wordDict: 'List[str]') -> 'List[str]':
if not wordDict:
return []
wD = set(wordDict)
max_offset = len(max(wD, key=len))
paths = []
def dfs(st, path):
if st == len(s):
paths.append(path)
return
for en in range(st + 1, st + max_offset + 1):
if s[st:en] in wD:
dfs(en, path + [(st, en)])
dfs(0, [])
return [' '.join([s[x[0] : x[1]] for x in path]) for path in paths]
</code></pre>
<h1>Code that fails space limit</h1>
<pre><code>class Solution:
def wordBreak(self, s: str, wordDict: 'List[str]') -> 'List[str]':
from collections import defaultdict
if not wordDict:
return []
wD = set(wordDict)
memo = defaultdict(list)
memo[len(s)] = [[(len(s), len(s) + 1)]]
for i in range(len(s) - 1, -1, -1):
for j in range(i + 1, len(s) + 1):
if s[i:j] in wD and j in memo:
for l in memo[j]:
memo[i].append([(i, j), *l])
return [' '.join([s[ind[0] : ind[1]] for ind in x[:-1]]) for x in memo[0]]
</code></pre>
<h1>Testing (the last test case fails each of the above versions)</h1>
<pre><code>import pprint
inps = [
("catsanddog", ["cat", "cats", "and", "sand", "dog"]),
("pineapplepenapple", ["apple", "pen", "applepen", "pine", "pineapple"]),
("catsandog", ["cats", "dog", "sand", "and", "cat"]),
("a", ['a']),
("abc", ['abc', 'a', 'b', 'c']),
("hellow", []),
(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
[
"a",
"aa",
"aaa",
"aaaa",
"aaaaa",
"aaaaaa",
"aaaaaaa",
"aaaaaaaa",
"aaaaaaaaa",
"aaaaaaaaaa",
],
),
]
sol = Solution()
for s, wd in inps:
print(f"Doing s[{s}] and wd[{wd}]...")
ans = sol.wordBreak(s, wd)
pprint.pprint(ans)
</code></pre>
| [] | [
{
"body": "<p>I have figured out how to do this problem and achieve the time and space requirements. It is faster than 64% of submissions but only more space efficient than 5% of submissions (woops). I ended up modifying the code that fails the space requirements. Here is my solution:</p>\n\n<pre><code>class Solution:\n def wordBreak(self, s: str, wordDict: 'List[str]') -> 'List[str]':\n from collections import defaultdict\n\n if not wordDict:\n return []\n\n wD = set(wordDict)\n childs = defaultdict(list)\n childs[len(s)] = [None]\n\n for i in range(len(s) - 1, -1, -1):\n for j in range(i + 1, len(s) + 1):\n if s[i:j] in wD and j in childs:\n childs[i].append(j)\n\n paths = []\n\n def dfs(nd, path):\n if nd is None:\n paths.append(path)\n return\n\n for ch in childs[nd]:\n dfs(ch, ' '.join([path, s[nd:ch]]))\n\n dfs(0, '')\n return [x.strip() for x in paths]\n</code></pre>\n\n<p>Any optimizations are still welcome. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T19:49:41.353",
"Id": "214866",
"ParentId": "214809",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "214866",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T02:11:28.367",
"Id": "214809",
"Score": "2",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded",
"dynamic-programming"
],
"Title": "Given a string and a word dict, find all possible sentences"
} | 214809 |
<p>I was searching for a long time how to write multi-page TIFFs with the JPEG encoding. TIFFs support JPEG encoded frames but the built-in encoder in .NET Framework does not have JPEG as a compression option. </p>
<p>The code is based on the answer to this question: <a href="https://stackoverflow.com/questions/14811496/tiff-with-jpeg-compression-much-larger-than-original-jpeg">https://stackoverflow.com/questions/14811496/tiff-with-jpeg-compression-much-larger-than-original-jpeg</a>
but does not rely on the FreeImage library.</p>
<p>First up, a class to convert <code>BitmapFrame</code> or <code>Bitmap</code> to a JPEG image:</p>
<pre><code>using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;
namespace TIFF
{
public class Jpeg
{
public byte[] Data;
public uint Width;
public uint Height;
public uint HorizontalResolution;
public uint VerticalResolution;
public Jpeg(byte[] data, uint width, uint height, uint horizontalResolution, uint verticalResolution)
{
this.Data = data;
this.Width = width;
this.Height = height;
this.HorizontalResolution = horizontalResolution;
this.VerticalResolution = verticalResolution;
}
public static Jpeg FromBitmapFrame(BitmapFrame bitmap, long quality)
{
Jpeg jpeg;
using (var stream = new MemoryStream())
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 90;
encoder.Frames.Add(bitmap);
encoder.Save(stream);
jpeg = new Jpeg(stream.ToArray(), (uint)bitmap.Width, (uint)bitmap.Height, (uint)bitmap.DpiX, (uint)bitmap.DpiY);
}
return jpeg;
}
public static Jpeg FromBitmap(Bitmap bitmap, long quality)
{
Jpeg jpeg;
using (var stream = new MemoryStream())
{
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
Encoder encoder = Encoder.Quality;
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] = new EncoderParameter(encoder, quality);
bitmap.Save(stream, jpgEncoder, parameters);
jpeg = new Jpeg(stream.ToArray(), (uint) bitmap.Width, (uint) bitmap.Height, (uint) bitmap.HorizontalResolution, (uint) bitmap.VerticalResolution);
}
return jpeg;
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
}
</code></pre>
<p>Next, a class to create the TIFF image</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Media.Imaging;
namespace TIFF
{
public static class JpegTiff
{
public static byte[] Create(List<BitmapFrame> frames, long quality)
{
List<Jpeg> jpegs = new List<Jpeg>();
foreach (var frame in frames)
{
jpegs.Add(Jpeg.FromBitmapFrame(frame, quality));
}
return WrapJpegs(jpegs);
}
public static byte[] Create(List<Bitmap> bitmaps, string filename, long quality)
{
List<Jpeg> jpegs = new List<Jpeg>();
foreach (var bitmap in bitmaps)
{
jpegs.Add(Jpeg.FromBitmap(bitmap, quality));
}
return WrapJpegs(jpegs);
}
private static byte[] WrapJpegs(List<Jpeg> jpegs)
{
if (jpegs == null || jpegs.Count == 0 || jpegs.FindIndex(b => b.Data.Length == 0) > -1)
throw new ArgumentNullException("Image Data must not be null or empty");
MemoryStream tiffData = new MemoryStream();
BinaryWriter writer = new BinaryWriter(tiffData);
uint offset = 8; // size of header, offset to IFD
ushort entryCount = 14; // entries per IFD
#region IFH - Image file header
// magic number
if (BitConverter.IsLittleEndian)
writer.Write(0x002A4949);
else
writer.Write(0x4D4D002A);
// offset to (first) IFD
writer.Write(offset);
#endregion IFH
#region IFD Image file directory
// write image file directories for each jpeg
for (int i = 0; offset > 0; i++)
{
var jpeg = jpegs[i];
uint width = jpeg.Width;
uint length = jpeg.Height;
uint xres = jpeg.HorizontalResolution;
uint yres = jpeg.VerticalResolution;
// count of entries:
writer.Write(entryCount);
offset += 6 + 12 * (uint)entryCount; // add lengths of entries, entry-count and next-ifd-offset
// TIFF-fields / IFD-entrys:
// {TAG, TYPE (3 = short, 4 = long, 5 = rational), COUNT, VALUE/OFFSET}
uint[,] fields = new uint[,] {
{254, 4, 1, 0}, // NewSubfileType
{256, 4, 1, width}, // ImageWidth
{257, 4, 1, length}, // ImageLength
{258, 3, 3, offset}, // BitsPerSample
{259, 3, 1, 7}, // Compression (new JPEG)
{262, 3, 1, 6}, //PhotometricInterpretation (YCbCr)
{273, 4, 1, offset + 22}, // StripOffsets (offset IFH + entries + values of BitsPerSample & YResolution & XResolution)
{277, 3, 1, 3}, // SamplesPerPixel
{278, 4, 1, length}, // RowsPerStrip
{279, 4, 1, (uint)jpegs[i].Data.LongLength}, // StripByteCounts
{282, 5, 1, offset + 6}, // XResolution (offset IFH + entries + values of BitsPerSample)
{283, 5, 1, offset + 14}, // YResolution (offset IFH + entries + values of BitsPerSample & YResolution)
{284, 3, 1, 1}, // PlanarConfiguration (chunky)
{296, 3, 1, 2} // ResolutionUnit
};
// write fields
for (int f = 0; f < fields.GetLength(0); f++)
{
writer.Write((ushort)fields[f, 0]);
writer.Write((ushort)fields[f, 1]);
writer.Write(fields[f, 2]);
writer.Write(fields[f, 3]);
}
// offset of next IFD
if (i == jpegs.Count - 1)
offset = 0;
else
offset += 22 + (uint)jpegs[i].Data.LongLength; // add values (of fields) length and jpeg length
writer.Write(offset);
#region values of fields
// BitsPerSample
writer.Write((ushort)8);
writer.Write((ushort)8);
writer.Write((ushort)8);
// XResolution
writer.Write(xres);
writer.Write(1);
// YResolution
writer.Write(yres);
writer.Write(1);
#endregion values of fields
// actual image Data
writer.Write(jpegs[i].Data);
}
#endregion IFD
writer.Close();
return tiffData.ToArray();
}
}
}
</code></pre>
<p>It could probably be improved by passing in the stream to write to instead of returning a byte array.</p>
| [] | [
{
"body": "<blockquote>\n<pre><code>public static Jpeg FromBitmapFrame(BitmapFrame bitmap, long quality)\n{\n Jpeg jpeg;\n using (var stream = new MemoryStream())\n {\n JpegBitmapEncoder encoder = new JpegBitmapEncoder();\n encoder.QualityLevel = 90;\n encoder.Frames.Add(bitmap);\n encoder.Save(stream);\n jpeg = new Jpeg(stream.ToArray(), (uint)bitmap.Width, (uint)bitmap.Height, (uint)bitmap.DpiX, (uint)bitmap.DpiY);\n }\n return jpeg;\n}\n</code></pre>\n</blockquote>\n\n<p>Here it should be safe to return from inside the <code>using</code> statement:</p>\n\n<pre><code>public static Jpeg FromBitmapFrame(BitmapFrame bitmap, long quality)\n{\n using (var stream = new MemoryStream())\n {\n JpegBitmapEncoder encoder = new JpegBitmapEncoder();\n encoder.QualityLevel = 90;\n encoder.Frames.Add(bitmap);\n encoder.Save(stream);\n return new Jpeg(stream.ToArray(), (uint)bitmap.Width, (uint)bitmap.Height, (uint)bitmap.DpiX, (uint)bitmap.DpiY);\n }\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> private static ImageCodecInfo GetEncoder(ImageFormat format)\n {\n ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();\n foreach (ImageCodecInfo codec in codecs)\n {\n if (codec.FormatID == format.Guid)\n {\n return codec;\n }\n }\n return null;\n }\n</code></pre>\n</blockquote>\n\n<p>Using LINQ this can be reduced to a oneliner:</p>\n\n<pre><code>private static ImageCodecInfo GetEncoder(ImageFormat format)\n{\n return ImageCodecInfo.GetImageDecoders().FirstOrDefault(codec => codec.FormatID == format.Guid);\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>public static byte[] Create(List<BitmapFrame> frames, long quality)\n{\n List<Jpeg> jpegs = new List<Jpeg>();\n foreach (var frame in frames)\n {\n jpegs.Add(Jpeg.FromBitmapFrame(frame, quality));\n }\n return WrapJpegs(jpegs);\n}\n</code></pre>\n</blockquote>\n\n<p>Again LINQ can \"modernize\" this a little:</p>\n\n<pre><code>public static byte[] Create(IEnumerable<BitmapFrame> frames, long quality)\n{\n return WrapJpegs(frames.Select(frame => Jpeg.FromBitmapFrame(frame, quality)).ToList());\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>jpegs.FindIndex(b => b.Data.Length == 0) > -1</code></p>\n</blockquote>\n\n<p>LINQ:</p>\n\n<pre><code>jpegs.Any(j => j.Data.Length == 0)\n</code></pre>\n\n<p>IMO easier to read.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> MemoryStream tiffData = new MemoryStream();\n BinaryWriter writer = new BinaryWriter(tiffData);\n</code></pre>\n</blockquote>\n\n<p>You need to wrap these in <code>using</code> statements:</p>\n\n<pre><code> using (MemoryStream tiffData = new MemoryStream()) // HDH Use using in order to clean up \n using (BinaryWriter writer = new BinaryWriter(tiffData))\n {\n ...\n writer.Flush();\n return tiffData.ToArray();\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> for (int i = 0; offset > 0; i++)\n {\n</code></pre>\n</blockquote>\n\n<p>The stop condition is confusing. Why not just use <code>jpegs.Count</code> because you actually iterate through all items anyway.</p>\n\n<hr>\n\n<p>In the main loop you declare this:</p>\n\n<pre><code>var jpeg = jpegs[i];\n</code></pre>\n\n<p>But you use <code>jpegs[i]</code> several times in the loop. Be consistent.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> uint[,] fields = new uint[,] {\n {254, 4, 1, 0}, // NewSubfileType\n {256, 4, 1, width}, // ImageWidth\n</code></pre>\n</blockquote>\n\n<p>I think I would make a struct or class for these fields in order to be strict with types - hence avoiding the casting.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> writer.Write((ushort)8);\n writer.Write((ushort)8);\n writer.Write((ushort)8);\n</code></pre>\n</blockquote>\n\n<p>make a <code>const ushort bitsPerSample = 8;</code> for this - before the loop.</p>\n\n<hr>\n\n<p>The idea of having a <code>stream</code> as argument to the methods is good, but be aware that <code>BinaryWriter</code> disposes the stream, when it is disposed unless you use the constructor with the <code>leaveOpen</code> flag. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T11:00:10.623",
"Id": "415470",
"Score": "0",
"body": "Nice stuff with the LINQ, looks great. BTW is it better to edit the original question with these changes or post another answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T11:01:54.717",
"Id": "415471",
"Score": "0",
"body": "@geometrikal: You're not allowed to change the question once an answer has been posted. Feel free to make an answer with the changes or post a new question with an updated version :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T10:56:47.923",
"Id": "214828",
"ParentId": "214812",
"Score": "5"
}
},
{
"body": "<p>Henrik covered a number of points which I would have raised, so I won't repeat those.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>namespace TIFF\n{\n public class Jpeg\n</code></pre>\n</blockquote>\n\n<p>seems inconsistent to me. The convention in .Net is to camel-case acronyms and initialisms, so the class name is as expected and the namespace is not.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static class JpegTiff\n {\n public static byte[] Create(List<BitmapFrame> frames, long quality)\n ...\n public static byte[] Create(List<Bitmap> bitmaps, string filename, long quality)\n ...\n private static byte[] WrapJpegs(List<Jpeg> jpegs)\n ...\n</code></pre>\n</blockquote>\n\n<p>Since <code>Jpeg</code> is a public class it seems to me that you could rename <code>WrapJpegs</code> to <code>Create</code> and make it public. That opens up the option, for example, of encoding different frames at different qualities. (I'd also change <code>List</code> to <code>IEnumerable</code>, as Henrik proposes for the existing <code>Create</code> methods).</p>\n\n<hr>\n\n<p>There are some worrying magic numbers. Some of these concerns might be alleviated by a comment with a URL for the file format specification.</p>\n\n<blockquote>\n<pre><code> uint offset = 8; // size of header, offset to IFD\n</code></pre>\n</blockquote>\n\n<p>Is this 4 for the endianness magic number and 4 for <code>offset</code> itself?</p>\n\n<blockquote>\n<pre><code> ushort entryCount = 14; // entries per IFD\n</code></pre>\n</blockquote>\n\n<p>This is <code>fields.GetLength(0)</code>, isn't it? Is there any reason that you can't explicitly use <code>fields.GetLength(0)</code> for robustness if you later add or remove a field?</p>\n\n<blockquote>\n<pre><code> // TIFF-fields / IFD-entrys:\n // {TAG, TYPE (3 = short, 4 = long, 5 = rational), COUNT, VALUE/OFFSET}\n uint[,] fields = ...\n\n // write fields\n for (int f = 0; f < fields.GetLength(0); f++)\n {\n writer.Write((ushort)fields[f, 0]);\n writer.Write((ushort)fields[f, 1]);\n writer.Write(fields[f, 2]);\n writer.Write(fields[f, 3]);\n }\n</code></pre>\n</blockquote>\n\n<p>I find it very confusing that a <code>short</code> and a <code>long</code> should take the same amount of space.</p>\n\n<blockquote>\n<pre><code> if (i == jpegs.Count - 1)\n offset = 0;\n else\n offset += 22 + (uint)jpegs[i].Data.LongLength; // add values (of fields) length and jpeg length\n</code></pre>\n</blockquote>\n\n<p>22? Three shorts and four ints?</p>\n\n<p>One more explicit (although less portable, I admit) approach to these lengths would be to use structs for the chunks of fields and <code>Marshal.SizeOf</code>. But I understand if you think that's overkill.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T23:35:56.940",
"Id": "415545",
"Score": "0",
"body": "Some good points. Most of the WrapJpegs code comes from the linked SO question, so I'm still trying to work it out. I would be interested in what using a struct for the chunks of fields looks like"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T12:21:29.637",
"Id": "214830",
"ParentId": "214812",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T04:17:35.840",
"Id": "214812",
"Score": "4",
"Tags": [
"c#",
"image",
"wpf",
"compression"
],
"Title": "WPF Bitmap / BitmapFrame to multi-page / multi-frame TIFF with JPEG encoding"
} | 214812 |
<p>It's a user alert script. It worked in every browser I tested. But the function itself looks very messy/repetitive. Is there any way to make this cleaner?</p>
<pre><code>function message(text) {
var alert = document.createElement('div');
var alertText = document.createTextNode(text);
var alertCloseButton = document.createElement('i');
var buttonText = document.createTextNode('close');
var shadow = document.createElement('div');
alert.className = 'alert-text';
alertCloseButton.className = 'material-icons';
alertCloseButton.id = 'close-alert';
alertCloseButton.setAttribute('onclick', 'function() { var a = this.parentNode; var s = a.parentNode; s.parentNode.removeChild(s)}');
alertCloseButton.onclick = function() { var a = this.parentNode; var s = a.parentNode; s.parentNode.removeChild(s) };
alertCloseButton.appendChild(buttonText);
alert.appendChild(alertCloseButton);
alert.appendChild(alertText);
shadow.className = 'shadow';
shadow.appendChild(alert);
document.body.appendChild(shadow);
}
var button = document.querySelector('button');
button.addEventListener('click', function(){
message('Button clicked');
});
</code></pre>
<p>Here's the code working: <a href="https://jsfiddle.net/3aouyfz7/" rel="nofollow noreferrer">https://jsfiddle.net/3aouyfz7/</a></p>
| [] | [
{
"body": "<h2>Explanation:</h2>\n\n<p>It's true that using objects can become messy after a while. That's why <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">Template Literals</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML\" rel=\"nofollow noreferrer\">innerHTML</a> are so powerful in this situation.</p>\n\n<p>I would highly advise to avoid using <code>parentNode</code> when attempting to remove HTML, you may unintentionally remove something in the future if you decide to make your alert HTML more complex.</p>\n\n<p>To solve this, create a container element that is accessible by your onclose method.</p>\n\n<p>Also, I would also advise to not overwrite existing objects. Why not name alert to something else?</p>\n\n<p>Don't add onclick events directly in the HTML, it's messy. </p>\n\n<h2>Solution:</h2>\n\n<pre><code>function message(text) {\n\n const container = document.createElement(\"div\");\n\n const onClose = ()=>container.remove();\n\n container.innerHTML = `\n <div class=\"shadow\">\n <div class=\"alert-text\">\n <i id=\"close-alert\" class=\"material-icons\">close</i>\n ${text}\n </div>\n </div>\n `;\n\n document.body.appendChild(container);\n\n document\n .querySelector('i#close-alert')\n .addEventListener(\"click\", onClose);\n}\n</code></pre>\n\n<h2>Working Example:</h2>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function message(text) {\n\n const container = document.createElement(\"div\");\n\n const onClose = ()=>container.remove();\n\n container.innerHTML = `\n <div class=\"shadow\">\n <div class=\"alert-text\">\n <i id=\"close-alert\" class=\"material-icons\">close</i>\n ${text}\n </div>\n </div>\n `;\n \n document.body.appendChild(container);\n \n document\n .querySelector('i#close-alert')\n .addEventListener(\"click\", onClose);\n}\n\nconst button = document.querySelector('button');\nbutton.addEventListener('click', function() {\n message('Button clicked');\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n box-sizing: border-box;\n}\n\n.shadow {\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, .5);\n position: fixed;\n top: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 98;\n}\n\n.alert-text {\n border: 1px solid #aaa;\n padding: 2.5em;\n min-height: 10%;\n width: auto;\n max-width: 80%;\n background: #fff;\n z-index: 99;\n position: relative;\n text-align: center;\n}\n\n.alert-text i {\n position: absolute;\n top: 0;\n right: 0;\n color: #777;\n cursor: pointer;\n padding: .5rem;\n}\n\n.alert-text i:hover {\n color: #444\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html>\n\n<head>\n <title></title>\n\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n\n</head>\n\n<body>\n\n <h3>Page content</h3>\n <button>alert</button>\n\n\n</body>\n\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T19:49:53.893",
"Id": "415529",
"Score": "1",
"body": "thanks for the clean up, i've learned a lot from your answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T12:33:01.650",
"Id": "214831",
"ParentId": "214814",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214831",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T06:36:46.563",
"Id": "214814",
"Score": "4",
"Tags": [
"javascript",
"dom"
],
"Title": "Function to display an alert"
} | 214814 |
<p>I want to create a pytest with a fake <code>utcnow</code>, but also I need to preserve the functionality of all other <code>datetime</code> methods. Simple example here:</p>
<pre><code>import datetime as dt
class FakeTime(dt.datetime):
fake_time = None
@classmethod
def utcnow(cls):
return cls.fake_time
def str_2_time(str_dt: str) -> dt.datetime:
"""Shortcut to do convert the string to datetime"""
return dt.datetime.strptime(str_dt, '%Y-%m-%d %H:%M')
def test_patch_datetime():
for utc_time in ['2019-01-01 10:00', '2019-02-01 13:00', '2019-03-01 16:00']:
FakeTime.fake_time = str_2_time(utc_time)
dt.datetime = FakeTime
assert dt.datetime.utcnow() == str_2_time(utc_time)
</code></pre>
<p>Is this the right way?</p>
<p>The method <code>str_2_time</code> just need to show that all other methods of the datetime works fine.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T14:25:49.773",
"Id": "415477",
"Score": "0",
"body": "I highly recommend this lib for mocking `now` in python tests https://github.com/spulec/freezegun"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T14:44:52.717",
"Id": "415482",
"Score": "0",
"body": "@Anentropic thank you, but if i will need more options i will add the package to the project"
}
] | [
{
"body": "<p>According to <a href=\"https://stackoverflow.com/a/4482067/1562285\">this</a>, subclassing <code>datetime.datetime</code> seems the way to go.</p>\n\n<p>There is no use for the <code>str_2_time</code> method though. You can easily inline this, or even simpler, just use the <code>datetime.datetime</code> constructor:</p>\n\n<pre><code>def test_patch_datetime():\n for utc_time in [\n dt.datetime(2019, 1, 1, 10),\n dt.datetime(2019, 2, 1, 13),\n dt.datetime(2019, 3, 1, 16),\n ]:\n FakeTime.fake_time = utc_time\n dt.datetime = FakeTime\n assert dt.datetime.utcnow() == utc_time\n</code></pre>\n\n<p>You should be aware that this can have side effects in other parts of your code, so it might be needed to replace it back with the original class after the test method:</p>\n\n<pre><code>def test_patch_datetime():\n datetime_orig = dt.datetime\n\n utc_times = [\n dt.datetime(2019, 1, 1, 10),\n dt.datetime(2019, 2, 1, 13),\n dt.datetime(2019, 3, 1, 16),\n ]\n for utc_time in utc_times:\n FakeTime.fake_time = utc_time\n dt.datetime = FakeTime\n assert dt.datetime.utcnow() == utc_time\n dt.datetime = datetime_orig\n # print(dt.datetime.utcnow())\n assert dt.datetime.utcnow() > max(utc_times)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T08:36:22.417",
"Id": "415454",
"Score": "0",
"body": "thank you, but the method `str_2_time` just need to show that all other methods of the `datetime` works fine."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T08:33:51.620",
"Id": "214822",
"ParentId": "214816",
"Score": "6"
}
},
{
"body": "<p>Usually, I do:</p>\n\n<ol>\n<li>Separate module, for example <code>utils.py</code>, that contains:</li>\n</ol>\n\n<pre><code>from datetime import datetime\n\ndef get_utcnow() -> datetime:\n return datetime.utcnow()\n</code></pre>\n\n<ol start=\"2\">\n<li>Use this function everywhere in my code.</li>\n<li>Add the mocking fixture in <code>tests/conftest.py</code>:</li>\n</ol>\n\n<pre><code>from datetime import datetime, timedelta\n\nimport pytest\n\nfrom .. import utils\n\n@pytest.fixture\ndef mock_utcnow(monkeypatch):\n now = datetime.min\n\n def wrapped(delta=0.0):\n when = now + timedelta(delta)\n monkeypatch.setattr(utils, \"get_utcnow\", lambda: when)\n return when\n\n return wrapped\n</code></pre>\n\n<ol start=\"4\">\n<li>Now it's easy to use it in your tests:</li>\n</ol>\n\n<pre><code>def test(mock_utcnow):\n now = mock_utcnow()\n new_now = mock_utcnow(0.1)\n</code></pre>\n\n<p>Additionally, with this fixture you can set the returning value with desired offset.</p>\n\n<p>Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T14:48:53.023",
"Id": "415485",
"Score": "0",
"body": "thank you for the answer, but i don't understand how it should help for my case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:43:42.927",
"Id": "415580",
"Score": "0",
"body": "If I understand you right, you want `utcnow` to return fake datetime.\nSo, using code from my answer:\n1. You will use `utils.get_utcnow` in your real code, not in the tests.\n2. In the tests you'll use fixture, that mocks `utils.get_utcnow`. After you call mocking function, every call of `utils.get_utcnow` in your real code will return fake datetime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:52:49.077",
"Id": "415586",
"Score": "0",
"body": "But with the code from my answer you'll get `datetime.min` by default, and after you can increase its value by adding `timedelta`, e.g. by calling `mock_utcnow(0.1)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:53:11.417",
"Id": "415587",
"Score": "0",
"body": "If you want to start not with a `datetime.min`, you can extend fixture [with this](https://gist.github.com/szobov/f670259ee6b0de7db1cf86ad65c678ca)\n\nBut it requires more code in your tests."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T14:17:26.380",
"Id": "214841",
"ParentId": "214816",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214822",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T07:36:16.667",
"Id": "214816",
"Score": "4",
"Tags": [
"python",
"datetime",
"unit-testing",
"mocks"
],
"Title": "Fake utcnow for the pytest"
} | 214816 |
<p>Kata: <a href="https://www.codewars.com/kata/range-extraction/python" rel="noreferrer">https://www.codewars.com/kata/range-extraction/python</a></p>
<blockquote>
<p>A format for expressing an ordered list of integers is to use a comma separated list of either</p>
<ul>
<li>individual integers </li>
<li>or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17") </li>
</ul>
<p>Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.</p>
<p>Example:</p>
<pre><code>solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])
# returns "-6,-3-1,3-5,7-11,14,15,17-20"
</code></pre>
<p>Courtesy of rosettacode.org </p>
</blockquote>
<h3>My Code</h3>
<pre class="lang-py prettyprint-override"><code>def solution(lst):
res = []
if lst:
tmp, i, ln = lst[0], 0, len(lst)
while i < ln:
tmp, j = lst[i], i
while j < ln - 1 and lst[j+1] == lst[j]+1:
j += 1
if j - i > 1:
tmp = str(lst[i]) + "-" + str(lst[j])
i = j+1
else:
i = (j if j > i else i+1)
res.append(tmp)
return ",".join(str(x) for x in res)
</code></pre>
| [] | [
{
"body": "<h2>Grouping</h2>\n\n<p>If you need to group anything using; <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>groupby</code></a> is probably the easiest way</p>\n\n<p>Here we can use a <code>itertools.groupby</code> recipe to group the consecutive ranges:</p>\n\n<pre><code>>>> for _, g in groupby(enumerate(lst), lambda i_x : i_x[0] - i_x[1]):\n... print([x for _, x in g])\n[-6]\n[-3, -2, -1, 0, 1]\n[3, 4, 5]\n[7, 8, 9, 10, 11]\n[14, 15]\n[17, 18, 19, 20]\n</code></pre>\n\n<h2>Yielding the correct representation</h2>\n\n<p>Now all is left is to check whether there are more then <code>2</code> items in the range, and return the range. Else return all the numbers in the range normally</p>\n\n<p>We can make this a generator, which yields either the range or a number, and afterwards join them together.</p>\n\n<h1>Full Code</h1>\n\n<pre><code>def group_consecutives(lst):\n for _, g in groupby(enumerate(lst), lambda i_x : i_x[0] - i_x[1]):\n r = [x for _, x in g]\n if len(r) > 2:\n yield f\"{r[0]}-{r[-1]}\"\n else:\n yield from map(str, r)\n\ndef range_extraction(lst):\n return ','.join(group_consecutives(lst))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T09:17:33.417",
"Id": "214826",
"ParentId": "214820",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "214826",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T08:10:07.180",
"Id": "214820",
"Score": "6",
"Tags": [
"python",
"beginner",
"programming-challenge",
"array"
],
"Title": "(Codewars) Range Extraction"
} | 214820 |
<p>I am really new to programming, and I made this simple tic tac toe app in python and <a href="https://codereview.stackexchange.com/q/214827/191336">C++</a>. Please tell me what can be improved</p>
<p>Code:</p>
<pre><code>import os
toDraw = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
turnsPlayed = 0
playerTurn = 1
def reset():
global turnsPlayed
turnsPlayed = 0
global toDraw
toDraw = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
global playerTurn
playerTurn = 1
def reDrawBoard(gameOver):
print(f"TIC TAC TOE\nPlayer one in X and Player two is O\n"
f"\n | | \n "
f"{toDraw[0]} | {toDraw[1]} | {toDraw[2]} "
f"\n___|___|___\n | | \n "
f"{toDraw[3]} | {toDraw[4]} | {toDraw[5]} "
f"\n___|___|___\n | | \n "
f"{toDraw[6]} | {toDraw[7]} | {toDraw[8]} "
f"\n | | \n\n")
if not gameOver:
print(f"Player {str(playerTurn)}, Enter a number: ")
#
# This prints (something similar to) -
#
# TIC TAC TOE
# Player one is X and Player two is O
#
# | |
# 1 | 2 | 3
# ___|___|___
# | |
# 4 | 5 | 6
# ___|___|___
# | |
# 7 | 8 | 9
# | |
#
# Player <1 or 2>, Enter a number:
#
def checkIfWin(): # 0 - Game in progress; 1 - Player 1 wins; 2 - Player 2 wins
one = toDraw[0]
two = toDraw[1]
three = toDraw[2]
four = toDraw[3]
five = toDraw[4]
six = toDraw[5]
seven = toDraw[6]
eight = toDraw[7]
nine = toDraw[8]
if ((one == "X" and two == "X" and three == "X") or
(one == "X" and four == "X" and seven == "X") or
(one == "X" and five == "X" and nine == "X") or
(seven == "X" and five == "X" and three == "X") or
(seven == "X" and eight == "X" and nine == "X") or
(three == "X" and six == "X" and nine == "X") or
(four == "X" and five == "X" and six == "X") or
(two == "X" and five == "X" and six == "X")):
return 1
elif ((one == "Y" and two == "Y" and three == "Y") or
(one == "Y" and four == "Y" and seven == "Y") or
(one == "Y" and five == "Y" and nine == "Y") or
(seven == "Y" and five == "Y" and three == "Y") or
(seven == "Y" and eight == "Y" and nine == "Y") or
(three == "Y" and six == "Y" and nine == "Y") or
(four == "Y" and five == "Y" and six == "Y") or
(two == "Y" and five == "Y" and six == "Y")):
return 2
else:
return 0
while True:
clear = lambda : os.system('clear')
reDrawBoard(False)
toPlay = ""
while True:
try:
toPlay = int(input())
if toPlay > 9:
print(f"\nInvalid Value. Try again.\nPlayer {str(playerTurn)}, Enter a number: ")
continue
except ValueError:
print(f"\nInvalid Value. Try again.\nPlayer {str(playerTurn)}, Enter a number: ")
continue
try:
if toPlay == int(toDraw[toPlay - 1]):
break
except ValueError:
print(f"Position already occupied. Please try again.\nPlayer {str(playerTurn)}, Enter a number: ")
continue
if playerTurn == 1:
toDraw[toPlay -1] = "X"
turnsPlayed += 1
playerTurn = 2
else:
toDraw[toPlay - 1] = "O"
turnsPlayed += 1
playerTurn = 1
result = checkIfWin()
if result == 1:
reDrawBoard(True)
response = input("PLAYER ONE WINS!!\nWould you like to play again? (Y/N): ").lower()
if response != "y":
#clear the screen
exit()
reset()
continue
if result == 2:
reDrawBoard(True)
response = input("PLAYER TWO WINS!!\nWould you like to play again? (Y/N): ").lower()
if response != "y":
#clear the screen
exit()
reset()
continue
if turnsPlayed == 9:
reDrawBoard(True)
response = input("DRAW!!\nWould you like to play again? (Y/N): ").lower()
if response != "y":
#clear the screen
exit()
reset()
continue
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T08:49:19.863",
"Id": "415456",
"Score": "0",
"body": "search for tic tac toe python on code review, and you will already find tens of tips on improving the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T08:54:51.157",
"Id": "415457",
"Score": "0",
"body": "@MaartenFabré Thanks, but I don't really understand all of the code in the other questions :) . Will try to improve what I can."
}
] | [
{
"body": "<p>One improvement I suggest is that in the beginning of your code, you could create a list of sets, in which each set would be a winning board configuration and then create two sets to record the players moves, like this: </p>\n\n<pre><code>winningMoves = [{1,2,3}, {1,4,7}, {1,5,9}, {7,5,3}, {7,8,9}, {3,6,9}, {4, 5, 6}, {2, 5, 8}]\nplayerOneMoves = set()\nplayerTwoMoves = set()\n</code></pre>\n\n<p>In the part that you check which player made the move, you would insert an \"add(toPlay)\" for both players, like this:</p>\n\n<pre><code>if playerTurn == 1:\n toDraw[toPlay -1] = \"X\"\n playerOneMoves.add(toPlay)\n turnsPlayed += 1\n playerTurn = 2\n</code></pre>\n\n<p>If I'm right, if you make things like this, you could reduce that great amount of code in checkIfWin() function to just:</p>\n\n<pre><code>def checkIfWin(): # 0 - Game in progress; 1 - Player 1 wins; 2 - Player 2 wins\n\n for move in winningMoves:\n if move.issubset(playerOneMoves):\n return 1\n elif move.issubset(playerTwoMoves):\n return 2\n return 0\n</code></pre>\n\n<p>The issubset() method will return True if move is a subset of the set that contains the player's moves. Which means it will return True if all elements in move are also in playerOneMoves or playerTwoMoves.</p>\n\n<p>Also, instead of printing the board with format, you could develop a way of printing each part of the board individually inside a loop, for example:</p>\n\n<pre><code>for num in range(1,10):\n\n if num in list(playerOneMoves):\n print(\"[{}]\".format('X'), end = '')\n elif num in list(playerTwoMoves):\n print(\"[{}]\".format('O'), end = '')\n else:\n print(\"[{}]\".format(num), end = '')\n if num%3 ==0:\n print(\"\")\n</code></pre>\n\n<p>(Of course you could improve the style!)</p>\n\n<p>The reason for that is that it would allow you to suppress toDraw completely and simplify your code even more. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T13:09:51.467",
"Id": "214835",
"ParentId": "214821",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214835",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T08:30:20.000",
"Id": "214821",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"tic-tac-toe"
],
"Title": "Simple Tic Tac Toe Game in Python3"
} | 214821 |
<p>We have been learning C++ the previous semester and I made this simple TicTacToe game at the end of it. We haven't yet covered topics of vectors, classes, objects, exception handling etc. so with this code I mostly wanted to practise use of arrays. I would like to hear from you on suggestions on how to make this code more readable, if there are any problems with it and, of course, possible improvements.</p>
<p>Since this game is played by the user as the player X and the computer as the player O, I am aware that the computer currently does not choose the best possible move, but rather randomly an empty field and that is something I plan to work on in the future.</p>
<p>Thank you in advance.</p>
<pre><code> #include <iostream>
#include <ctime>
#include <cstdlib>
const int SIZE = 3;
// tracks the status of all fields
bool boardStatus[SIZE][SIZE];
int score[2] = {};
void printMenu();
void drawBoard (bool m1[][SIZE], bool m2[][SIZE]){
for (int i = 0; i < SIZE; i++){
std::cout << "-------------\n" << "| ";
for (int j = 0; j < SIZE; j++)
if (m1[i][j]) std::cout << "X" << " | ";
else if (m2[i][j]) std::cout << "O" << " | ";
else std::cout << " | ";
std::cout << "\n";
}
std::cout << "-------------\n";
}
bool draw(){
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
if (!boardStatus[i][j]) return false;
return true;
}
bool win(bool m[][SIZE]){
int counter1 = 0, counter2 = 0;
// checks row by row and column by column for
// three X's or O's
for (int i = 0; i < SIZE; i++){
for (int j = 0; j < SIZE; j++){
if (m[i][j]) counter1++;
if (m[j][i]) counter2++;
}
if (counter1 == 3 || counter2 == 3) return true;
counter1 = 0; counter2 = 0;
}
// checks left diagonal
for (int i = 0; i < SIZE; i++)
if (m[i][i]) counter1++;
if (counter1 == 3) return true;
// checks right diagonal
for (int i = 0, j = 2; i < SIZE; i++, j--)
if (m[i][j]) counter2++;
if (counter2 == 3) return true;
return false;
}
void printWinOrDraw (bool m[][SIZE], char ch){
if (win(m)) {
std::cout << ch << " player won!\n\n";
if (ch == 'X') score[0]++;
else score[1]++;
}
else if (draw()) std::cout << "It's a draw!\n\n";
return;
}
// randomly generates field for player O
void computerChoice(int &rowComputer, int &columnComputer){
srand(time(0));
do{
rowComputer = rand() % 3;
columnComputer = rand() % 3;
if (!boardStatus[rowComputer][columnComputer])break;
} while (boardStatus[rowComputer][columnComputer]);
}
// takes valid input for player X from the user
void playerInput (int &rowPlayer, int &columnPlayer){
do {
do {
std::cout << "Enter a row (0, 1 or 2) for player X: ";
std::cin >> rowPlayer;
if (rowPlayer < 0 || rowPlayer > 2)
std::cout << "Invalid input! Try again\n";
} while (rowPlayer < 0 || rowPlayer > 2);
do {
std::cout << "Enter a column (0, 1 or 2) for player X: ";
std::cin >> columnPlayer;
if (columnPlayer < 0 || columnPlayer > 2)
std::cout << "Invalid input! Try again\n";
} while (columnPlayer < 0 || columnPlayer > 2);
if (!boardStatus[rowPlayer][columnPlayer]) break;
else std::cout << "That field is already taken. Use another field.\n";
} while (boardStatus[rowPlayer][columnPlayer]);
}
void startGame(bool player[][SIZE], bool computer[][SIZE]){
int rowPlayer, columnPlayer, rowComputer, columnComputer;
do {
playerInput(rowPlayer, columnPlayer);
// marks player X field choice as taken
boardStatus[rowPlayer][columnPlayer] = true;
player[rowPlayer][columnPlayer] = true;
drawBoard(player, computer);
if (win(player) || draw()){
printWinOrDraw(player, 'X');
break;
}
computerChoice(rowComputer, columnComputer);
std::cout << "O player chooses field (" << rowComputer << "," << columnComputer << "): \n";
// marks player O field choice as taken
boardStatus[rowComputer][columnComputer] = true;
computer[rowComputer][columnComputer] = true;
drawBoard(player, computer);
if (win(computer) || draw()){
printWinOrDraw(computer, 'O');
break;
}
} while (!win(player) || !win(computer) || !draw());
printMenu();
}
void setGame(){
bool player[SIZE][SIZE], computer[SIZE][SIZE];
// all fields on the board are initially marked
// as empty (false)
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++) {
boardStatus[i][j] = false;
player[i][j] = false;
computer[i][j] = false;
}
drawBoard(player, computer);
startGame(player, computer);
}
void printMenu(){
std::cout << "Choose one of following options by entering 1 or 2: "
<< "\n1. Reset the game "
<< "\n2. Exit\n";
int option;
std::cin >> option;
switch(option){
case 1: setGame(); break;
case 2: std::cout << "\nSCORE:\nX | O\n" << score[0] << " : " << score[1] << "\n"; return;
default: std::cout << "Invalid input. Game ends\n"; return;
}
}
int main(){
std::cout << "WELCOME TO THE GAME!\nYou are player X and the computer is player O.\nLet's start the game: \n";
setGame();
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Variable naming needs some work. <code>SIZE</code>, <code>m</code>, <code>ch</code>, <code>counter1</code> etc. could use more thought out names indicating what they do or what they are related to.<br>\nDoes <code>win</code> win the game? Apparently it checks <em>for</em> a win so a rename makes sense here.</p>\n\n<hr>\n\n<p><code>int score[2] = {};</code> while allowed is redundant</p>\n\n<hr>\n\n<p>Separate functions a bit. As it stands now it's somewhat hard to read so consider adding newlines between functions. </p>\n\n<hr>\n\n<p>Look into <a href=\"https://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow noreferrer\">random</a> if you need randomization in your programs.</p>\n\n<hr>\n\n<p>Mostly personal preference but adding braces where possible can save you from nasty bugs in the long run.</p>\n\n<hr>\n\n<p>You have a variable for the board size yet the game breaks in various ways for sizes >3.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T07:31:54.360",
"Id": "416231",
"Score": "0",
"body": "I should have put more thought to naming, I agree. Thank you for the suggestions. If you could clarify a bit more your last suggestion, that would be great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T17:31:39.943",
"Id": "416331",
"Score": "0",
"body": "@J.J Try setting `const int SIZE = 3;` to 4, is the game still playable?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T12:49:17.127",
"Id": "215138",
"ParentId": "214824",
"Score": "3"
}
},
{
"body": "<p>When we include <code><ctime></code>, we get function names in the <code>std</code> namespace. The compiler is also allowed, but not required, to define the same names in the global namespace; we can't rely on those in a portable program.</p>\n\n<p>So we need</p>\n\n<pre><code>std::srand(std::time(0));\n</code></pre>\n\n<hr>\n\n<p>A more serious issue is that the flow of control is all over the place. For example, <code>printMenu()</code> not only displays the menu (as its name would suggest), but it also performs the user's requested action. See if you can make it into a function that displays the menu and <em>returns</em> the user's response, so that it's a reusable service for the caller, rather than taking over the flow of control. The problem you have here is that everything is very tightly <em>coupled</em>, meaning that none of the code can be used in any other program.</p>\n\n<p>To improve the structure, think how to write the program so that either player can be operated by a computer (either in this program, or perhaps via a network protocol) or by a human (by a text or graphical interface, or via the same network protocol). If we can separate the game play from the player interaction, then we have a less tightly coupled program. If you can see how to do that, it's a principle that can be applied more generally, and it will serve you well.</p>\n\n<p>If you find yourself struggling to decouple the parts of the program that are too tightly coupled, then there's a wealth of reading out there, pitched at varying levels - perhaps start with <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID principles</a> and follow the links (both the links to the five principles and the ones in the \"References\" section).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T22:12:33.517",
"Id": "416376",
"Score": "0",
"body": "Readers are invited to suggest other reading - in comments, please."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T22:12:08.630",
"Id": "215302",
"ParentId": "214824",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T08:52:36.427",
"Id": "214824",
"Score": "2",
"Tags": [
"c++",
"beginner",
"array",
"console",
"tic-tac-toe"
],
"Title": "TicTacToe game in C++ made with 2D arrays"
} | 214824 |
<p>I am really new to programming, and I made this simple Tic Tac Toe app in C++. Please tell me what can be improved.</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> toDraw{"1", "2", "3", "4", "5", "6", "7", "8", "9"}; // NOLINT(cert-err58-cpp)
void reset();
void reDrawBoard(bool gameOver);
int playerTurn = 1;
int check(); // 0 - Game in progress; 1 - Player 1 wins; 2 - Player 2 wins;
int turnsPlayed = 0;
int main() {
while (true) {
reDrawBoard(false);
string input;
int inputToInt;
while (true) {
input = "";
cin >> input;
try {
inputToInt = stoi(input);
if (inputToInt > 9) {
cout << "\nInvalid Value. Try again.";
cout << "\nPlayer " + to_string(playerTurn) + ", Enter a number:";
continue;
}
}
catch (exception &e) {
cout << "\nInvalid Value. Try again.";
cout << "\nPlayer " + to_string(playerTurn) + ", Enter a number:";
continue;
}
try {
if (inputToInt == stoi(toDraw.at(static_cast<unsigned long>(inputToInt - 1)))) {
break;
}
}
catch (exception &e) {
cout << "Position already occupied. Please try again.";
cout << "\nPlayer " + to_string(playerTurn) + ", Enter a number:";
continue;
}
}
if (playerTurn == 1) {
toDraw[inputToInt - 1] = "X";
turnsPlayed++;
playerTurn = 2;
} else {
toDraw[inputToInt - 1] = "O";
turnsPlayed++;
playerTurn = 1;
}
int result = check();
if (result == 1) {
reDrawBoard(true);
cout << "PLAYER ONE WINS!!\n";
cout << "Would you like to play again? (Y/N): ";
string response;
cin >> response;
transform(response.begin(), response.end(), response.begin(), ::tolower);
if (response != "y") {
printf("\e[1;1H\e[2J");
return 0;
}
reset();
continue;
}
if (result == 2) {
reDrawBoard(true);
cout << "PLAYER TWO WINS!!\n";
cout << "Would you like to play again? (Y/N): ";
string response;
cin >> response;
transform(response.begin(), response.end(), response.begin(), ::tolower);
if (response != "y") {
printf("\e[1;1H\e[2J");
return 0;
}
reset();
continue;
}
if (turnsPlayed == 9) {
cout << "DRAW!!\n";
cout << "Would you like to play again? (Y/N): ";
string response;
cin >> response;
transform(response.begin(), response.end(), response.begin(), ::tolower);
if (response != "y") {
printf("\e[1;1H\e[2J");
return 0;
}
reset();
}
}
}
void reDrawBoard(bool gameOver) {
printf("\e[1;1H\e[2J");
cout <<
"TIC TAC TOE - Made by Khushraj (a.k.a Holyprogrammer)\nPlayer one in X and Player two is O\n\n | | \n " +
toDraw.at(0) +
" | " + toDraw.at(1) + " | " +
toDraw.at(2) + " \n___|___|___\n | | \n " + toDraw.at(3) + " | " + toDraw.at(4) + " | " +
toDraw.at(5) +
" \n___|___|___\n | | \n " + toDraw.at(6) + " | " + toDraw.at(7) + " | " + toDraw.at(8) +
" \n | | \n\n";
if (!gameOver) {
cout << "Player " + to_string(playerTurn) + ", Enter a number: ";
}
/*
* This prints (something similar to) -
*
* TIC TAC TOE - Made by Khushraj
* Player one is X and Player two is O
*
* | |
* 1 | 2 | 3
* ___|___|___
* | |
* 4 | 5 | 6
* ___|___|___
* | |
* 7 | 8 | 9
* | |
*
* Player <1 || 2>, Enter a number:
*/
}
int check() { // 0 - Game in progress, 1 - Player one wins, 2 - Player two wins
string one = toDraw[0];
string two = toDraw[1];
string three = toDraw[2];
string four = toDraw[3];
string five = toDraw[4];
string six = toDraw[5];
string seven = toDraw[6];
string eight = toDraw[7];
string nine = toDraw[8];
//FOR PLAYER ONE
// If the player has 3X in a row, then
if ((one == "X" && two == "X" && three == "X") || (one == "X" && four == "X" && seven == "X") ||
(one == "X" && five == "X" && nine == "X") || (seven == "X" && five == "X" && three == "X") ||
(seven == "X" && eight == "X" && nine == "X") || (three == "X" && six == "X" && nine == "X") ||
(four == "X" && five == "X" && six == "X") || (two == "X" && five == "X" && six == "X")) {
return 1;
}
//FOR PLAYER TWO
// If the player has 3Y in a row, then
if ((one == "O" && two == "O" && three == "O") || (one == "O" && four == "O" && seven == "O") ||
(one == "O" && five == "O" && nine == "O") || (seven == "O" && five == "O" && three == "O") ||
(seven == "O" && eight == "O" && nine == "O") || (three == "O" && six == "O" && nine == "O") ||
(four == "O" && five == "O" && six == "O") || (two == "O" && five == "O" && eight == "O")) {
return 2;
}
return 0;
}
void reset() {
turnsPlayed = 0;
toDraw = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
playerTurn = 1;
}
</code></pre>
| [] | [
{
"body": "<p>Welcome to programming! Here are some things that may help you improve your program.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. Know when to use it and when not to (as when writing include headers). In this particular case, I happen to think it's perfectly appropriate because it's a single short program and not a header. Some people seem to think it should never be used under any circumstance, but my view is that it can be used as long as it is done responsibly and with full knowledge of the consequences. </p>\n\n<h2>Avoid the use of global variables</h2>\n\n<p>I see that <code>toDraw</code>, <code>playerTurn</code> and <code>turnsPlayed</code> are declared as global variables rather than as local variables. It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable. See the next suggestion.</p>\n\n<h2>Use object orientation</h2>\n\n<p>Because you're writing in C++, it would make sense to collect things into a class such as <code>TicTacToe</code> that could hold the <code>toDraw</code>, <code>playerTurn</code> and <code>turnsPlayed</code> variables, and have <code>reset</code> and <code>reDrawBard</code> be member functions rather than separate functions. You may not yet have learned about objects or classes, but they're one of the main strengths of C++ and something you should learn soon if you haven't already. Use objects where they make sense.</p>\n\n<h2>Use appropriate data types</h2>\n\n<p>The code currently contains this code:</p>\n\n<pre><code>int check() { // 0 - Game in progress, 1 - Player one wins, 2 - Player two wins\n string one = toDraw[0];\n string two = toDraw[1];\n string three = toDraw[2];\n string four = toDraw[3];\n string five = toDraw[4];\n string six = toDraw[5];\n string seven = toDraw[6];\n string eight = toDraw[7];\n string nine = toDraw[8];\n\n //FOR PLAYER ONE\n // If the player has 3X in a row, then\n if ((one == \"X\" && two == \"X\" && three == \"X\") || (one == \"X\" && four == \"X\" && seven == \"X\") ||\n (one == \"X\" && five == \"X\" && nine == \"X\") || (seven == \"X\" && five == \"X\" && three == \"X\") ||\n (seven == \"X\" && eight == \"X\" && nine == \"X\") || (three == \"X\" && six == \"X\" && nine == \"X\") ||\n (four == \"X\" && five == \"X\" && six == \"X\") || (two == \"X\" && five == \"X\" && six == \"X\")) {\n return 1;\n }\n</code></pre>\n\n<p>First, the comment is good, but the whole function could be improved if it instead returned an <code>enum</code> or even better, an <code>enum class</code>:</p>\n\n<pre><code>enum class GameState { inProgress, Player1Wins, Player2Wins, Tie };\n</code></pre>\n\n<p>Now we can use names instead of values and we are also assured that the return value <em>must</em> be one of these instead of any possible <code>int</code> value.</p>\n\n<p>Second, creating and naming all of those strings every time is both potentially slow and prone to error. In fact ...</p>\n\n<h2>Fix the bug</h2>\n\n<p>Part of the current logic for checking for a win as shown above is this:</p>\n\n<pre><code>|| (two == \"X\" && five == \"X\" && six == \"X\")) {\n</code></pre>\n\n<p>That should be squares <code>two</code>, <code>five</code> and <code>eight</code>, not <code>six</code>. I'd recommend rewriting the <code>check</code> function entirely to avoid this.</p>\n\n<h2>Think carefully about the problem</h2>\n\n<p>By definition, only the player who just played can win, so instead of checking for both <code>X</code> and <code>O</code> wins each time, we can pass in a variable which indicates which player just played and only check that. </p>\n\n<h2>Make sure to <code>#include</code> all required headers</h2>\n\n<p>This program calls <code>printf</code> but does not include the corresponding header. Fix that by adding this line:</p>\n\n<pre><code>#include <cstdio>\n</code></pre>\n\n<p>Or better yet...</p>\n\n<h2>Don't mix <code>printf</code> and <code>iostream</code></h2>\n\n<p>There's little reason to require both <code><cstdio></code> and <code><iostream></code> in this program. Everywhere there is a <code>printf</code> could instead be a <code>std::cout <<</code> instead.</p>\n\n<h2>Don't use non-standard escape sequences</h2>\n\n<p>The <code>\\e</code> escape sequence, while common, is not a <a href=\"https://en.cppreference.com/w/cpp/language/escape\" rel=\"nofollow noreferrer\">standard escape sequence</a>. Instead, you could use <code>\\x27</code> or <code>\\033</code>.</p>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>There is a lot of repeated code here that only differs by which player token is being considered. Instead of repeating code, it's generally better to make common code into a function.</p>\n\n<h2>Eliminate magic numbers</h2>\n\n<p>The constants 3, 9 and the string <code>\"\\e[1;1H\\e[2J\"</code> are used in multiple places. It would be better to have them as named <code>const</code> values so that it would be clear what those numbers and string represent.</p>\n\n<h2>Declare the loop exit condition at the top</h2>\n\n<p>The <code>while</code> loop inside <code>main</code> currently says this:</p>\n\n<pre><code>while (true) {\n</code></pre>\n\n<p>but the loop doesn't really continue forever -- it exits when the player decides to quit the game. For that reason, I'd suggest instead that it be something like this:</p>\n\n<pre><code>bool playing = true;\nwhile (playing) {\n</code></pre>\n\n<p>Then just set the condition within the loop at the appropriate place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:21:52.760",
"Id": "415495",
"Score": "0",
"body": "Thanks a lot. I'll change whatever I can and post back."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:55:16.653",
"Id": "415498",
"Score": "0",
"body": "I'm glad it was useful to you. Just remember not the change the code in this question but ask a new one. See [What to do when someone answers](/help/someone-answers)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:08:20.957",
"Id": "214846",
"ParentId": "214827",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "214846",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T09:28:12.737",
"Id": "214827",
"Score": "3",
"Tags": [
"c++",
"beginner",
"tic-tac-toe"
],
"Title": "Simple Tic Tac Toe game in C++"
} | 214827 |
<p>I am learning about one of the hardest parts of Audio development: the synchronization between the audio thread and the GUI thread. Per the discussion here <a href="https://forum.juce.com/t/timur-doumler-talks-on-c-audio-sharing-data-across-threads/26311" rel="nofollow noreferrer">https://forum.juce.com/t/timur-doumler-talks-on-c-audio-sharing-data-across-threads/26311</a> and here: <a href="https://stackoverflow.com/questions/15460829/lock-free-swap-of-two-unique-ptrt">https://stackoverflow.com/questions/15460829/lock-free-swap-of-two-unique-ptrt</a>
I'm wondering if the following class solves the problem or comes close to solving it. </p>
<pre><code>template<typename T>
struct SmartAtomicPtr
{
SmartAtomicPtr( T* newT )
{
update( newT );
}
~SmartAtomicPtr()
{
update(nullptr);
}
void update( T* newT, std::memory_order ord = memory_order_seq_cst )
{
keepAlive.reset( atomicTptr.exchange( newT, ord ) );
}
std::shared_ptr<T> getShared(std::memory_order ord = memory_order_seq_cst)
{
return std::make_shared<T>( atomicTptr.load(ord) );
}
T* getRaw(std::memory_order ord = memory_order_seq_cst)
{
return atomicTptr.load(ord);
}
private:
std::atomic<T*> atomicTptr{nullptr};
std::shared_ptr<T> keepAlive;
};
</code></pre>
<p>I know that whatever value ends up in the shared_ptr won't be deleted until the <code>SmartAtomicPtr</code> goes out of scope, which is fine. </p>
<p>the ultimate goal would be a lock-free, wait-free solution.</p>
<p>an example of where this might get used is the following interleaving of the audio and message thread. The goal is to keep the returned object from dangling</p>
<pre><code>/*
AudioProcessor owns a SmartAtomicPtr<T> ptr that the message
thread has public access to.
*/
/* audio thread */ auto* t = ptr.getRaw();
/* message thread */ processor.ptr.update( new T() );
/* audio thread */ t->doSomething(); //t is a dangling pointer now
</code></pre>
<p>with getShared(), I believe that <code>t</code> no longer dangles:</p>
<pre><code>/* audio thread */ auto t = ptr.getShared();
/* message thread */ processor.ptr.update( new T() );
/* audio thread */ t->doSomething(); //t is one of 2 shared_ptrs
//holding the previous atomic value of ptr
</code></pre>
<p>I ran into some double-deletes, but I believe I have solved them, and also prevented the shared_ptr member from being stomped on in the event you call <code>getShared()</code> and <code>update()</code> at the same time, and also kept it leak-free. </p>
<p>any thoughts?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:12:20.523",
"Id": "415490",
"Score": "0",
"body": "From C++20, there's [`std::atomic<shared_ptr<T>>`](https://en.cppreference.com/w/cpp/memory/shared_ptr/atomic2) partial specialization. You'll want to understand how it works if you're implementing your own."
}
] | [
{
"body": "<p><code>keepAlive.reset</code> is not thread safe. So your class as a whole cannot be thread safe.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:13:48.630",
"Id": "415492",
"Score": "0",
"body": "Concrete proof that a short answer can be a great answer - good one!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-17T05:54:15.197",
"Id": "417087",
"Score": "0",
"body": "thanks @ratchet. I ended up using a couple FIFOs and a lot of std::move() to ensure construction and destruction happened on the gui thread, even though usage was happening on the audio thread for my project."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T12:41:55.063",
"Id": "214832",
"ParentId": "214829",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214832",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T11:00:10.943",
"Id": "214829",
"Score": "1",
"Tags": [
"c++",
"pointers",
"audio",
"lock-free",
"atomic"
],
"Title": "Passing objects atomically across threads without locks or data races for audio synchronization"
} | 214829 |
<p>TL;DR I'm self teaching VBA, learning about functions and passing arguments from a subroutine into the function and want to know if my very basic function to define a range is optimal and follows correct referencing/standards/practices.</p>
<p>I'm teaching myself VBA (mostly in MS Excel) as a starting point into programming in my spare time (what little of it I have) with the goal of a career change and am now learning how to utilise functions. </p>
<p>Below is a function I have written to define a range based on the variables passed as arguments. As you will see the worksheet, first row and first column are required arguments and the second row and second column are optional. </p>
<p>The function will assign the value of the first row (or column) to the second row (or column) if the optional argument is omitted. </p>
<pre><code>Function defineRange(mySheet As Object, startRow As Long, firstColumn As Long, Optional endRow As Long, Optional secondColumn As Long) As Object
'will create a single row range
If endRow = 0 Then
endRow = startRow
End If
'will create a single column range
If secondColumn = 0 Then
secondColumn = firstColumn
End If
'Define the A1 reference for the range with cells.address parameter using arguments as the row and column index.
Set defineRange = mySheet.Range(Cells(startRow, firstColumn).Address, Cells(endRow, secondColumn).Address)
End Function
</code></pre>
<p>As an <strong>example</strong> I'd call it from a subroutine as follows: </p>
<pre><code>Sub test()
Dim myRange As Object
Set myRange = defineRange(ThisWorkbook.Sheets(1), 5, 2, 10, 4)
myRange.Select
End Sub
</code></pre>
<p>The result is <code>Range("B5:D10")</code> is selected on <code>sheet1</code> of the workbook.</p>
<p>Is the function code optimal?
Have best practices been followed?</p>
| [] | [
{
"body": "<p>First, kudos for teaching yourself VBA - I was once in your shoes and how I wish I could have had Code Review to help me back then!</p>\n\n<p>Let's start with the function's <em>signature</em>:</p>\n\n<blockquote>\n<pre><code>Function defineRange(mySheet As Object, startRow As Long, firstColumn As Long, Optional endRow As Long, Optional secondColumn As Long) As Object\n</code></pre>\n</blockquote>\n\n<p>It's not clear whether the function's implicit public accessibility is intended or not. If it means to be accessible from outside the module it's declared in, then it should be explicitly <code>Public</code>. Otherwise, it should be <code>Private</code> - a private procedure/function/method can only be invoked from within the module it belongs to. I'm thinking the intent is for it to be <code>Public</code> here.</p>\n\n<p>You probably noticed pretty much everything in VBA type libraries is <code>PascalCase</code>. From <code>Range</code> to <code>Worksheet.Name</code> - best practice is to \"blend in\" and write code that adheres to the naming standard. Hence, <code>DefineRange</code> would be better. I like how the name begins with a verb (as it should!), however \"define\" doesn't strike me as the best choice in this case. The function is <em>getting</em>, or rather <em>acquiring</em> a <code>Range</code> object. The Excel object model already provides an API for this, so <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinventing-the-wheel'\" rel=\"tag\">reinventing-the-wheel</a> is appropriate here :)</p>\n\n<p>The parameters are all implicitly passed <em>by reference</em> (<code>ByRef</code>), which is an unfortunate default. Would this be expected/desired behavior?</p>\n\n<pre><code>Dim firstRow As Long\nfirstRow = 12\n\nDim lastRow as Long\nlastRow = 0\n\nDim target As Range\nSet target = defineRange(Sheet1, firstRow, 1, lastRow)\n\nDebug.Print lastRow ' prints 12, not 0. is that expected?\n</code></pre>\n\n<p>By passing the parameters <code>ByVal</code>, instead of passing a <em>pointer</em> (\"reference\") to the value, you essentially pass a <em>copy</em> of that value, and the calling code's variables can't get modified by the function. In VB.NET and many other languages, the implicit default is to pass arguments <em>by value</em>: it's somewhat rare that a parameter <em>needs</em> to be passed by reference.</p>\n\n<p><code>mySheet</code> is declared as an <code>Object</code>, which means the function will happily take a <code>Collection</code>, some <code>UserForm1</code>, any <code>Range</code>, or even <code>MyClass</code> for this <code>mySheet</code> parameter... and then the <code>mySheet.Range</code> call will fail at run-time with error 438 \"can't find property or method\" (unless there's a method named <code>Range</code> on that <code>UserForm1</code> or <code>MyClass</code> object, of course). By declaring it <code>As Object</code>, you made every member calls against that object <em>late-bound</em>, meaning the compiler can't help you, and will happily let you try to invoke <code>mySheet.Rnge</code>.</p>\n\n<p>It's usually best to avoid deferring failures to run-time, and fail at compile-time instead, whenever possible. We do this with <em>early binding</em>, by declaring objects using a specialized interface we know we can work with - in this case, <code>Excel.Worksheet</code>, or just <code>Worksheet</code>. We can do this, because when VBA is hosted in Excel, the VBA project is guaranteed to have a reference to the <code>Excel</code> type library. If we were hosted in Word or PowerPoint, we would have to explicitly add that reference (through tools/references), or work late-bound and keep it <code>As Object</code>.</p>\n\n<p>The parameter names are meant to be pairs, but they're inconsistent:</p>\n\n<ul>\n<li><strong>start</strong>Row, <strong>end</strong>Row</li>\n<li><strong>first</strong>Column, <strong>second</strong>Column</li>\n</ul>\n\n<p>\"Start/End\" was a better, clearer idea than \"First/Second\" - I'd go and rename the parameters to have <code>startColumn</code> and <code>endColumn</code>, matching <code>startRow</code> and <code>endRow</code>.</p>\n\n<p>Kudos for declaring an explicit return type - all <code>Function</code> procedures return something, whether you declare a return type or not. Then again, it would be better to return a <code>Range</code> rather than an <code>Object</code>.</p>\n\n<p>So, that covers the function's signature :)</p>\n\n<hr>\n\n<p>There are a number of possible bugs and edge cases that should be handled. The first thing any function should do, is validate its inputs.</p>\n\n<p>VBA doesn't have unsigned integer types, so a <code>Long</code> could very well be a negative number, or it could be zero -- but Excel's object model isn't going to like you trying to get the cell at row <code>0</code> and column <code>-728</code>.</p>\n\n<p>There are several ways to deal with this. The simplest is to use <code>Debug.Assert</code> at the very top of the function, i.e. halt program execution if assumptions aren't validated:</p>\n\n<pre><code>'Debug.Assert TypeOf mySheet Is Excel.Worksheet\nDebug.Assert startRow > 0\nDebug.Assert firstColumn > 0\n</code></pre>\n\n<p>Another way is to have a <em>guard clause</em>, again at the very top of the function, that explicitly throws an error given invalid arguments:</p>\n\n<pre><code>If startRow > 0 Then Err.Raise 5, \"defineRange\", \"Argument 'startRow' must be greater than zero.\"\nIf firstColumn > 0 Then Err.Raise 5, \"defineRange\", \"Argument 'firstColumn' must be greater than zero.\"\n</code></pre>\n\n<p>One advantage of using <em>guard clauses</em>, is that if a function is given arguments it cannot possibly work with, then we <strong>fail early</strong>. This makes it easier to debug if something goes wrong later: instead of dealing with a cryptic and rather useless \"Method 'Range' of class 'Worksheet' failed\" error, the code that tried to invoke our function now knows exactly what went wrong, and how to fix it.</p>\n\n<p>The return value assignment will fail if <code>mySheet</code> isn't the <code>ActiveSheet</code>:</p>\n\n<pre><code>mySheet.Range(Cells(startRow, firstColumn).Address, Cells(endRow, secondColumn).Address)\n</code></pre>\n\n<p>That's because the unqualified <code>Cells</code> calls are context-dependent.</p>\n\n<p>If the function is written in a worksheet module's code-behind, then it's implicitly <code>Me.Cells</code>.</p>\n\n<p>If the function is written anywhere else, then it's implicitly <code>[_Global].Cells</code>, which ultimately resolves to <code>ActiveSheet.Cells</code>. That isn't a problem if <code>mySheet</code> is active, but then if it isn't...</p>\n\n<pre><code>Sheet1.Range(Sheet2.Cells(...), Sheet2.Cells(...))\n</code></pre>\n\n<p>That's guaranteed to throw the dreaded run-time error 1004 \"application-defined error\", because only <a href=\"https://en.wikipedia.org/wiki/Schr%C3%B6dinger%27s_cat\" rel=\"nofollow noreferrer\">Schrödinger's Range</a> can belong to two worksheets at the same time.</p>\n\n<p>You can fix this with a <code>With</code> block:</p>\n\n<pre><code>With mySheet\n Set defineRange = .Range(.Cells(startRow, firstColumn).Address, .Cells(endRow, secondColumn).Address)\nEnd With\n</code></pre>\n\n<p>Note the <code>.</code> dereferencing operators qualifying the <code>Cells</code> member calls with the object reference held by the <code>With</code> block. It's equivalent to this:</p>\n\n<pre><code>Set defineRange = mySheet.Range(mySheet.Cells(startRow, firstColumn).Address, mySheet.Cells(endRow, secondColumn).Address)\n</code></pre>\n\n<p>That said, you don't need to work off the <code>.Address</code> string: <code>Range</code> is more than happy to work with the <code>Range</code> references returned by <code>Cells(...)</code>:</p>\n\n<pre><code>Set defineRange = mySheet.Range(mySheet.Cells(startRow, firstColumn), mySheet.Cells(endRow, secondColumn))\n</code></pre>\n\n<p>While that works, I find it quite a mouthful, and as shown above, it has too many reasons to fail to my taste - I'd probably split it up:</p>\n\n<pre><code>Dim startCell As Range\nSet startCell = mySheet.Cells(startRow, firstColumn)\n\nDim endCell As Range\nSet endCell = mySheet.Cells(endRow, secondColumn)\n</code></pre>\n\n<p>Making the return assignment rather trivial:</p>\n\n<pre><code>Set defineRange = mySheet.Range(startCell, endCell)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T18:11:40.653",
"Id": "415518",
"Score": "0",
"body": "Fantastic! The functions signature section has cleared up all the bits I didn't quite understand. Learning is definately made a billion times easier with use of sites like this and SO. In the bugs/edge cases section I recieved a runtime error when `.Address` wad missing from the `Range` references - I think it was the dreaded Runtime error 1004. I prefer the code without `.Address` so I'll look into that further. I funnily enough had split the range reference as you mentioned inittialy but ended up cramming it all into the one line. Overall it seems I did okay!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T19:25:51.467",
"Id": "415526",
"Score": "1",
"body": "@SamuelEverson something isn't adding up, `.Address` shouldn't be needed. I've just now executed `?range(cells(1,1),cells(2,2)).address` in the immediate pane and got `$A$1:$B$2` as an output, as expected. The error would have to have been caused by something else. One thing I didn't mention, is the indentation: while generally consistent, `Function...End Function` blocks (i.e. procedure scopes) denote scopes and should prompt an indent level. Also, see if [Rubberduck](http://www.github.com/rubberduck-vba/Rubberduck)'s code inspections can find more potential issues =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T21:24:47.103",
"Id": "415536",
"Score": "0",
"body": "yes I agree. I probably won't be able to recreate the error I was getting (that seemed to be caused by the missing `.Address`) as I made a fair few changes throughout writing the code but if I figure it out I'll be sure to share the results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T10:55:31.643",
"Id": "415762",
"Score": "0",
"body": "I did some debuging and I have put the above mentioned issue with `.Address` down to me incorrectly declaring something somewhere when I originally tested the code. I've made adjustments per your review and it all works as expected (except the description of the `Err.Raise` method is not appearing - the default description appears) but I'm looking into that to work out why."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:48:10.727",
"Id": "214848",
"ParentId": "214833",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214848",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T13:05:39.897",
"Id": "214833",
"Score": "5",
"Tags": [
"vba",
"excel",
"reinventing-the-wheel"
],
"Title": "Define a range based on passed arguments"
} | 214833 |
<p>I am working on this <a href="https://www.hackerrank.com/contests/hack-it-to-win-it-paypal/challenges/q4-traveling-is-fun/problem" rel="nofollow noreferrer">HackerRank</a> problem but running into time constraint issues.</p>
<p>Basically, given two arrays, we need to determine if the ith element of the second array is reachable by the ith element of the first array, where edges are determined by whether or not the gcd of the two node values is greater than some threshold. Below is my attempt but it times out for large inputs.</p>
<pre><code>def computeGCD(x, y):
while(y):
x, y = y, x % y
return x
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in graph.keys():
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
def connectedCities(n, g, originCities, destinationCities):
res = []
graph = {i+1:[] for i in range(n)}
for i in originCities:
for j in range(n):
if i != j+1 and computeGCD(i, j+1) > g:
graph[i].append(j+1)
for i in range(len(originCities)):
paths = find_all_paths(graph, originCities[i], destinationCities[i])
if len(paths) > 0:
res.append(1)
else:
res.append(0)
return res
</code></pre>
<p>Can you help me determine if there is something I can be doing more efficiently here, or if solving this via a graph is even the most appropriate way?</p>
| [] | [
{
"body": "<blockquote>\n<pre><code>def computeGCD(x, y):\n</code></pre>\n</blockquote>\n\n<p>Just call it <code>gcd</code>. It's part of a computer program: you don't need to say that it computes.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> graph = {i+1:[] for i in range(n)}\n for i in originCities:\n for j in range(n):\n if i != j+1 and computeGCD(i, j+1) > g:\n graph[i].append(j+1)\n</code></pre>\n</blockquote>\n\n<p>This is buggy: it doesn't build the whole graph. Consider test case <code>connectedCities(16, 1, [14], [15])</code>: there is a path <code>14 -- 6 -- 15</code> with GCDs respectively <code>2</code> and <code>3</code>.</p>\n\n<p>As a matter of style, I would find the code more readable if it iterated over <code>range(1, n+1)</code> and didn't have to continually increment the variable.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for i in range(len(originCities)):\n paths = find_all_paths(graph, originCities[i], destinationCities[i])\n if len(paths) > 0:\n res.append(1)\n else:\n res.append(0)\n</code></pre>\n</blockquote>\n\n<p>Spot the big performance problem: to determine whether any foo exists, it suffices to find one foo. You don't need to find every foo in the universe and then count them.</p>\n\n<p>But just fixing that still leaves a smaller performance problem: if there are a lot of queries (i.e. if <code>originCities</code> and <code>destinationCities</code> are long) then it's quicker to do an expensive preprocessing to get an object which answers queries fast than it is to evaluate each query separately. As a big hint, in graph-theoretic terms the queries are \"<em>Are these two vertices in the same connected component?</em>\".</p>\n\n<p>Note that if you really want to squeeze the asymptotic complexity (and it's not too bad for practical performance either), <span class=\"math-container\">\\$O(n \\lg \\lg n + q)\\$</span> is achievable<sup>1</sup> where <span class=\"math-container\">\\$q\\$</span> is the number of queries.</p>\n\n<p><sub><sup>1</sup> Technically there's also a factor of <span class=\"math-container\">\\$\\alpha(n)\\$</span> where <span class=\"math-container\">\\$\\alpha\\$</span> is the inverse Ackermann function, but for practical purposes it's constant.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T11:52:06.650",
"Id": "415595",
"Score": "0",
"body": "Incidentally, it's a fun exercise to consider what nasty test cases you can come up with to punish different implementation approaches. E.g. `connectedCities(1000000, 0, [12345], [67890])` can be solved instantaneously; now generalise that trick... This question has great potential for a long-form interview discussion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:17:55.667",
"Id": "214899",
"ParentId": "214847",
"Score": "1"
}
},
{
"body": "<p>Solving this via a graph algorithm is probably the way to go. However your <code>find_all_paths</code> algorithm is not the right tool.</p>\n\n<p>Instead, what you need to find are the connected components of this graph. Then, if two vertices are not in the same component, there is no way between them and you can return zero.</p>\n\n<p>With this you can solve the actual connected part in linear time (on top of this you will still have the building of the graph, which will be quadratic in time because of the finding of the edges).</p>\n\n<p>First, though, let's have a look at your graph building. It needs to process all combinations of <code>i</code> and <code>j</code>, not just the ones starting from an origin city, because otherwise cities that are connected via two or more hops will not be marked as connected.</p>\n\n<p>Also, the <code>math</code> module, included in the standard library, also has a <code>gcd</code> function. After testing, that one seems to be about a factor two faster than your implementation.</p>\n\n<pre><code>from collections import defaultdict\nfrom math import gcd\nfrom itertools import count\n\ndef build_graph(n, g):\n graph = defaultdict(set) # don't care if we add a connection more than once\n for i in range(1, n + 1):\n if i not in graph: # ensure even stand-alone nodes are in the graph\n graph[i] = set()\n for j in range(1, n + 1):\n if i != j and gcd(i, j) > g:\n graph[i].add(j)\n graph[j].add(i) # make connections bi-directional\n return graph\n</code></pre>\n\n<p>Now we need to implement a way to find all nodes, starting from one start node, for example depth-first search:</p>\n\n<pre><code>def dfs(graph, start, visited):\n yield start\n visited.add(start)\n for node in graph[start]:\n if node in visited:\n continue\n yield from dfs(graph, node, visited)\n</code></pre>\n\n<p>With this implementation we could just directly solve the problem like this:</p>\n\n<pre><code>def connectedCities(n, g, originCities, destinationCities):\n graph = build_graph(n, g)\n connected_cities = {i: set(dfs(graph, i, set())) for i in originCities}\n return [dest in connected_cities\n for orig, dest in zip(originCities, destinationCities)]\n</code></pre>\n\n<p>However, it still has hidden quadratic behaviour, since the depth-first search is performed starting from every origin city, resetting the visited <code>set</code> each time. Instead keep it around and give all nodes that you get from one starting node the same component label:</p>\n\n<pre><code>def get_components(graph):\n assignments, visited = {}, set()\n for label, node in enumerate(graph):\n if node in visited:\n continue\n assignments.update(dict.fromkeys(dfs(graph, node, visited), label))\n return assignments\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>graph = {1:[2,3], 2:[1], 3:[1], 4:[5], 5:[4]}\nget_components(graph)\n# {1: 0, 2: 0, 3: 0, 4: 3, 5: 3}\n</code></pre>\n\n<p>With some extra work the labels cold be made contiguous, but here it is enough that they are unique. Now, two cities have a connection, iff they are in the same component, i.e. if their assigned component label is the same:</p>\n\n<pre><code>def connectedCities(n, g, originCities, destinationCities):\n graph = build_graph(n, g)\n component = get_components(graph)\n return [int(component[orig] == component[dest])\n for orig, dest in zip(originCities, destinationCities)]\n</code></pre>\n\n<p>This passes the three sample inputs given in the problem description. I don't have a HackerRank account so I can't test if it is fast enough, though.</p>\n\n<p>In the end it is <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span> for the building of the graph, <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> for finding the connected components and afterwards <span class=\"math-container\">\\$\\mathcal{O}(q)\\$</span>, with <span class=\"math-container\">\\$q\\$</span> being the length of <code>originCities</code> and <code>destinationCities</code> for the querying.</p>\n\n<hr>\n\n<p>Here are two possible optimizations on this:</p>\n\n<ol>\n<li><p>Note that when we added an edge between <code>i</code> and <code>j</code>, we also added an edge between <code>j</code> and <code>i</code>, so <code>j</code> does not need to run over all values anymore, only those larger than <code>i</code> (since all other combinations have already been explored):</p>\n\n<pre><code>def build_graph(n, g):\n graph = defaultdict(set) # don't care if we add a connection more than once\n for i in range(1, n + 1):\n if i not in graph: # ensure even stand-alone nodes are in the graph\n graph[i] = set()\n for j in range(i + 1, n + 1):\n if gcd(i, j) > g:\n graph[i].add(j)\n graph[j].add(i) # make connections bi-directional\n return graph\n</code></pre></li>\n<li><p>To avoid the recursion limit, implement the depth-first search using a stack of yet-to-be-visited nodes:</p>\n\n<pre><code>def dfs(graph, start, visited):\n out = {start}\n visited.add(start)\n to_visit = graph[start]\n while to_visit:\n node = to_visit.pop() # this actually modifies `graph`, careful...\n if node in visited:\n continue\n out.add(node)\n visited.add(node)\n to_visit |= graph[node] - visited\n return out\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:05:48.683",
"Id": "415638",
"Score": "1",
"body": "Really appreciate the thoughts and help. I tried running your code and unfortunately it does still time out on two of the test cases (before it timed out on 7 so it is an improvement) and it gave the wrong answer for five test cases. I'll take what you have provided me and see if I can dig deeper to see what is going on with these 5 that are wrong and the two that still time out..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:04:08.720",
"Id": "415650",
"Score": "0",
"body": "@user9592573: Let me know if you figure out a failing testcase. Maybe it's something simple as empty graphs..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:13:34.393",
"Id": "415652",
"Score": "1",
"body": "I can give you a slow one: `print(connectedCities(10000, 1, [10, 4, 3, 6], [3, 6, 2, 9]))`. There are various heuristics one can implement to reduce the need to precompute connected components, and this is one example of how that can make a big difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:16:52.753",
"Id": "415654",
"Score": "0",
"body": "@PeterTaylor: That *does* take quite some time. And then it hits the recursion limit :) There are a lot of optimizations left in how you build the graph, I guess. And since that part is quadratic it is also where the most benefits are to be gained."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:17:41.383",
"Id": "415655",
"Score": "0",
"body": "I take that back: it's not slow, it dies with `RecursionError: maximum recursion depth exceeded in comparison`. So maybe large `n` is where the automated tester is failing the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:50:20.287",
"Id": "415663",
"Score": "0",
"body": "@PeterTaylor: Added a non-recursive/non-generator implementation for the depth-first search and an optimization for `build_graph` that solves the example given by you in 25s. Probably still too slow, but at least it no longer crashes..."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:42:32.413",
"Id": "214904",
"ParentId": "214847",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:45:11.837",
"Id": "214847",
"Score": "1",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded",
"graph"
],
"Title": "Determine whether a node is reachable"
} | 214847 |
<p>I have implemented a simple binary search tree class in C++ using <code>std::unique_ptr</code> objects to hold the pointers to each node. In doing this I have come across a situation that is somewhat questionable in the <code>Delete</code> method. Since I can't copy the unique pointers, but I need a way to traverse the tree with a "temporary" pointer, I had to resort to using a raw pointer to do the traversal.</p>
<p>This is the section I am talking about (In the <code>Delete</code> method):</p>
<pre><code>// Need to use a raw pointer because I can't assign to a std::unique_ptr
Node* n = node.get();
while (n->right) {
// Using a reference to a unique_ptr instead of a raw pointer will cause this line to fail to compile
n = n->right.get();
}
</code></pre>
<p>Is this an acceptable thing to do?</p>
<p>It compiles and runs. And since the underlying pointer is still managed by a unique_ptr object it will be deleted properly. Everything about this works fine, but it just doesn't feel right for some reason.</p>
<p>The full source code is shown below (Feel free to comment on anything else that may be improved as well):</p>
<pre><code>#include <iostream>
#include <memory>
using std::make_unique;
using std::unique_ptr;
template <typename T>
class Tree {
struct Node {
Node(const T& value)
: value(value), left(nullptr), right(nullptr) {}
T value;
unique_ptr<Node> left;
unique_ptr<Node> right;
};
public:
Tree() : root_(nullptr) {}
// Insert a value into the tree
void Insert(const T& value) {
Insert(root_, value);
}
// Delete a value from the tree
bool Delete(const T& value) {
return Delete(root_, value);
}
// Search the tree for a node and return true if it is found
bool Contains(const T& value) const {
return Contains(root_, value);
}
private:
void Insert(unique_ptr<Node>& node, const T& value) {
if (not node) {
node = make_unique<Node>(value);
}
else {
value < node->value
? Insert(node->left, value)
: Insert(node->right, value);
}
}
bool Delete(unique_ptr<Node>& node, const T& value) {
if (not node) {
return false;
}
else if (value == node->value) {
if (node->left) {
unique_ptr<Node>& right = node->right;
node = move(node->left);
if (right) {
// Need to use a raw pointer because I can't assign to a std::unique_ptr
Node* n = node.get();
while (n->right) {
// Using a reference to a unique_ptr instead of a raw pointer will cause this line to fail to compile
n = n->right.get();
}
n->right = move(right);
}
}
else {
node = move(node->right);
}
return true;
}
else {
return value < node->value
? Delete(node->left, value)
: Delete(node->right, value);
}
}
bool Contains(const unique_ptr<Node>& node, const T& value) const {
if (not node) {
return false;
}
else if (node->value == value) {
return true;
}
else {
return value < node->value
? Contains(node->left, value)
: Contains(node->right, value);
}
}
unique_ptr<Node> root_;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T16:11:19.777",
"Id": "415502",
"Score": "1",
"body": "As to your specific question: it might be a matter of opinion, but I'd say that a raw pointer is exactly correct for referencing something you don't own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T16:14:35.453",
"Id": "415504",
"Score": "1",
"body": "Is there a reason you can't use `std::shared_ptr`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T16:43:49.847",
"Id": "415505",
"Score": "1",
"body": "@tinstaafl, I could implement the whole thing using `std::shared_ptr`, but using `std::unique_ptr` is generally more efficient (theres no extra memory overhead and move operations are faster than copy). I guess using a raw pointer to refer to something owned by a `std::unique_ptr` is essentially the same as creating a `std::weak_ptr` from a `std::shared_ptr`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:20:03.800",
"Id": "415510",
"Score": "0",
"body": "@tjwrona1992, IIRC having weak ptr locks object counter on shared ptr, thus forcing it to exist a little while longer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T15:31:29.520",
"Id": "415811",
"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)*."
}
] | [
{
"body": "<h2>On raw and smart pointers</h2>\n<p>First, I'll address your specific question, about using a raw pointer to refer to nodes in the tree. I believe you're doing exactly the right thing here, because smart pointers convey information about <strong>ownership</strong> of the resource.</p>\n<p>We are looking at nodes that are owned by the tree (actually, each node is owned by its parent), and it's entirely appropriate that that ownership is encoded as a <code>std::unique_ptr</code>; that says that this is the only place that's responsible for deleting the node when it's no longer required.</p>\n<p>Our <code>Delete</code> method walks nodes from the root downwards; it needs to refer to the nodes, but only during the execution of the method (it doesn't store pointers anywhere). A raw pointer is perfectly suitable here.</p>\n<hr />\n<h2>General review</h2>\n<p>Is <code><iostream></code> used anywhere? I think it can be omitted.</p>\n<p>If this is a header file, avoid bringing <code>std::make_unique</code> and <code>std::unique_ptr</code> into the global namespace, as that will affect every file that includes the header. It's reasonable to do so inside the function bodies, but at that point it's likely better to simply use the qualified names. Including them within the scope of the type is a middle ground where opinions will differ.</p>\n<p>We should include <code><utility></code> for <code>std::move</code> (and the same comments apply to importing that name into <code>::</code>).</p>\n<p>Consider turning tests around to test a positive first, which slightly reduces cognitive load. Instead of:</p>\n<blockquote>\n<pre><code>if (not node) {\n node = make_unique<Node>(value);\n}\nelse {\n value < node->value\n ? Insert(node->left, value)\n : Insert(node->right, value);\n}\n</code></pre>\n</blockquote>\n<p>This is easier to reason about:</p>\n<pre><code>if (node) {\n value < node->value\n ? Insert(node->left, value)\n : Insert(node->right, value);\n}\nelse {\n node = make_unique<Node>(value);\n}\n</code></pre>\n<p>Actually, that ternary can be narrowed to within the argument list (you can add more parens according to taste):</p>\n<pre><code>if (node) {\n Insert(value < node->value ? node->left : node->right, value);\n}\nelse {\n node = make_unique<Node>(value);\n}\n</code></pre>\n<p>On a related note, if we return early from within <code>if</code>, we can just flow into the next code without <code>else</code>:</p>\n<blockquote>\n<pre><code>if (not node) {\n return false;\n}\nelse if (node->value == value) {\n return true;\n}\nelse {\n return value < node->value\n ? Contains(node->left, value)\n : Contains(node->right, value);\n}\n</code></pre>\n</blockquote>\n<p>That can become</p>\n<pre><code>if (not node) {\n return false;\n}\nif (node->value == value) {\n return true;\n}\n\nreturn Contains(value < node->value ? node->left : node->right, value);\n</code></pre>\n<p>We might be able to remove some repetition by adding a method to find the insertion point for a value - <code>Contains()</code> can return true if that insertion point has a value that compares equal, and <code>Delete()</code> can start from that point in removing the value.</p>\n<p>If the tree could be large, then perhaps iteration may be better than recursion for walking the tree. That means we'll need pointers in some places where we currently have references, and some things may have to lose <code>const</code> qualification, but may give a performance improvement and save on stack usage (or may not, depending on how your compiler manages to optimise the recursive call - always check these things!).</p>\n<hr />\n<h1>Further directions</h1>\n<p>Try to evolve the public interface to supporting <em>standard container</em> operations. This probably begins with creating iterators and the member functions that return them.</p>\n<p>Consider maintaining a <em>balanced</em> tree - you'll want to read up on the theory if you're not already familiar with the techniques to do this.</p>\n<p>You haven't shown your unit tests here, but it's worthwhile occasionally running them with a memory checker such as Valgrind. As well as ensuring we don't leak memory, that will also help identify any uses of dangling pointers or uninitialized values, which an ordinary run might not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T19:12:10.477",
"Id": "415522",
"Score": "0",
"body": "How would I go about turning the recursion into iteration? I've heard that it can be much more efficient to do things that way but I can't really see how it should be done. Are there any good examples on how to do this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T19:17:52.540",
"Id": "415524",
"Score": "0",
"body": "And as for the other comments - iostream is used later in the file for some testing routines I wrote but you're right, it is not needed for the tree. Also the tree class will eventually be in a header so I will remove the using statements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T19:17:56.580",
"Id": "415525",
"Score": "0",
"body": "Additionally it seems in Visual Studio I don't need `#include <utility>` or `using std::move` in order to call `move`... The code compiles and runs fine... that's a little scary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T20:31:19.387",
"Id": "415532",
"Score": "0",
"body": "Worthwhile reading on SO: [Way to go from recursion to iteration](https://stackoverflow.com/questions/159590)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-11T17:39:34.990",
"Id": "416176",
"Score": "0",
"body": "I looked into replacing the recursion with iteration, but for binary trees the code starts to get pretty messy (you need to manage a lot of pointers to pointers). For the sake of readability I feel recursion is the better approach in this case. I don't foresee myself using it in a situation with huge datasets that could cause stack overflows."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T19:00:16.833",
"Id": "214864",
"ParentId": "214850",
"Score": "9"
}
},
{
"body": "<p>Here are some ideas to help you improve your program.</p>\n<h2>Fix the bug</h2>\n<p>If we create a <code>Tree<std::string> t</code> and then insert "epsilon", "gamma", "beta", "delta", "alpha", "mu", and "kappa" in that order, we have a tree like this:</p>\n<p><a href=\"https://i.stack.imgur.com/Fddqh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Fddqh.png\" alt=\"tree before deletion\" /></a></p>\n<p>If we then call <code>t.Delete("beta");</code> we invoke undefined behavior and mess up the tree by effectively deleting two nodes (both "beta" and "delta" are now gone):</p>\n<p><a href=\"https://i.stack.imgur.com/KFMPX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KFMPX.png\" alt=\"tree after deletion\" /></a></p>\n<h2>Use raw pointers</h2>\n<p>The usual advice is to replace raw pointers with smart pointers, but in this particular case, I would advise going the other way for a number of reasons. First, the <code>std::unique_ptr</code> is not part of the public interface of the tree, so changing it to a raw pointer would not affect users of the tree at all. Second, the smart pointer is only getting in the way here, since it would be much simpler to write this code with plain pointers. Third, a plain pointer version would better allow you to have a single private concrete implementation class using a <code>void *</code> for the data. The template would then only have a very light wrapper to convert to and from <code>void *</code> to type <code>T</code>. This makes it certain that if you have multiple kinds of trees, there will only be one code instance that actually implements the tree manipulations and each templated version will only have a small bit of code overhead per type.</p>\n<h2>Avoid polluting the global namespace with <code>using</code></h2>\n<p>The <code>using std::make_unique</code> and <code>using std::unique_ptr</code> in this code are at file scope. If this is intended to be an include file, then that effectively brings those to into the global scope which could cause name collisions. Instead, you could simply remove those and simply add <code>std::</code> where appropriate or omit them entirely if you follow the previous suggestion.</p>\n<h2>Don't define a constructor that only initializes data</h2>\n<p>The only thing your <code>Tree</code> constructor does is to initialize <code>root_</code> to a fixed value. It's generally better to instead use member initializers instead. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-default\" rel=\"nofollow noreferrer\">Cpp Guidelines C.45</a>. I'd also simplify the <code>Node</code> constructor by using member initializers for <code>left</code> and <code>right</code>.</p>\n<h2>Provide a usable interface</h2>\n<p>The way it's currently defined, it's not possible to do anything at all with nodes once they are stored in the <code>Tree</code> except to determine whether they're stored in the tree. That's unlikely to be a useful interface in the real world.</p>\n<h2>Use only necessary <code>#include</code>s</h2>\n<p>The <code>#include <iostream></code> line is not necessary and can be safely removed.</p>\n<h2>Consider using more idiomatic C++</h2>\n<p>While your use of <code>not</code> is not technically wrong, you should be aware that many experienced C++ programmers will be unfamiliar with <a href=\"https://en.cppreference.com/w/cpp/language/operator_alternative\" rel=\"nofollow noreferrer\">alternative operators</a>, and so if others read your code, it might be an impediment to their understanding of it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T14:59:17.540",
"Id": "415799",
"Score": "0",
"body": "Could you expand on the idea of using `void *` in the implementation and then only having a template wrapper? From what I understand templates should always be preferred over using `void *` but maybe I have missed the point. Is `void *` fine to use as long as it doesn't appear in the public interface?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T15:27:01.900",
"Id": "415810",
"Score": "0",
"body": "I've fixed the bug. Thanks for pointing it out :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T15:55:09.037",
"Id": "415813",
"Score": "0",
"body": "The use of `void *` as the data type is just one way to have a concrete implementation which lies beneath (and is hidden under) a templated class. Imagine creating the `Tree` with a concrete type such as `int`. It's usually easier to make sure everything works. Then once it works, change to `void *` and you can store pointers to anything instead. There is very little reason to use `void *` in modern C++, but IMHO, using them *within* a class is fine. Most implementations of `operator new` use it just that way, for example."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T14:37:24.923",
"Id": "214928",
"ParentId": "214850",
"Score": "6"
}
},
{
"body": "<pre><code>unique_ptr<Node>& right = node->right;\nnode = move(node->left); // it will destroy the previous node and right nodes\nif (right) // right will be nullptr as the right nodes would have been destructed in the previous line\n{...}\n</code></pre>\n\n<p>In your Delete() function, this logic seems to be flawed. When you move your node->left into node, then all the existing right nodes will be destroyed because you just created a reference of unique_ptr which doesn't stop the following move operation from deleting these nodes.</p>\n\n<pre><code>if (right) {...}\n</code></pre>\n\n<p>So, in effect the above condition will never be true and also, you will lose the right nodes. </p>\n\n<p>The correct way to do this will be to move the right nodes into a local variable something like this : </p>\n\n<pre><code>auto right = std::move(node->right);\nnode = move(node->left);\nif (right) // Now, right will contain all the right nodes\n{...}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-27T05:26:34.590",
"Id": "242988",
"ParentId": "214850",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214864",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T15:55:42.183",
"Id": "214850",
"Score": "6",
"Tags": [
"c++",
"c++11",
"tree",
"pointers"
],
"Title": "Implementing a binary tree in C++ using \"std::unique_ptr\""
} | 214850 |
<p>I'm creating an online calculator to get the average grade of different tests my students take. I wonder if you see any problems in the following code or any way to improve it:</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.getElementById('calculator').addEventListener('click', function() {
var physicsTests = document.getElementById('physics').getElementsByTagName('input'),
historyTests = document.getElementById('history').getElementsByTagName('input'),
physicsTestsCount = 0,
historyTestsCount = 0,
physicsAverage = document.getElementById('physicsAverage'),
historyAverage = document.getElementById('historyAverage'),
i;
for (i = 0; i < physicsTests.length; i++) {
if (physicsTests[i].value) {
physicsTestsCount++;
}
if (!physicsTestsCount) {
physicsAverage.value = 'No assessment made!';
} else {
physicsAverage.value = (Number(physicsTests[0].value) + Number(physicsTests[1].value) + Number(physicsTests[2].value)) / physicsTestsCount;
}
}
for (i = 0; i < historyTests.length; i++) {
if (historyTests[i].value) {
historyTestsCount++;
}
if (!historyTestsCount) {
historyAverage.value = 'No assessment made!';
} else {
historyAverage.value = (Number(historyTests[0].value) + Number(historyTests[1].value) + Number(historyTests[2].value)) / historyTestsCount;
}
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<p id="physics">
Physics:
<input type="number">
<input type="number">
<input type="number">
<output id="physicsAverage"></output>
</p>
<p id="history">
History:
<input type="number">
<input type="number">
<input type="number">
<output id="historyAverage"></output>
</p>
<button type="button" id="calculator">Calculate</button>
</form></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T06:46:12.407",
"Id": "415563",
"Score": "0",
"body": "Please see *[What to do when someone answers](/help/someone-answers)*. I have rolled back Rev 3 → 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T18:05:52.003",
"Id": "415921",
"Score": "0",
"body": "Here's the [follow-up question](https://codereview.stackexchange.com/q/215107/33793)."
}
] | [
{
"body": "<p><code>type=number</code> inputs can be error-prone because it's easy to mistakenly adjust a value with the mouse wheel. Unless you specifically intend to enter grades with a mouse wheel, or have some other use for that interface, go with regular text fields.</p>\n\n<p>You're testing the truth of <code>element.value</code> as a string and then adding it as a number. It's good practice to be explicit about these kinds of conversions. </p>\n\n<p>It would be nice to generalize the code to handle any subject, without the use of hard-coding or copy-and-paste. </p>\n\n<p>We only need the subject name to put a label next to the inputs; the code doesn't need to know it at all. The code snippet below uses the <code>name=...</code> attribute to label the inputs (via CSS) and <code>class=subject</code> to denote an average-eligible set of inputs. The number of inputs is determined solely by the HTML.</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.getElementById('calculator').addEventListener('click', function() {\n Array.from( document.getElementsByClassName('subject') ).forEach(subject => {\n const scores=Array.from( subject.getElementsByTagName('input') ).map( e => \"\"+e.value.trim() ).filter( s => s.length ).map( n => parseFloat(n) ),\n output=subject.getElementsByTagName('output'),\n sum=scores.length ? scores.reduce((partial_sum, a) => partial_sum + a) : 0,\n average=scores.length ? ( sum / scores.length ).toFixed(2) : \"No assessment made!\"\n if (output.length) output[0].textContent = average;\n })\n});\n </code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.subject::before { text-transform: capitalize; content: attr(name) \": \" }\n.subject > input { width:3em }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form>\n <p class=subject name=physics> <input> <input> <input> <output/> </p>\n <p class=subject name=history> <input> <input> <input> <output/> </p>\n <p class=subject name=chemistry> <input> <input> <input> <input> <output/> </p>\n <p class=subject name=algebra> <input> <output/> </p>\n <button type=button id=calculator>Calculate</button>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T06:01:08.273",
"Id": "415556",
"Score": "0",
"body": "\"By testing the truth of element.value directly, you'll discard any zero scores.\" As you see in my demo, you can also enter 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:27:30.240",
"Id": "415577",
"Score": "0",
"body": "@Mori yes, that actually works. The answer is incorrect but mainly because the value is a *string* at this point. The string `\"0\"` (zero) is not considered falsey, the *number* zero is. So if you decide to refactor the code and change that test to (effectively) be `if (Number(physicsTests[i].value)` you will have a bug and it might not be immediately obvious why. You might end up getting this over two or three refactors that are each logical and concise, so the final one introduces a bug without meaning to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:39:02.833",
"Id": "415579",
"Score": "0",
"body": "@Mori you're right; the bug I named is not there. The principle I'm referring to - \"be explicit about string/number conversions\" - is a good habit but the code works here even if you don't follow it. I edited my answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:32:22.070",
"Id": "214856",
"ParentId": "214853",
"Score": "3"
}
},
{
"body": "<h2>Not a bug, but incorrect</h2>\n<ul>\n<li>You have the average calculations inside the for loop. That means you calculate the average 3 time, 2 times too many.</li>\n</ul>\n<h2>Improvements</h2>\n<ul>\n<li><p>Use <code>querySelectorAll</code> and a <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors\" rel=\"nofollow noreferrer\">CSS selector</a> string, Its flexible and you avoid the long winded combination of queries.</p>\n</li>\n<li><p>You can avoid the extra id for the outputs using the query <code>"#subject > output"</code></p>\n</li>\n<li><p>Use <code>for of</code> to iterate the query, saves you having to index into the array.</p>\n</li>\n<li><p>Round the results <code>Math.round</code> or use <code>toFixed</code> to set the number of decimal points . Floating point numbers can add tiny amounts that make numbers look bad.</p>\n</li>\n<li><p>Rather than hard code the <code>calculations</code> a function can be created that takes the subject name and then does the summing and average.</p>\n</li>\n<li><p>Good UI design means preventing bad input using constraints. The input type number lets you set the min and max constraints values</p>\n<p>As the other answer suggested that the number input type be avoided due to accidental scrolling. Do not buy into that argument. Input type number is the correct type to use, and note that the wheel only has effect when the input is focused.</p>\n</li>\n</ul>\n<p><sup><strong>Note</strong> this answer assumes you are targeting ES6+ and HTML5 compliant browsers</sup></p>\n<h2>Example</h2>\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 subjects = [\"physics\", \"history\"];\ndocument.querySelector(\"button\")\n .addEventListener(\"click\",() => subjects.forEach(calcResults));\n\nfunction calcResults(subject) {\n const tests = document.querySelectorAll(`#${subject} > input`);\n const ave = document.querySelector(`#${subject} > output`);\n var sum = 0, count = 0;\n for (const {value} of tests) {\n if (value !== \"\") { \n sum += Number(value);\n count += 1;\n }\n }\n ave.value = count === 0 ? \"No assessment.\" : (sum / count).toFixed(2);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form>\n<p id=\"physics\">\n Physics:\n <input type=\"number\" min=\"0\" max=\"100\"/>\n <input type=\"number\" min=\"0\" max=\"100\"/>\n <input type=\"number\" min=\"0\" max=\"100\"/>\n <output/>\n</p>\n<p id=\"history\">\n History:\n <input type=\"number\" min=\"0\" max=\"100\"/>\n <input type=\"number\" min=\"0\" max=\"100\"/>\n <input type=\"number\" min=\"0\" max=\"100\"/>\n <output/>\n</p>\n<button type=\"button\">Calculate</button>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Extras</h2>\n<p>I am guessing that the two subjects are but an example and that there may be more. JavaScript makes it easy to extend repeated content.</p>\n<p>The following example creates the UI from a simple <code>settings</code> object. To reduce the amount of typing 3 helper functions provide a shorthand for common DOM calls, <code>tag</code> creates tag and sets its properties, <code>query</code> does <code>querySelectAll</code> on <code>document</code>, and <code>append</code>, append siblings to parent element</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>settings = {\n subjects : [\"Physics\", \"History\", \"English\", \"Biology\"],\n numberOfGrades : 3,\n numberInput : {type: \"number\", min: \"0\", max: \"100\"},\n}\nconst tag = (name, prop = {}) => Object.assign(document.createElement(name), prop);\nconst query = query => document.querySelectorAll(query);\nconst append = (parent, ...sibs) => {\n for (const sib of sibs) { parent.appendChild(sib) }\n return parent; \n}\n\naddEventListener(\"load\", () => {\n const form = query(\"form\")[0];\n settings.subjects.forEach(subject => {\n var count = settings.numberOfGrades;\n const inputs = [];\n while (count--) { inputs.push(tag(\"Input\", settings.numberInput)) }\n append(\n form,\n append(\n tag(\"p\", {textContent: subject + \": \", id: subject}),\n ...inputs,\n tag(\"output\"),\n )\n );\n });\n const button = tag(\"button\", {textContent: \"Calculate\", type: \"button\"});\n append(form, button);\n button.addEventListener(\"click\", () => settings.subjects.forEach(calcResults)); \n});\n\n\nfunction calcResults(subject) {\n const tests = query(`#${subject} > input`);\n const ave = query(`#${subject} > output`)[0];\n var sum = 0, count = 0;\n for (const {value} of tests) {\n if (value !== \"\") { \n sum += Number(value);\n count += 1;\n }\n }\n ave.value = count === 0 ? \"No assessment.\" : (sum / count).toFixed(2);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input { margin: 4px; }\np { margin: 0px; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form></form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T23:45:54.233",
"Id": "415546",
"Score": "0",
"body": "\"the wheel only has effect when the input is focused\" - it varies and can be much worse. In Firefox, the wheel adjusts only when the input is focused AND the pointer is over the input. PLUS, if pointer landed on the focused input as a result of a scroll, it changes the value AND scrolls the page! Insane, but there you have it. So you enter a value with pointer somewhere else, operate wheel to scroll page and wheel appears to work normally...until you scroll past the (still-focused) field and silently change someone's grades. The concept of a number input is fine; the reality is not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T07:09:04.857",
"Id": "415565",
"Score": "0",
"body": "@Blindman67: \"You have the average calculations inside the for loop. That means you calculate the average 3 time, 2 times too many.\" Good point! Just updated my code in [this demo](https://jsfiddle.net/Mori/p2m0tvfy/7/). \"this answer assumes you are targeting ES6+ and HTML5 compliant browsers\" Would you mind converting it to an older version?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:29:40.990",
"Id": "415599",
"Score": "0",
"body": "See also the new [post](https://codereview.stackexchange.com/a/214912/33793)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:43:07.463",
"Id": "415613",
"Score": "0",
"body": "@Mort Sorry i don't do legacy. if you need to support abandoned browsers there are various turn key solutions when you are ready to go wild. Do not fixate on legacy as it prevents you developing the skills you will need for tomorrow... IMHO"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T09:04:47.033",
"Id": "418131",
"Score": "0",
"body": "I'm afraid your demos don't calculate the averages correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T11:10:06.980",
"Id": "418138",
"Score": "0",
"body": "@Mori I use the same method as your code shows, divide the sum of assessed valued by the count . It gets the same results as your code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:47:02.327",
"Id": "418147",
"Score": "0",
"body": "@Blindman67: Just for instance try the following values: 2, 3, 3. The average is 2.66, but your demos show 3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:55:48.800",
"Id": "418149",
"Score": "1",
"body": "@Mori As pointed out in the answer I round the result to prevent results like 5,2,3 giving 3.3333333333333335 (yes JS gets it wrong). You can set the number of decimal places you want on the last line `(sum / count).toFixed(2)` the `toFixed` takes that number of decimal places as argument and rounds to the nearest returning a string representation of the number"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T13:01:38.343",
"Id": "418151",
"Score": "0",
"body": "@Mori I have updated the answer to show 2 decimal places. BTW I thought the correct answer for 2,3,3 is 2.67 not 2.66? If you require the value to round down always you can use a different method of rounding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T13:14:34.283",
"Id": "418153",
"Score": "0",
"body": "Yes, you're right! In your first demo, can we get the paragraph IDs and make an array programmatically without having to adding them manually?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T15:19:58.587",
"Id": "418160",
"Score": "0",
"body": "@Mori yes you can. In the second snippet in my answer creates the form from the content of the object `settings`. To create from the pages content would just need some mods to that code. However DO NOT use the `id` to define the subject name. Use the data attribute eg `<p data-subject-name = \"physics\">` the `ID` is a unique identifier, giving it semantic meaning is in conflict with its role."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T22:57:49.867",
"Id": "214873",
"ParentId": "214853",
"Score": "2"
}
},
{
"body": "<h1>Optimisations</h1>\n\n<p>Based on your snippet, I assume you are writing in ES5 and not ES6. So I'm gonna use ES5 syntax below.</p>\n\n<p>See code below, explanations are in comments. My focus in more in the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> and <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">SoC</a> principles:</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>/*\n1. Use objects to store elements so that:\n - they can be easily accessed and looped\n - we can easily add more subjects to calculate without writing more codes\n - we don't have to keep revisiting the DOM on every calculation\n2. Use `.querySelectorAll` for:\n - shorter code\n - easily understood because of CSS syntax and better readability\n*/\nvar inputs = {\n physics: document.querySelectorAll('#physics input'),\n history: document.querySelectorAll('#history input')\n};\n\nvar outputs = {\n physics: document.querySelector('#physicsAverage'),\n history: document.querySelector('#historyAverage')\n};\n\nvar calculator = document.querySelector('#calculator');\n\n\n/*\n1. Wrap all calculations into one function.\n2. Here, it's called `calculate`.\n*/\ncalculator.addEventListener('click', calculate);\n\n\n/*\n1. Split operations into separate functions so that:\n - the code is DRY.\n - it follows the Separation of Concern (SoC) principle.\n*/\n\nfunction calculate(){\n var subject;\n\n // Loop over the `inputs` object for its keys\n for (subject in inputs){\n // Wrap the actual calculations into one function (SoC).\n // So that you don't have to write repeating code (DRY).\n calculateScoreOf(subject);\n }\n}\n\nfunction calculateScoreOf(subject){\n var tests = inputs[subject];\n var output = outputs[subject];\n \n // No need for `count` variable in your original code.\n // The `.length` property already has the value\n var testCount = tests.length;\n \n // Use `Array.prototype.map` instead of for-loop to get all values\n // For better readability and SoC.\n var scores = Array.prototype.map.call(tests, getInputValue);\n \n // Use NaN checking for incomplete assessment indication instead of count checking (DRY)\n var hasNaN = scores.some(isNaN);\n \n var scoreTotal,\n scoreAverage;\n\n if (hasNaN)\n output.value = 'Incomplete assessment!';\n else {\n // Use `.reduce` to sum scores instead of hard-coding the addition (DRY and SoC)\n scoreTotal = scores.reduce(sumScores, 0);\n scoreAverage = scoreTotal/testCount;\n\n // Use `.toFixed` to set decimal place.\n output.value = scoreAverage.toFixed(2);\n }\n}\n\nfunction getInputValue(input){\n // Returns NaN if invalid input\n return parseFloat(input.value);\n}\n\nfunction sumScores(a, b){\n return a + b;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form>\n <p id=\"physics\">\n Physics:\n <input type=\"number\">\n <input type=\"number\">\n <input type=\"number\">\n <output id=\"physicsAverage\"></output>\n </p>\n <p id=\"history\">\n History:\n <input type=\"number\">\n <input type=\"number\">\n <input type=\"number\">\n <output id=\"historyAverage\"></output>\n </p>\n <button type=\"button\" id=\"calculator\">Calculate</button>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h1>Links</h1>\n\n<ol>\n<li><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself (DRY)</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">Separation of Concerns (SoC)</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\"><code>for...in</code> loop</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll\" rel=\"nofollow noreferrer\"><code>.querySelectorAll</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector\" rel=\"nofollow noreferrer\"><code>.querySelector</code></a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>Array.prototype.map</code></a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\"><code>Array.prototype.some</code></a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\"><code>Array.prototype.reduce</code></a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN\" rel=\"nofollow noreferrer\"><code>isNaN</code></a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed\" rel=\"nofollow noreferrer\"><code>.toFixed</code></a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat\" rel=\"nofollow noreferrer\"><code>parseFloat</code></a></li>\n</ol>\n\n<h1>Extra: Code in ES6</h1>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const inputs = {\n physics: [...document.querySelectorAll('#physics input')],\n history: [...document.querySelectorAll('#history input')]\n};\n\nconst outputs = {\n physics: document.querySelector('#physicsAverage'),\n history: document.querySelector('#historyAverage')\n};\n\nconst calculator = document.querySelector('#calculator');\n\ncalculator.addEventListener('click', calculate);\n\nfunction calculate(){\n for (const subject in inputs)\n calculateScoreOf(subject);\n}\n\nfunction calculateScoreOf(subject){\n const tests = inputs[subject];\n const output = outputs[subject];\n const testCount = tests.length;\n \n const scores = tests.map(el => parseFloat(el.value));\n const hasNaN = scores.some(isNaN);\n\n if (hasNaN)\n output.value = 'Incomplete assessment!';\n else {\n const scoreTotal = scores.reduce((a, b) => a + b, 0);\n const scoreAverage = scoreTotal/testCount;\n output.value = scoreAverage.toFixed(2);\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form>\n <p id=\"physics\">\n Physics:\n <input type=\"number\">\n <input type=\"number\">\n <input type=\"number\">\n <output id=\"physicsAverage\"></output>\n </p>\n <p id=\"history\">\n History:\n <input type=\"number\">\n <input type=\"number\">\n <input type=\"number\">\n <output id=\"historyAverage\"></output>\n </p>\n <button type=\"button\" id=\"calculator\">Calculate</button>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:51:54.613",
"Id": "415585",
"Score": "0",
"body": "\"*// Returns NaN if invalid input*\" ***NOT NECESSARILY!*** Sorry for the caps but I do have to stress that `parseFloat(\"5Banana\")` will result in `5` even when I'd consider that invalid input. Using `Number` (or a unary `+` - they are equivalent) to do an explicit number conversion will *correctly* give you `NaN` for inputs that cannot at all be converted to a JS numeric. Although `\"5,50\"` (a valid decimal separator for a different culture) would return `NaN`. While a `parseFloat` will give you `5`, so it's still off."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:54:58.677",
"Id": "415588",
"Score": "0",
"body": "\"// The `.length` property already has the value\" but now the code behaves differently - inputting `3` in the first field and leaving the other two empty would have calculated the average for a single value (so, the same value) while with this implementation you HAVE to fill in all fields."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T02:26:35.553",
"Id": "214884",
"ParentId": "214853",
"Score": "1"
}
},
{
"body": "<h2>Main updates</h2>\n\n<ul>\n<li>Calculated the total values of each row through the <code>loop</code>.</li>\n<li>Put the average calculation outside the loop.<br>\nCredit: Thanks to <a href=\"https://codereview.stackexchange.com/a/214873/33793\">Blindman67</a> for this pointer!</li>\n</ul>\n\n<h2>Final code</h2>\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.getElementById('calculator').addEventListener('click', function() {\n var physicsTests = document.getElementById('physics').getElementsByTagName('input'),\n historyTests = document.getElementById('history').getElementsByTagName('input'),\n physicsTestsTotal = 0,\n historyTestsTotal = 0,\n physicsTestsCount = 0,\n historyTestsCount = 0,\n physicsAverage = document.getElementById('physicsAverage'),\n historyAverage = document.getElementById('historyAverage'),\n warning = 'Please enter a grade.',\n i;\n for (i = 0; i < physicsTests.length; i++) {\n if (physicsTests[i].value) {\n physicsTestsTotal += Number(physicsTests[i].value);\n physicsTestsCount++;\n }\n }\n if (physicsTestsCount) {\n physicsAverage.value = physicsTestsTotal / physicsTestsCount;\n } else {\n physicsAverage.value = warning;\n }\n for (i = 0; i < historyTests.length; i++) {\n if (historyTests[i].value) {\n historyTestsTotal += Number(historyTests[i].value);\n historyTestsCount++;\n }\n }\n if (historyTestsCount) {\n historyAverage.value = historyTestsTotal / historyTestsCount;\n } else {\n historyAverage.value = warning;\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>[type=\"number\"] {\n width: 5em;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form>\n <p id=\"physics\">\n Physics:\n <input type=\"number\">\n <input type=\"number\">\n <input type=\"number\">\n <output id=\"physicsAverage\"></output>\n </p>\n <p id=\"history\">\n History:\n <input type=\"number\">\n <input type=\"number\">\n <input type=\"number\">\n <output id=\"historyAverage\"></output>\n </p>\n <input type=\"button\" value=\"Calculate\" id=\"calculator\">\n</form></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-07T12:24:51.753",
"Id": "214912",
"ParentId": "214853",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "214873",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T16:20:17.247",
"Id": "214853",
"Score": "3",
"Tags": [
"javascript",
"html",
"form"
],
"Title": "Calculate inputs average"
} | 214853 |
<p>I want to split a song into multiple parts, given the song duration and number of parts.</p>
<p>My code achieves that, but it feels a little "stupid" and I would like to learn a more sophisticated - and shorter - way. Particularly, I feel that the marker variable is a little overkill. I would welcome any suggestions. </p>
<pre><code>song_duration = 20 # these two
num_of_parts = 4 # are given
part_duration = song_duration / num_of_parts
parts = []
marker = 0
for _ in range(num_of_parts):
part = [marker, marker + part_duration]
marker += part_duration
parts.append(part)
print(parts)
# parts is : [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:52:11.377",
"Id": "415513",
"Score": "1",
"body": "Welcome to CodeReview ! From the output sample you've provided, it looks like you are using Python 3 (which is great). Can you confirm ? (The behavior for division is different which leads to different behaviors in your case)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:57:28.633",
"Id": "415514",
"Score": "1",
"body": "Thanks for the warm welcome:). Yes, I am using Python 3."
}
] | [
{
"body": "<p>Firstly you should be able to see that the left value in each part is the same as the right value in the previous part. This can be implemented by using the <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools-recipes\" rel=\"noreferrer\"><code>pairwise</code></a> recipe:</p>\n\n<pre><code>def pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n</code></pre>\n\n<p>From this you should be able to generate all the wanted numbers using a list, or generator, comprehension:</p>\n\n<pre><code>part_duration = song_duration / num_of_parts\nparts = [i * part_duration for i in range(num_of_parts + 1)]\n</code></pre>\n\n<hr>\n\n<pre><code>import itertools\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\ndef song_segments(duration, segments):\n delta = duration / segments\n return pairwise([i * delta for i in range(segments + 1)])\n\n\nprint(list(song_segments(20, 4)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:58:03.593",
"Id": "214859",
"ParentId": "214857",
"Score": "6"
}
},
{
"body": "<p>A few things:</p>\n\n<p>First, you can make use of the third parameter of <code>range</code>, which is the step, <em>IF</em> you can guarantee that <code>part_duration</code> is an integer (which is the case for the example you posted here):</p>\n\n<pre><code># Integer division\npart_duration = song_duration // num_of_parts\nparts = []\n\n# I rearranged this a bit too\nfor i in range(0, song_duration, part_duration):\n part = [i, i + part_duration]\n parts.append(part)\n\nprint(parts)\n# [[0, 5], [5, 10], [10, 15], [15, 20]] # Note they're integers\n</code></pre>\n\n<p>Note how this is just a transformation from a <code>range</code> to a <code>list</code> though. If you're transforming one collection to a list, list comprehensions should come to mind:</p>\n\n<pre><code># List comprehension split over two lines\nparts = [[i, i + part_duration]\n for i in range(0, song_duration, part_duration)]\n\nprint(parts)\n# [[0, 5], [5, 10], [10, 15], [15, 20]]\n</code></pre>\n\n<hr>\n\n<p>If you can't guarantee integer steps though, I'm not sure of a good way. Unfortunately, Python doesn't allow fractional steps for its <code>range</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:58:26.657",
"Id": "214860",
"ParentId": "214857",
"Score": "6"
}
},
{
"body": "<p>Here are a few suggestions.</p>\n\n<p><strong>Write a function</strong></p>\n\n<p>Your code could be moved into a function on its own. It has the benefit of giving the code a clear name, a clear input, a clear output and we could go further and add documentation and tests.</p>\n\n<pre><code>def split_song(song_duration, num_of_parts):\n \"\"\"Returns parts when a song of duration song_duration is split into num_of_parts parts.\"\"\"\n part_duration = song_duration / num_of_parts\n parts = []\n marker = 0\n\n for _ in range(num_of_parts):\n part = [marker, marker + part_duration]\n marker += part_duration\n parts.append(part)\n return parts\n\nassert split_song(20, 4) == [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]\nassert split_song(21, 4) == [[0, 5.25], [5.25, 10.5], [10.5, 15.75], [15.75, 21.0]]\n</code></pre>\n\n<p><strong>Proper data structure</strong></p>\n\n<p>You are returning a list of list. In Python, there is a <a href=\"https://nedbatchelder.com/blog/201608/lists_vs_tuples.html\" rel=\"noreferrer\">cultural difference in how <code>tuple</code> and <code>list</code> are used</a>.</p>\n\n<p>In our case, we know that each piece will contain 2 pieces of information: the begining and the end. It would be more relevant to use tuples here.</p>\n\n<pre><code>part = (marker, marker + part_duration)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T18:02:03.217",
"Id": "214861",
"ParentId": "214857",
"Score": "7"
}
},
{
"body": "<p>In general, building a list using a loop of the form</p>\n\n<blockquote>\n<pre><code>some_list = []\nfor …:\n some_list.append(…)\n</code></pre>\n</blockquote>\n\n<p>… would be better written using a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"noreferrer\">list comprehension</a>.</p>\n\n<p>Each interval always has two elements: a start time and an end time. These two-element lists would be better represented as <a href=\"https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences\" rel=\"noreferrer\">tuples</a> instead of lists. (Tuples have a connotation that they have a fixed length, whereas lists can grow to arbitrary lengths.)</p>\n\n<p>Finally, I'd package the code into a function.</p>\n\n<pre><code>def intervals(parts, duration):\n part_duration = duration / parts\n return [(i * part_duration, (i + 1) * part_duration) for i in range(parts)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T18:43:39.327",
"Id": "214863",
"ParentId": "214857",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "214863",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:45:46.780",
"Id": "214857",
"Score": "12",
"Tags": [
"python",
"python-3.x"
],
"Title": "Split a number into equal parts given the number of parts"
} | 214857 |
<p>I'm using a database that has a library for access to it. Connection is done synchronously, it's blocking and I do not have a way to abort it. To connect, I have to write:</p>
<pre><code>var _loader = new DatabaseDriverLoader();
DatabaseDriver _driver = _loader.Connect(connectionString, login, password);
</code></pre>
<p>I wanted to improve it:</p>
<ul>
<li>Be able to connect asynchronously (not waiting for actual connection)</li>
<li>Be able to cancel the connection if I need to</li>
</ul>
<p>Here's a wrapper that I created:</p>
<pre><code>public class DatabaseConnection : IDisposable
{
private DatabaseDriver _driver;
private DatabaseDriverLoader _loader
public event EventHandler ConnectionFailed;
public event EventHandler ConnectionEstablished;
public event EventHandler ConnectionLost;
public async Task ConnectAsync(string connectionString, string login, string password, CancellationToken cancellationToken)
{
var connectionTask = Task.Run(() =>
{
try
{
var _loader = new DatabaseDriverLoader();
DatabaseDriver _driver = _loader.Connect(connectionString, login, password);
}
catch (Exception e) { }
});
await Task.Run(async () =>
{
while(!connectionTask.IsCompleted && !cancellationToken.IsCancellationRequested)
{
await Task.Delay(100);
}
});
cancellationToken.ThrowIfCancellationRequested();
if (_driver == null)
{
ConnectionFailed?.Invoke(this, EventArgs.Empty);
return;
}
ConnectionEstablished?.Invoke(this, EventArgs.Empty);
_driver.ConnectionToServerLost += OnConnectionLost;
}
public void Dispose()
{
if (_driver != null)
{
_driver.ConnectionToServerLost -= OnConnectionLost;
_driver.Dispose();
}
_loader?.Dispose();
}
public DatabaseDriver GetDriver()
{
return _driver;
}
private void OnConnectionLost(object sender, EventArgs e) => ConnectionLost?.Invoke(sender, e);
}
</code></pre>
<p>Here's how I would use that class:</p>
<pre><code>private async Task ConnectWithDatabase()
{
//Delete old connection instance
_dbConnectionTokenSource?.Cancel();
if (_dbConnection != null)
{
_dbConnection.ConnectionEstablished -= OnDbConnectionEstablished;
_dbConnection.ConnectionLost -= OnDbConnectionLost;
_dbConnection.ConnectionFailed -= OnDbConnectionFailed;
_dbConnection.Dispose();
}
//Create new connection instance
_dbConnection = new DatabaseConnection();
_dbConnection.ConnectionEstablished += OnDbConnectionEstablished;
_dbConnection.ConnectionLost += OnDbConnectionLost;
_dbConnection.ConnectionFailed += OnDbConnectionFailed;
_dbConnectionTokenSource = new CancellationTokenSource();
var token = _dbConnectionTokenSource.Token;
try
{
await _dbConnection.ConnectAsync(
ConnectionString,
Login,
Password,
token)
.ConfigureAwait(false);
}
catch (TaskCanceledException e)
{ }
}
</code></pre>
<p>I wanted to ask you kindly for review of this code, because I'm not really sure if this is done correctly.
I don't know if it is a good idea to use an event for successful connection. Maybe Connect method should return successful Task when connection occurs?</p>
<p>I'm not sure if cancellation is done correctly. In my use case there might be situations where DatabaseConection is canceled and disposed before connection occurs successfully.</p>
<p>I am not sure if it's a good idea to create new threads in DatabaseConnection, because clients of this class might not want it? - at least I read somewhere that it's not a good design, but I'm not sure why.</p>
<p>I will be happy to hear any opinion, always good to learn something new.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T07:30:54.997",
"Id": "415570",
"Score": "0",
"body": "@HenrikHansen Ofcourse, you are right. Mistakes came over, because I modified code a bit before posting here to remove unnecessary parts. I fixed it now. Async behaviour is needed, because I do not want thread to be blocked when I start connecting to database."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T07:37:51.057",
"Id": "415571",
"Score": "1",
"body": "_because I modified code a bit before posting here to remove unnecessary parts_ - there are no unnecessary parts on Code Review. Please post your actual code without modifying it. Otherwise you might not get the feedback you are hoping for and both reviewers and you will be unhappy about having wasted their time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T10:20:52.320",
"Id": "415589",
"Score": "0",
"body": "@t3chb0t Modifications were about names and very small refactoring. After fixing, my code is same as I posted here."
}
] | [
{
"body": "<p>I would first start by saying that such a class is <a href=\"https://devblogs.microsoft.com/pfxteam/should-i-expose-asynchronous-wrappers-for-synchronous-methods/\" rel=\"nofollow noreferrer\">generally regarded as a bad practice</a> because it doesn't achieve what's supposed to do, or simply there are better ways of doing it.</p>\n\n<p>But let's go to the actual code, in the <code>ConnectAsync</code> method.</p>\n\n<blockquote>\n<pre><code>var connectionTask = Task.Run(() =>\n{\n try\n {\n var _loader = new DatabaseDriverLoader();\n DatabaseDriver _driver = _loader.Connect(connectionString, login, password);\n }\n catch (Exception e) { }\n});\n</code></pre>\n</blockquote>\n\n<p>Here you delegate the connection to the main class and initialize the <code>_driver</code> field. The first problem is that, since it's wrapped in a <code>Task</code>, it uses a separate thread and that new thread is the blocked one instead of the calling one. In a desktop program, it can be a good thing (since it keeps the UI thread free to handle the UI), but in a web site you free the original thread and stall another one, which is what you want to avoid with an async method.</p>\n\n<p>Even worse, the empty <code>catch</code> block will swallow any exceptions, so you won't get any clue why a connection fails if that happens.</p>\n\n<p>The next part also has its problems:</p>\n\n<blockquote>\n<pre><code>await Task.Run(async () =>\n{\n while(!connectionTask.IsCompleted && !cancellationToken.IsCancellationRequested)\n {\n await Task.Delay(100);\n }\n});\n</code></pre>\n</blockquote>\n\n<p>This employs a second thread and loops until the first one finishes or the cancellation is requested. While it sounds neat in principle, it actually ends up using double the resources it should for the ability to \"cancel\" the connection (more on that latter), which is far suboptimal. Callers expect NO threads consumed when you see an async DB connection, but instead this code stalls 2 of them.</p>\n\n<h2>What to do instead?</h2>\n\n<p>In short, leave the decision to the caller! This class introduced some side effects that callers normally don't expect. In web pages, it consumes far more resources than necesary, and in desktop programs it can be simply invoked via <code>Task.Run</code> method directly, instead of wrapping in a class, if keeping the UI responsive is desired. This removes the need for this class, using the provided driver directly.</p>\n\n<h2>About your other points</h2>\n\n<blockquote>\n <p>Be able to connect asynchronously (not waiting for actual connection)</p>\n</blockquote>\n\n<p>It clearly does that, but I would simply use the first chunk of code (awaiting for it) directly, and remove the need for this, because of unwanted side effects.</p>\n\n<blockquote>\n <p>Be able to cancel the connection if I need to</p>\n</blockquote>\n\n<p>Here is the bigger catch. It does <strong>NOT</strong> cancel the connection at all! When the cancellation token is triggered, the loop is interrupted, but the first thread is left running, and its result is ignored. This means that if the connection succeeds, you have a floating connection that won't be disposed of properly, and the involved resources will still be consumed. The only practical effect of cancellation is the early return.</p>\n\n<blockquote>\n <p>Maybe Connect method should return successful Task when connection occurs?</p>\n</blockquote>\n\n<p>Yes, that's a good practice. I don't see a particular use for an event here (not that it's a bad thing to have one, but it serves little purpose). Most important, in its current form, the code <em>does</em> return a task and completes it on sucessful connection, and that's what you use in your \"demo\" code in fact. That's a good thing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-16T02:40:27.420",
"Id": "232477",
"ParentId": "214858",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T17:53:56.660",
"Id": "214858",
"Score": "1",
"Tags": [
"c#",
"database",
"asynchronous",
"task-parallel-library"
],
"Title": "Asynchronous wrapper for database connection"
} | 214858 |
<p>Let's say I have a Binary Tree that looks like</p>
<pre><code> +
2 *
5 8
</code></pre>
<p>I've written a function to traverse inorder to solve it as 2+5*8</p>
<p>Is there a better way? Using <code>eval</code> seems a bit hacky and perhaps I can just have a function calculate the total sum on either side and then do a left + right instead.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
solveEquation() {
let equation = "";
let traverse = (currentNode = this.root) => {
if (currentNode !== null) {
if (currentNode.left !== null) traverse(currentNode.left);
equation += currentNode.value;
if (currentNode.right !== null) traverse(currentNode.right);
}
}
traverse();
return eval(equation);
}
init() {
this.root = new Node('+');
let currentNode = this.root;
currentNode.left = new Node(2);
currentNode.right = new Node('*');
currentNode = currentNode.right;
currentNode.left = new Node(5);
currentNode.right = new Node(8);
}
}
let bst = new BinarySearchTree();
bst.init();
console.log(bst.solveEquation());</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T20:29:55.073",
"Id": "415531",
"Score": "0",
"body": "The input is a binary tree, but in what sense is it a [binary _search_ tree](https://en.wikipedia.org/wiki/Binary_search_tree)?"
}
] | [
{
"body": "<p>This is not a search tree. You can call it an abstract syntax tree, or just a binary tree. </p>\n\n<p>You can use a dispatch table to evaluate ops.</p>\n\n<pre><code> dispatch = {\n '+': (a,b) => a+b,\n '*': (a,b) => a*b\n }\n ...\n if (node.left && node.right && node.value in dispatch) dispatch[node.value]( traverse(node.left), traverse(node.right) );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T20:39:26.240",
"Id": "214869",
"ParentId": "214867",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T19:52:55.573",
"Id": "214867",
"Score": "1",
"Tags": [
"javascript",
"tree",
"math-expression-eval"
],
"Title": "Evaluating an arithmetic expression from a binary tree"
} | 214867 |
<p>I am really new to programming, and I made this simple tkinter app in
python. Please tell me what can be improved and how to use classes
correctly in combination with tkinter.</p>
<p><a href="https://github.com/apocalyps0/lol-random-game" rel="nofollow noreferrer">Github to clone if you want</a></p>
<pre><code>#!/usr/bin/env python
# ---------------------------------
# @author: apoc
# @version: 0.1
# ---------------------------------
# importing
from tkinter import *
import csv
from random import randint
class LRG(object):
def __init__(self,master):
# variables
with open('data/champs.csv','r') as f:
reader = csv.reader(f)
self.champ_list = list(reader)
# layout
self.randombutton = Button(master,text='Random',command=self.scan)
self.infofield = Text(master,height=20,width=50)
# layout
self.randombutton.grid(row=0,column=1,sticky=E,pady=2,padx=5)
self.infofield.grid(row=1,columnspan=4,sticky=W,column=0,pady=4)
def scan(self):
self.infofield.delete('1.0',END)
self.infofield.insert(END,self.champ_list[
randint(0,len(self.champ_list))
])
if __name__ == "__main__":
master = Tk()
LRG(master)
master.title("LRG")
master.mainloop()
</code></pre>
| [] | [
{
"body": "<h1>Standards</h1>\n\n<p>Follow the PEP8 coding standard. One violation that immediately is obvious is the lack of a space following a comma. For example, <code>(row=0, column=1, sticky=E, pady=2, padx=5)</code> is much easier to read. Use <code>pylint</code> (or similar) to check your code style against the recommended standard.</p>\n\n<h1>Import grouping</h1>\n\n<p>My personal preference is to keep <code>import ...</code> statements together, and <code>from ... import ...</code> statements together, not interleave them.</p>\n\n<h1>Private class members</h1>\n\n<p>\"Private\" members should be prefixed with an underscore. Such as <code>self._champ_list</code> and <code>def _scan(self):</code>. This doesn't actually make them private, but some tools will use the leading underscore as a key to skip generating documentation, not offer the member name in autocomplete, etc.</p>\n\n<h1>Remove useless members</h1>\n\n<p><code>self.randombutton</code> is only used in the constructor; it could just be a local variable, instead of a member.</p>\n\n<h1>Use correct comments</h1>\n\n<p>The <code># layout</code> comment above the <code>Button</code> and <code>Text</code> construction is misleading; it is not doing any layout.</p>\n\n<h1>Self documenting names</h1>\n\n<p>Use understandable names. I have no idea what <code>LRG</code> is. Good variable names go a long way towards creating self-documenting code.</p>\n\n<h1>Use Doc-Strings</h1>\n\n<p>Add <code>\"\"\"doc-strings\"\"\"</code> for files, public classes, public members, and public functions. Using <code>LRG</code> as a class name could be fine (in may be a common acronym at your company), but adding a doc-string for the class could spell out what the acronym stands for at least once.</p>\n\n<h1>Avoid hard-coded information</h1>\n\n<p>You have hard-coded reading the <code>data/champs.csv</code> file into the constructor. Consider making it more flexible, such as passing in a filename with that as a default.</p>\n\n<pre><code>class LRG:\n \"\"\"Literal Random Generator\"\"\"\n\n def __init__(self, master, csv_filename=\"data/champs.csv\"):\n # ...etc...\n</code></pre>\n\n<p>Or, move the reading of the data outside of the class, and pass the <code>champ_list</code> in as a constructor argument. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T07:21:50.477",
"Id": "415566",
"Score": "0",
"body": "Thank you you very much. I will update my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T00:11:46.510",
"Id": "214877",
"ParentId": "214870",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "214877",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T20:51:44.963",
"Id": "214870",
"Score": "0",
"Tags": [
"python",
"beginner",
"tkinter"
],
"Title": "Simple tkinter application that choose a random string"
} | 214870 |
<p>I am implementing an algorithm to solve the following problem:</p>
<blockquote>
<p>Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.</p>
</blockquote>
<p>The solution of this problem using recursion is quite straightforward:</p>
<pre><code>class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def build_bst_recursive(array):
size = len(array)
return _build_bst(array, first=0, last=size - 1)
def _build_bst(array, first, last):
if last < first:
return None
mid = (first + last) // 2
node = Node(mid)
node.left = _build_bst(array, first, mid - 1)
node.right = _build_bst(array, mid + 1, last)
return node
</code></pre>
<p>Out of curiosity I also would like to solve the same problem using an iterative algorithm. Here is what I came up with:</p>
<pre><code>class Stack:
class _Node:
def __init__(self, value):
self.value = value
self.next_node = None
def __init__(self):
self.head_node = None
def is_empty(self):
return self.head_node is None
def push(self, value):
node = self._Node(value)
node.next_node = self.head_node
self.head_node = node
def pop(self):
if self.is_empty():
raise Exception("Stack is empty.")
node = self.head_node
self.head_node = node.next_node
return node.value
def build_bst_iterative(array):
size = len(array)
# Stack stores tuples of the first and the last indices of half-segments:
stack_indices = Stack()
stack_indices.push((0, size - 1))
# Stack stores tree nodes:
stack_nodes = Stack()
# Add to the stack a node that will be a root of the tree:
root_node = Node(None)
stack_nodes.push(root_node)
while not stack_indices.is_empty():
first, last = stack_indices.pop()
node = stack_nodes.pop()
if last < first:
# The segment is degenerated. Keep the node empty.
continue
elif last == first:
# Assign the value, it is the last bottom node.
node.value = array[last]
continue
mid = (first + last) // 2
node.value = array[mid]
node.left = Node(None)
node.right = Node(None)
# Update stacks:
# (right half-segment)
stack_indices.push((mid + 1, last))
stack_nodes.push(node.right)
# (left half-segment)
stack_indices.push((first, mid - 1))
stack_nodes.push(node.left)
assert stack_nodes.is_empty()
return root_node
</code></pre>
<p>I would highly appreciate if you could review the code and suggest any approaches for improvement. For example, I am trying to understand if it is possible to use only one stack.</p>
<p><strong>EDIT</strong> After looking into my code in the morning, I realise that there is no need for two stacks because I always push and pop to the two stacks at the same time. Here there is an updated version of the code:</p>
<pre><code>def build_bst_iterative_one_stack(array):
size = len(array)
# Add to the stack a node that will be a root of the tree:
root_node = Node(None)
# Stack stores tuples of the current node, and the first and the last indices of half-segments:
stack = Stack()
stack.push((root_node, 0, size - 1))
while not stack.is_empty():
node, first, last = stack.pop()
if last < first:
# The segment is degenerated. Do nothing.
continue
elif last == first:
# Assign the value, it is the last bottom node.
node.value = array[last]
continue
mid = (first + last) // 2
node.value = array[mid]
node.left = Node(None)
node.right = Node(None)
# Update the stack with the left and the right half-segment:
stack.push((node.right, mid + 1, last))
stack.push((node.left, first, mid - 1))
assert stack.is_empty()
return root_node
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T07:23:52.140",
"Id": "415568",
"Score": "0",
"body": "(The second thing striking about the iterative approach is the roll-your-own stack - what's wrong with `list.append/pop`? The sole reason I tried to understand that non-commented code was that I was curious whether you presented a bottom-up procedure.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:06:39.913",
"Id": "415576",
"Score": "0",
"body": "@greybeard thank you for your comment. You are right I could use a `list`. I also added some comments to make the iterative algorithm easier to understand. In a bottom-up procedure you would build tree from bottom? In this case I have a top-down procedure. I would highly appreciate if you could elaborate how to implement a bottom-up procedure. Also, what is also the first thing striking about the iterative approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T10:47:41.770",
"Id": "415590",
"Score": "0",
"body": "(I was about to compliment you on your post when I found part of the praise would have to go to 200_success - in my eyes, you didn't do half bad as it is.) (Note that changes to the code are not welcome once reviews started.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T11:46:57.033",
"Id": "415594",
"Score": "0",
"body": "@greybeard (ok, probably I miss something about what 200_success wrote.) (Thanks for telling me about the code changes, I didn't know about this. Just joined the community.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:58:31.330",
"Id": "415615",
"Score": "1",
"body": "(See also: [Create Balanced Binary Search Tree from Sorted linked list](https://stackoverflow.com/a/18406975))"
}
] | [
{
"body": "<p>Let me start with an all too common hindsight:<br>\nyour code lacks test support and scaffold.</p>\n\n<p>The most basic test support for a class is a succinct <code>__str__</code>, for <code>class Node</code>:</p>\n\n<pre><code>def __str__(self):\n return '<' + ('.' if not self.left else (str(self.left) + '|')) \\\n + str(self.value) + ('.' if not self.right\n else ('|' + str(self.right))) + '>'\n</code></pre>\n\n<p>(a more elaborate one would allow to limit recursion.) The result for</p>\n\n<pre><code>if __name__ == '__main__':\n ascending = [chr(x) for x in range(ord('a'), ord('g'))]\n print(build_bst_recursive(ascending))\n print(build_bst_iterative_one_stack(ascending))\n</code></pre>\n\n<blockquote>\n <p><<.0|<.1.>>|2|<<.3.>|4|<.5.>>><br>\n <<<.None.>|a|<.b.>>|c|<<.d.>|e|<.f.>>></p>\n</blockquote>\n\n<p>highlights an oversight with <code>_build_bst()</code> (not using <code>node = Node(array[mid])</code>) and a problem in the stack variants with always creating two child nodes (or with the handling commented <code># The segment is degenerated. Do nothing.</code>). </p>\n\n<hr>\n\n<p>Your code is more or less in line with the <a href=\"https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (good - do you use an IDE, your IDE's PEP8 support?); make it a habit to provide <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">documentation strings</a> for everything public, too. </p>\n\n<p>If I was serious about comparing alternative implementations, I'd try to define an <a href=\"https://docs.python.org/3/library/abc.html\" rel=\"nofollow noreferrer\">interface</a> and hope to avoid names like <code>build_bst_iterative_one_stack</code>.<br>\nI got used to the builtin <code>len()</code>, I don't see an advantage to introducing <code>size = len(array)</code> <em>where used once</em>.</p>\n\n<p><code>_build_bst()</code> is pretty basic; if it was public, it would need a <em>doc string</em> specifying <code>last</code> to be inclusive. I don't like the name <code>array</code> - would prefer <code>values</code> or <code>ordered</code> (<code>ascending</code> would be misleading, as <code>_build_bst()</code> works perfectly for descending values).</p>\n\n<p>I'd hesitate to roll my own stack class, more so if the stated purpose was something else, entirely. If I did, I'd just extend <code>list</code>:</p>\n\n<pre><code>class Stack(list):\n ''' syntactic sugar: adds push(), is_empty() to list's pop() '''\n push = list.append\n\n def is_empty(self):\n return not bool(self)\n</code></pre>\n\n<p>(Skipping <code>build_bst_iterative()</code>.)<br>\nIn <code>build_bst_iterative_one_stack()</code>, I'd prefer <code>toDo</code> over <code>stack</code>. The comment <code>stack stores […and…] indices of half-segments</code> is funny in the first tuple pushed two statements down <em>not</em> being a half.<br>\nI don't have an inspiration how to fix the introduction of <em><code>None</code>-Nodes</em> without duplicating the check.</p>\n\n<p>Your \"<code>build_bst_iterative*()</code>\" implementations are straightforward conversions of the basic recursive approach (see <a href=\"https://stackoverflow.com/a/18406975\">Create Balanced Binary Search Tree from Sorted linked list</a> for one working without \"random\" access); I would not expect insights beyond <em>doesn't get prettier for explicit stack handling</em>. </p>\n\n<p>Much to my dismay, I didn't find a decent web reference for a genuine iterative approach (numerous weird ones, some as new as <a href=\"https://arxiv.org/abs/1902.02499\" rel=\"nofollow noreferrer\">2019/3/2</a>):<br>\nFirst consider the case of 2ⁿ-1 nodes: with <em>level</em>s numbered from 0 for bottom (up to <em>n-1</em>), the level of each node is the number of trailing zeroes in its ordinal. Have an array to reference one node for each level, initialised to <code>None</code>s. For each value, create a <code>Node</code>. Check the reference at the level indicated by the number of trailing zeroes in its ordinal: if <code>None</code>, just plant the node there and make whatever is one level lower its left descendant. If not <code>None</code>, make node the right descendant of the node at the next higher level an set this level to <code>None</code>. (As an alternative to checking this reference, you can inspect the bit in the ordinal just two above the trailing zeroes.)<br>\nThere are numerous ways to handle <em>N</em> ≠ 2ⁿ-1; one being to aim for a <a href=\"https://en.m.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees\" rel=\"nofollow noreferrer\">complete binary tree</a>: compute the ordinal <em>rb</em> of the rightmost node at the bottom level. Proceed as above to <em>rb+1</em>, and increase the \"ordinal number\" by two instead of one thereafter.<br>\n(Finally, return the node at the highest level as the root of the tree built…)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:52:50.533",
"Id": "415634",
"Score": "0",
"body": "Thank you a lot for your review! (I use PyCharm and you can configure https://github.com/ambv/black to format the code on save or on shortcut) (I also didn't yet come up with a strategy how to overcome the introduction of None-Nodes...) (Special thanks for the link that you provided about how to implement the algorithm for SLL. It is really useful to see how you can do it with in-place traversal!) (Wow I am quite surprised that I came up with a question that brings us to very recent publications in the field.) Thank you again for your time, reading your review was really useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:18:23.973",
"Id": "415640",
"Score": "0",
"body": "@desa: on the [CR help page on asking questions](https://codereview.stackexchange.com/help/asking), there is one [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) - see the paragraph about *I improved my code…*. (My take on *accepting an answer* has shifted to *allow two days before accepting an answer* (the good news being that you can shift the accept to a different answer).)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T10:40:59.290",
"Id": "214907",
"ParentId": "214874",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214907",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T23:31:13.280",
"Id": "214874",
"Score": "4",
"Tags": [
"python",
"algorithm",
"tree",
"binary-search"
],
"Title": "Building balanced BST from sorted array: recursive and iterative approaches"
} | 214874 |
<h3>Problem:</h3>
<p>We have a Google Custom Search function that replaces the <code>input</code> placeholder attribute and it works okay. </p>
<p>Would you be so kind and help me with reviewing it, and if possible, provide an efficient function to replace this function with (also hoping that it would work with older version of IE and other browsers, not very necessary though): </p>
<h3>Placeholder Script:</h3>
<pre><code>// google search placeholder
(function() {
var cx = '!!!!!!!!!!!!!!!!!!!';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx='+ cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
window.onload = function(){
document.getElementById('gsc-i-id1').placeholder = 'e.g., United Stocks AMD';
};
</code></pre>
<p>where <code>cx</code> is a dynamic variable <code>string</code> parameter, defined as the custom search engine ID to use for a request (<a href="https://developers.google.com/custom-search/v1/cse/list" rel="nofollow noreferrer">Custom Search API</a>, <a href="https://stackoverflow.com/questions/6562125/getting-a-cx-id-for-custom-search-google-api-python">ID for custom search</a>).</p>
<h3>Result Display Script:</h3>
<pre><code><script>
(function() {
var cx = 'partner-pub-1444970657765319:8190375623';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchresults-only></gcse:searchresults-only>
</code></pre>
<h3>Popular Query Script:</h3>
<pre><code><script type="text/javascript" src="http://www.google.com/cse/query_renderer.js"></script>
<div id="queries"></div>
<script src="http://www.google.com/cse/api/partner-pub-1444970657765319/cse/8190375623/queries/js?oe=UTF-8&amp;callback=(new+PopularQueryRenderer(document.getElementById(%22queries%22))).render"></script>
</code></pre>
<h3>Added CSS:</h3>
<pre><code>/*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}
</code></pre>
<h3>Screenshot Before Search:</h3>
<p><a href="https://i.stack.imgur.com/u1gmu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u1gmu.png" alt="enter image description here"></a></p>
<h3>Screenshot After Search:</h3>
<p><a href="https://i.stack.imgur.com/3wpxs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3wpxs.png" alt="Code Review Search"></a></p>
<h3>Screenshot for "Code Review" search:</h3>
<p><a href="https://i.stack.imgur.com/g2OyN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g2OyN.png" alt="Code Review Result"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:57:07.707",
"Id": "415647",
"Score": "2",
"body": "What does `cx` refer to? Is that a fixed variable or is it dynamic?"
}
] | [
{
"body": "<p>So after testing it, you don't really need to define it in your javascript. You can simply add it in your HTML before all your other scripts.</p>\n\n<p>That's what <code>s.parentNode.insertBefore(gcse, s);</code> does. It finds the first occurence of a script tag in your HTML (which is kind of funny as it won't work if there are no script tags in your HTML), and adds your new script before it.</p>\n\n<p>So if the first occurence of a script tag appears in the HEAD, then it'll be placed in the head'</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-html lang-html prettyprint-override\"><code><script src=\"https://cse.google.com/cse.js?cx=017643444788069204610:4gvhea_mvga\" async type=\"text/javascript\"></script>\n<gcse:search></gcse:search></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Making your javascript <em>more efficient</em> will be difficult as 1. there isn't much happening and 2. it's already very short.</p>\n\n<p>But you could do something like this (which doesn't change much)... </p>\n\n<pre><code>// google search placeholder\n(function(cx) { \n const gcse = document.createElement('script');\n gcse.type = 'text/javascript';\n gcse.async = true;\n gcse.src = `https://cse.google.com/cse.js?cx=${cx}`;\n const s = document.getElementsByTagName('script')[0];\n s.parentNode.insertBefore(gcse, s);\n})('!!!!!!!!!!!!!!!!!!!');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:30:26.017",
"Id": "214937",
"ParentId": "214875",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214937",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-06T23:48:09.957",
"Id": "214875",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"api",
"dom"
],
"Title": "Google Custom Search placeholder function in JavaScript"
} | 214875 |
<p>I am working on problem where I need to decode a string:</p>
<blockquote>
<p>A message containing letters from A-Z is being encoded to numbers
using the following mapping:</p>
<blockquote>
<p>'A' -> 1<br>
'B' -> 2<br>
...<br>
'Z' -> 26</p>
</blockquote>
<p>Given a non-empty string containing only digits, determine the total
number of ways to decode it.</p>
<h3>Example 1:</h3>
<p>Input: "12"<br>
Output: 2<br>
Explanation: It could be decoded as "AB" (1 2) or "L" (12).</p>
<h3>Example 2:</h3>
<p>Input: "226"<br>
Output: 3<br>
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).</p>
</blockquote>
<p>I came up with the following recursive approach and it works fine. Is there any better or efficient way to solve the same problem?</p>
<pre><code> public static int decode(String data) {
int[] memo = new int[data.length() + 1];
return helper(data, data.length(), memo);
}
private static int helper(String data, int k, int[] memo) {
if (k == 0)
return 1;
int s = data.length() - k;
if (data.charAt(s) == '0')
return 0;
if (memo[k] != 0) {
return memo[k];
}
int result = helper(data, k - 1, memo);
if (k >= 2 && Integer.parseInt(data.substring(data.length() - k, data.length() - k + 2)) <= 26) {
result += helper(data, k - 2, memo);
}
memo[k] = result;
return result;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T11:48:21.147",
"Id": "415769",
"Score": "0",
"body": "Possible duplicate of [Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded](https://codereview.stackexchange.com/questions/213972/given-the-mapping-a-1-b-2-z-26-and-an-encoded-message-count-the-nu)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T03:08:07.777",
"Id": "415860",
"Score": "2",
"body": "@TorbenPutkonen duplicates are defined a bit differently on this site. Please read [this relevant meta answer](https://codereview.meta.stackexchange.com/a/3821/120114)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T10:05:52.830",
"Id": "437893",
"Score": "0",
"body": "Or this meta: https://codereview.meta.stackexchange.com/questions/9204/out-dated-duplicates-definition-in-help-center"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T09:23:43.230",
"Id": "438352",
"Score": "0",
"body": "*\"It works fine\"* is usually best demonstrated by including your **unit tests** with the code for review."
}
] | [
{
"body": "<p>First off, as mentioned in the comments the variable and function name(s) could be a bit more descriptive. <code>decode</code> is fine, but <code>helper</code> should be renamed to something like <code>count_decodings</code>. <code>k</code> could be <code>len</code> or <code>substring_length</code>. I disagree with the comments about <code>data</code> though- we know nothing about the string being passed, so the only more apt name would be lowercase <code>string</code>, which at first glance may get confused with the type.</p>\n\n<p>Moving on to structure, you can actually revise your algorithm to do away with <code>k</code>, and make the substring logic simpler. Assume the string that is passed is the entire string- no offset. Then call your function recursively on a substring of the input string.</p>\n\n<pre><code>private static int helper(String data, int[] memo) {\n if (data.length() == 0)\n return 1;\n if (data.charAt(0) == '0')\n return 0;\n if (memo[data.length()] != 0) {\n return memo[data.length()];\n }\n\n int result = helper(data.substring(1), memo);\n if (data.length() > 1 && Integer.parseInt(data.substring(0, 2)) <= 26) {\n result += helper(data.substring(2), memo);\n }\n memo[data.length()] = result;\n return result;\n}\n</code></pre>\n\n<p>As you can see, this results in far less index juggling, and is far easier for someone else to read. <a href=\"https://stackoverflow.com/a/54976521/6221024\">When I was writing this answer</a> there were at least two other answers trying to figure out the correct way to juggle these indices to make the algorithm work, and both were since deleted by their authors because they were too error prone / couldn't get it working quite right. If that doesn't say something about the maintainability and readability of index juggling, I don't know what does.</p>\n\n<p>Lastly, I'd like to speculate that the algorithm could possibly be sped up by minimizing the conversions between strings and integers. You could possibly replace</p>\n\n<pre><code>data.substring(0, 2)) <= 26\n</code></pre>\n\n<p>with</p>\n\n<pre><code>data.substring(0, 2).compareTo(\"26\") < 1\n</code></pre>\n\n<p>-which would save the conversion, but at the cost of confusion and bad form (comparing numerical values as strings). Alternatively, you could convert data to an integer once, and then do floored division and modular reduction by 10 to get your digits and \"substrings\". These would only provide constant speedups at best, however.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T08:59:38.987",
"Id": "214898",
"ParentId": "214878",
"Score": "1"
}
},
{
"body": "<p>To me, the code does not express the solution in a way that is easily connected to the description of the problem. \"Message\" becomes <code>data</code>. It's not really clear <em>to me</em> how \"number of ways\" is represented in the code except as the ultimate return value. </p>\n\n<h3>Business Logic</h3>\n\n<p>Deeper down, the code does not reflect the way I reason through the examples. I understand </p>\n\n<pre><code>\"12\" -> 2\n\"226\" -> 3\n</code></pre>\n\n<p>imply that \"one followed by any number\" and \"two followed by 0,1,2,3,4,5, or 6\" can be interpreted two ways. </p>\n\n<p>Pseudo-code that looks <em>more</em> like the business logic <em>to me</em>:</p>\n\n<pre><code>// if all characters are not digits, \n// there are zero ways to interpret the message\nif not Message.allDigits() return 0\n\n// if the message is only zeros, \n// there are zero ways to interpret the message\nif Message.allDigitsAreZero() return 0\n\n// otherwise there is at least one way to interpret it\nways = 1\n\n//using one based index for simplicty\nFor i from 0 to Message.length\n case\n i equals Message.length() {\n return ways\n Message.charAt(i) is '0'\n i++\n Message.charAt(i) is '1' \n ways += 1\n i++\n Message.charAt(i) is '2' \n AND Message.charAt(i+1) is '[0-6]'\n ways += 1\n i++\n end case\n</code></pre>\n\n<h3>Pseudo-Code as a specification</h3>\n\n<p>The pseudo-code defines a solution shape that is more independent of the language used to implement it. It reflects the problem and not the language we use to implement it.</p>\n\n<h3>Validation suggests an implementation approach</h3>\n\n<p>Starting with data validation (<code>allDigits</code> and <code>allDigitsZero</code>) on the whole message suggests regex's -- anything else is more work to implement. </p>\n\n<pre><code>allDigits(Message)\n Message.matches(\"\\d{\" + string.length + \"}\")\n\nallDigitsZero(Message)\n Message.matches(\"0{\" + string.length + \"}\")\n</code></pre>\n\n<p>Using regexes the rule for <code>1</code> might look like:</p>\n\n<pre><code> // One indexing is messy here.\n // Zero indexing would be cleaner\n Message.matches(\".{\" + i-1 + \"}1\\d*\")\n ways += 1\n i++\n</code></pre>\n\n<h3>Implementation approach suggests an architecture</h3>\n\n<p>But that's a bit less readable than I want to try to figure out six weeks from now. This is a case where recursion can help make the code more readable <strong>assuming the reader can read recursion.</strong> </p>\n\n<pre><code>// overloading decode\nint decode(Message, ways)\n case\n Message.length equals 1\n return ways\n Message.matches(\"1\\d*)\"\n decode(Message.substring(2), ways+1) // one indexed\n Message.matches(\"2[0-6]\")\n decode(Message.substring(2), ways+1) // one indexed\n decode(Message.substring(2), ways+1) // one indexed\n end case\n</code></pre>\n\n<h3>Discussion</h3>\n\n<p><strong>Is this more efficient?</strong> Without profiling running code in a production environment, there's no way to tell. The JVM performs more optimizations than most people can readily reason about. Plus there's no way to tell if more efficiency here matters. If the messages are being read from disk, or coming from the internet, or even read from RAM, <code>decode</code> probably isn't the bottle neck. And the system is almost certainly running other code.</p>\n\n<p><strong>Is it better?</strong> Maybe. Maybe not. In Java, Loops are idiomatic. Recursion not so much. If other parts of the system are recursive then recursive code is more consistent with the rest of the code base. If it's the only piece of recursive code, then recursion might not be the better choice.</p>\n\n<p>One way in which a regex approach might be better is that it does not require changing the data type. We get a string and operate on it as a string. Recursion using <code>substring</code> makes the code less complex (again, assuming the people reading it can readily read recursion).</p>\n\n<p>One way in which a regex approach might be worse is that pattern matching is not a primary Java idiom. It's mostly reserved for strings. Other languages use it more extensively. But we start with a string, so it's more likely ok.</p>\n\n<h3>Final thoughts</h3>\n\n<ul>\n<li>Better names</li>\n<li>Logic that looks like the business problem</li>\n<li>Comments, please</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T17:11:43.553",
"Id": "225664",
"ParentId": "214878",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T00:12:57.977",
"Id": "214878",
"Score": "3",
"Tags": [
"java",
"algorithm",
"strings",
"recursion",
"dynamic-programming"
],
"Title": "Counting the number of ways to decode a string"
} | 214878 |
<p>I'm working on learning C++ coming from python. I'm doing some projects to help me out understanding the language a bit more.</p>
<p>My code works I just want to know if there is anything that I can improve on it or best practices in C++, maybe something that I should have done differently.</p>
<pre><code>// Ceaser Cipher implementation
#include <iostream>
#include <string>
char shiftF(char ch, int shift, const char type)
{
if (type == 'e')
{
return ch == 'z' || ch == 'Z' ? ch - 25 : ch + shift;
}
else if (type == 'd')
{
return ch == 'z' || ch == 'Z' ? ch - 25 : ch - shift;
}
}
std::string encode(std::string str, int shift, char type)
{
std::string tempMsg;
for (auto ch : str)
{
if (isalpha(ch))
{
tempMsg += shiftF(ch, shift, type);
}
else if (isspace(ch))
{
// There is probably a better way to do this.
tempMsg += " ";
}
else if (isalnum(ch))
{
continue;
}
}
return tempMsg;
}
int main(int argc, char *argv[])
{
int choice;
std::cout << "What do you want to do? 1.Encrypt, 2.Decrypt: ";
std::cin >> choice;
std::string result;
const char dec = 'd';
const char enc = 'e';
if (choice == 1)
{
int key;
std::cout << "Enter encryption shift: ";
std::cin >> key;
std::string msg;
std::cout << "Enter a message: ";
// This doesn't work for some reason?
// std::cin.clear();
// std::cin.sync();
std::cin.ignore();
std::getline(std::cin, msg);
result = encode(msg, key, enc);
}
else if (choice == 2)
{
int key;
std::cout << "Enter decryption shift: ";
std::cin >> key;
std::string msg;
std::cout << "Enter a message: ";
std::cin.ignore();
std::getline(std::cin, msg);
result = encode(msg, key, dec);
}
else
{
std::cout << "Wrong option, exiting!";
}
std::cout << "Message encoded: " << result;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T12:08:49.167",
"Id": "416002",
"Score": "0",
"body": "Given your follow-up question, I would encourage you to accept on the of the answers below (click the tick mark below the upvote/downvote buttons). This helps the StackExchange system by treating your question as \"solved\" instead of bumping it to front page periodically. It also avoids not skewing site statistics."
}
] | [
{
"body": "<p>Your functions are doing too much. Remember: <em>one function, one responsibility</em>. That is, the <code>encode</code> function actually both encodes and decodes and that behavior is controlled via its arguments. In particular, the choice of behavior is offloaded to <code>shiftF</code> based on a <code>char</code>. There is no error if that <code>char</code> is anything other than <code>'d'</code> or <code>'e'</code>. This is something that we should absolutely try to avoid: we want to catch as many problems as we can at compile-time, but even runtime errors are preferred to silent errors!</p>\n\n<p>On closer inspection, there is no need for such a complication. In fact, the only difference between encoding and decoding is the sign of <code>shift</code>. So we could write:</p>\n\n<pre><code>std::string encode(const std::string& str, int shift)\n{\n std::string tempMsg;\n\n std::transform(str.cbegin(), str.cend(), std::back_inserter(tempMsg), [&](char ch) -> char\n { \n if (isspace(ch))\n return ' ';\n\n return ch == 'z' || ch == 'Z' ? ch - 25 : ch + shift; \n });\n\n return tempMsg;\n}\n\nstd::string decode(const std::string& str, int shift)\n{\n return encode(str, -1 * shift);\n}\n</code></pre>\n\n<p>What is happening here?</p>\n\n<ul>\n<li><p>We pass the input message <code>str</code> as a const-ref and not by-value as in your original code. When you pass by-value, the object gets copied and in this case there is no reason for it. In this case, you could actually even pass the object by-reference only, and modify it in-place but we're not doing it here.</p></li>\n<li><p>We use a standard function <a href=\"https://en.cppreference.com/w/cpp/algorithm/transform\" rel=\"nofollow noreferrer\"><code>std::transform</code></a> with a <a href=\"https://en.cppreference.com/w/cpp/language/lambda\" rel=\"nofollow noreferrer\">lambda function</a> that encapsulates the logic of <code>shiftF</code>. You need to include <code><algorithm></code> for this use.</p></li>\n<li><p>The third argument for <code>std::transform</code> is <code>std::back_inserter</code> found from <code><iterator></code>, which takes care of inserting at the back of the string <code>tempMsg</code>.</p></li>\n<li><p>Conceptually, the division of encoding and decoding into separate functions is cleaner and more logical. Whenever you can implement another function in terms of other functions, it's likely a good idea because you don't have to repeat yourself leading to less maintenance decreasing the chances for bugs.</p></li>\n</ul>\n\n<p>Once you adopt this approach, you can get rid of the <code>const char</code> variables from your main program, and just call the correct <code>encode</code> or <code>decode</code> function inside your if-statement. As a side remark, you could also return meaningful error codes in your main. For example, if the choice is invalid, return from the else-branch e.g., <code>EXIT_FAILURE</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:10:32.327",
"Id": "415625",
"Score": "0",
"body": "Does std::transform act as the for loop? Another question, why are you using the reference for str? I still get confused when to use references and pointers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:16:57.477",
"Id": "415627",
"Score": "0",
"body": "(1) Yes, with std::transform the first two parameters say \"go from begin to end in this range\", the third argument says \"this is where the result from each iteration of the loop goes to\" and the fourth argument is \"apply this operation in the loop\". (2) I use a *constant reference* to `str`. When it's const, you can't modify its content inside the function. This is good because it conveys meaning and gives you protection from unintended mistakes. The reference means you do *not* copy the argument into the function, but directly play with that argument. Does it make sense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:20:50.927",
"Id": "415628",
"Score": "0",
"body": "And basically, just don't use pointers unless you have to. They are not evil, but you have to be careful especially if you use \"naked pointers\" (e.g., allocate memory dynamically without so-called smart pointers). If you talk about argument passing (that's a keyword you can search for), cheap-to-copy built-ins (int, float, char) you usually pass as `int x` and so. With more expensive objects, you should avoid copying them (like `std::string` etc.) and pass those by reference (which you should make const as well unless you need to modify the object)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:30:08.260",
"Id": "415630",
"Score": "0",
"body": "You explained it very well thank you! So if I use references I'm passing the object itself otherwise it's a copy? Why should I use the object itself? Memory efficiency? Coming from python/java pointers and references kill me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:56:08.340",
"Id": "415635",
"Score": "0",
"body": "Exactly, that's basically it. And yep, why copy a string if you want to say convert it to uppercase, taking it by reference avoids unnecessary copying. Having these options roughly means you have more control over your program, which unlocks potential for more performance but also makes it easier to shoot yourself in the foot."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:38:39.017",
"Id": "214902",
"ParentId": "214879",
"Score": "3"
}
},
{
"body": "<p>The code makes the assumption that the runtime character set encodes letters contiguously in order. Whilst this may be true on your system, it will fail on platforms that use <a href=\"https://en.wikipedia.org/wiki/EBCDIC\" rel=\"nofollow noreferrer\">EBCDIC</a> or other codings with gaps between letters. It will also fail for codings such as IS 8859, which have letters outside of <code>a..z</code>,<code>A..Z</code> (e.g. <code>à</code>).</p>\n<p>We're missing the include of <code><cctype></code> which defines <code>std::isalpha</code>, <code>std::isspace</code> and <code>std::isalnum</code> (all of which are misspelt in the code).</p>\n<p>When reading input, always have a plan for what happens if the read fails. So <code>std::cin >> key</code> needs to be <code>if (std::cin >> key)</code> with appropriate code in the <code>if</code> and <code>else</code> branches.</p>\n<p>Consider working as a filter for standard input, rather than operating on just a single line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:21:12.457",
"Id": "415598",
"Score": "0",
"body": "I'm using visual studio and it didn't show any errors on isalpha/isspace, strange and when I ran \"Hello World\" it handled the space well and entered the isspace condition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:04:31.797",
"Id": "415607",
"Score": "1",
"body": "It's unfortunate that even the best compilers can't spot all the possible portability problems in our code - it still takes a human to pick up some of these."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:09:41.900",
"Id": "214910",
"ParentId": "214879",
"Score": "3"
}
},
{
"body": "<p>Not sure you ceaser cipher is working as expected:</p>\n\n<pre><code>return ch == 'z' || ch == 'Z' ? ch - 25 : ch + shift;\n</code></pre>\n\n<p>There is a special case for <code>z</code> or <code>Z</code>. This is not symmetric so decoding an encoded 'Z' or 'z' will fail. Also letters can be encoded as punctuation (which is why your <code>encode()</code> does not even try to enocde punctuation. I would fix this so that letters are encoded as letters (everything else is unencoded).</p>\n\n<p>I would change your encoding to:</p>\n\n<pre><code>// int min: Pass 'a' for std::islower() and 'A' for std::isupper()\n// int dir: Pass 1 for encode and -1 for decode.\nchar code(char ch, int shift, char dir, int min)\n{\n return (ch + min + (dir * shift) % 26) + min;\n}\n</code></pre>\n\n<p>Now that letters are encoced into other letters only (and don't splash out in into the punctuation range). We can simplify the shift function. It will handle letters and all other characters are left unencoded.</p>\n\n<pre><code>char shiftF(char ch, int shift, char dir)\n{\n if (std::isalpha(ch) && std::islower(ch)) {\n return code(ch, shift, dir, 'a');\n }\n else if (std::isalpha(ch) && std::isupper(ch)) {\n return code(ch, shift, dir, 'A');\n }\n return ch;\n}\n</code></pre>\n\n<p>As the shift now handles all letters correctly we don't need to any real work in the encode. But to make it safer and stop a sensitive string from being leaked around memory lets us change it to update the string in place.</p>\n\n<pre><code>void encode(std::string& str, int shift, char dir)\n{\n for (auto& ch : str) {\n ch = shiftF(ch, shift, dir);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-11T23:28:14.207",
"Id": "215221",
"ParentId": "214879",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T00:19:27.447",
"Id": "214879",
"Score": "4",
"Tags": [
"c++",
"caesar-cipher"
],
"Title": "Implementation, Ceaser Cipher in C++"
} | 214879 |
<p>I have multiple products that all have sizes and I need to find the cheapest configuration that meets the minimum required size.</p>
<p>For example, John needs a minimum of 10 litres of storage - it can be more, but not less. </p>
<p>There are 2L, 3L, 5L, 8L and 10L options (but this can change). </p>
<p>As an example, it might be cheaper to get:</p>
<ul>
<li>1x10L container OR</li>
<li>2x5L containers OR</li>
<li>1x2L, 1x3L and 1x5L OR</li>
<li>4x3L (this one is over 10 L, but it is still possible that it will be cheaper)</li>
</ul>
<p>So far I've tried looping over and over up to 4 times (because typically the maximum requirement will be 40 L), but in some cases I am running out of memory, and it doesn't seem like the most efficient way of doing it.</p>
<pre><code>
// Size is in mL
$available_containers = [
[
'id' => 22700,
'price' => 1190,
'size' => 2000,
],
[
'id' => 22701,
'price' => 1245,
'size' => 3000,
],
[
'id' => 22702,
'price' => 1415,
'size' => 4000,
],
[
'id' => 22715,
'price' => 12300,
'size' => 5000,
],
[
'id' => 22706,
'price' => 1740,
'size' => 5000,
],
[
'id' => 22703,
'price' => 1510,
'size' => 5000,
],
[
'id' => 22707,
'price' => 1790,
'size' => 6000,
],
[
'id' => 22704,
'price' => 1770,
'size' => 6000,
],
[
'id' => 22708,
'price' => 2215,
'size' => 7000,
],
[
'id' => 22705,
'price' => 2195,
'size' => 8200,
],
[
'id' => 22709,
'price' => 2660,
'size' => 8200,
],
[
'id' => 22710,
'price' => 2799,
'size' => 10000,
],
[
'id' => 22711,
'price' => 2910,
'size' => 12500,
],
[
'id' => 22712,
'price' => 3260,
'size' => 15000,
],
[
'id' => 22713,
'price' => 4130,
'size' => 20000,
],
[
'id' => 22714,
'price' => 3770,
'size' => 27000,
]
];
$required_size = 8; // Can change.
$container_install = 5;
foreach ( $available_containers as $v ){
foreach ( $available_containers as $v2 ){
foreach ($available_containers as $v3 ) {
foreach ( $available_containers as $v4 ){
$all_configs = [
[
'size' => $v['size'],
'configuration' => [ $v['size'] ],
'price' => $v['price'],
],
[
'size' => $v['size'] + $v2['size'],
'configuration' => [ $v['size'], $v2['size'] ],
'price' => $v['price'] + $v2['price'] + $container_install,
],
[
'size' => $v['size'] + $v2['size'] + $v3['size'],
'configuration' => [ $v['size'], $v2['size'], $v3['size'] ],
'price' => $v['price'] + $v2['price'] + $v3['price'] + $container_install + $container_install,
],
[
'size' => $v['size'] + $v2['size'] + $v3['size'] + $v4['size'],
'configuration' => [ $v['size'], $v2['size'], $v3['size'], $v4['size'] ],
'price' => $v['price'] + $v2['price'] + $v3['price'] + $v4['price'] + $container_install + $container_install + $container_install,
],
];
foreach ( $all_configs as $c ){
if ( $c['size'] >= $required_size ){
$configuration[] = array(
'configuration' => $c['configuration'],
'size' => $c['size'],
'price' => $c['price'],
);
}
}
}
}
}
}
// Sort by price.
$sorted_configs = array_sort($configuration, 'price', SORT_ASC); // This function simply sorts all permutations by price
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T06:00:32.693",
"Id": "415555",
"Score": "0",
"body": "That's an expensive 5L container (#22715). Sure you haven't added an extra `0`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T06:20:49.367",
"Id": "415559",
"Score": "0",
"body": "Haha thanks @AJNeufeld. Yes. Containers are actually not what I'm calculating, but I've used it to simplify the idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T06:51:34.443",
"Id": "415564",
"Score": "0",
"body": "I'd call it the cheapest combination rather than permutation, because the order doesn't matter."
}
] | [
{
"body": "<p>This problem is an instance of <a href=\"https://en.wikipedia.org/wiki/Integer_programming\" rel=\"nofollow noreferrer\">Integer Linear Programming</a>. ILP is NP-hard, so an algorithm to find the optimal solution will not be much faster than brute-force. However, a common technique to find an approximate optimum is to solve it as a <a href=\"https://en.wikipedia.org/wiki/Linear_programming\" rel=\"nofollow noreferrer\">Linear Programming</a> problem without the integer restrictions, then round the results up or down as necessary. Fortunately, many <a href=\"http://www.phpsimplex.com/en/\" rel=\"nofollow noreferrer\">libraries</a> exist to solve non-integer LP quite efficiently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T07:01:45.250",
"Id": "214893",
"ParentId": "214881",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code>foreach ( $available_containers as $v ){\n foreach ( $available_containers as $v2 ){\n foreach ($available_containers as $v3 ) {\n foreach ( $available_containers as $v4 ){\n</code></pre>\n</blockquote>\n\n<p>When you have this many loops, it's time to think about replacing the nesting with recursion.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> $all_configs = [\n [\n 'size' => $v['size'],\n 'configuration' => [ $v['size'] ],\n 'price' => $v['price'],\n ],\n</code></pre>\n</blockquote>\n\n<p>Yes, this is very inefficient.</p>\n\n<ul>\n<li>It considers each one-container solution <span class=\"math-container\">\\$N^3\\$</span> times, where <span class=\"math-container\">\\$N\\$</span> is the number of containers. </li>\n<li>If the one container already meets the size requirement then it's inefficient to consider larger sets which include it.</li>\n<li>If you've already considered <code>[#22707, #22704, #22708, #22705]</code> then there's no point considering <code>[#22704, #22707, #22708, #22705]</code>. The simple solution is to work with indices and iterate starting at the index of the previous selection.</li>\n</ul>\n\n<p>Again, a recursive approach would be preferable: it would kill three or four birds with one stone.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> foreach ( $all_configs as $c ){\n if ( $c['size'] >= $required_size ){\n $configuration[] = array(\n 'configuration' => $c['configuration'],\n 'size' => $c['size'],\n 'price' => $c['price'],\n );\n...\n\n// Sort by price.\n$sorted_configs = array_sort($configuration, 'price', SORT_ASC); // This function simply sorts all permutations by price\n</code></pre>\n</blockquote>\n\n<p>I don't think you need both of those comments - in fact, neither says anything which isn't obvious from the code.</p>\n\n<p>However, you also don't need to build an array of solutions or to sort, at least given the specification:</p>\n\n<blockquote>\n <p>I need to find <strong>the</strong> cheapest configuration that meets the minimum required size</p>\n</blockquote>\n\n<p>(my emphasis). Just track the best found so far.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T23:12:31.900",
"Id": "416382",
"Score": "0",
"body": "Thanks Peter. There are some cases where it would be cheaper to get TWO containers over one, though. Also, there are cases where a larger container might be on special, so it might be cheaper to get a 10L over an 8L, for example. I'm not sure if you've considered this? I think I have an alternate solution now anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T23:36:03.930",
"Id": "416384",
"Score": "0",
"body": "@Mando, it might be cheaper to get containers X and Y than container Z, but I'm assuming that it will never be cheaper to get containers X and Z than just Z. If some containers have negative prices, the cheapest configuration is to buy an infinite number of those containers..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-12T23:52:38.593",
"Id": "416386",
"Score": "0",
"body": "Yes - That is correct."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T08:47:22.367",
"Id": "214897",
"ParentId": "214881",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T01:53:32.720",
"Id": "214881",
"Score": "2",
"Tags": [
"php",
"mathematics"
],
"Title": "PHP find cheapest permutation"
} | 214881 |
<p>I have implemented a binary search tree using templates and unique_ptr in C++ 11. At present, only insertion and deletion are implemented. Please provide your feedback for improvements.</p>
<pre><code>#include <iostream>
#include <memory>
template<typename T>
class Btree {
public:
void insert(T data)
{
_insert(root, data);
}
void traverse(void (*func)(T data))
{
_traverse(root, func);
}
void del(T data)
{
_del(root, data);
}
private:
struct node {
T data;
std::unique_ptr<node> left, right;
node(T data): data(data), left(nullptr), right(nullptr) {}
};
std::unique_ptr<node> root;
void _insert(std::unique_ptr<node>& curr, T data);
void _del(std::unique_ptr<node>& curr, T data);
void _traverse(std::unique_ptr<node>& curr, void (*func)(T data));
T _findmin(std::unique_ptr<node> &curr);
};
template<typename T>
void Btree<T>::_insert(std::unique_ptr<node>& curr, T data)
{
if (curr == nullptr) {
curr.reset(new node(data));
return;
}
if (data < curr->data)
_insert(curr->left, data);
else
_insert(curr->right, data);
}
template<typename T>
T Btree<T>::_findmin(std::unique_ptr<node>& curr)
{
if (curr && curr->left == nullptr)
return curr->data;
return _findmin(curr->left);
}
template<typename T>
void Btree<T>::_del(std::unique_ptr<node>& curr, T data)
{
if (curr == nullptr)
return;
if (data < curr->data)
_del(curr->left, data);
else if (data > curr->data)
_del(curr->right, data);
else {
// if one child is nullptr or both child are nullptr
if (curr->left == nullptr) {
auto &p = curr->right;
curr.reset(p.release());
}
else if (curr->right == nullptr) {
auto &p = curr->left;
curr.reset(p.release());
}
//if child is non leaf node
else {
T temp = _findmin(curr->right);
curr->data = temp;
_del(curr->right, temp);
}
}
}
template<typename T>
void Btree<T>::_traverse(std::unique_ptr<node>& curr, void (*func)(T data))
{
if (curr == nullptr)
return;
_traverse(curr->left, func);
func(curr->data);
_traverse(curr->right, func);
}
</code></pre>
| [] | [
{
"body": "<p>Since <code>insert</code> gets its data by value, you're making multiple copies of that data as you navigate down the tree to find where to add the new node. Passing the parameter by <code>const T&</code> (so you only make one copy) would avoid these copies, a benefit for types that are expensive to copy. Another possibility is to use <code>T &&</code> to move the data, but this will change the original value being passed in which may be undesirable.</p>\n\n<p>The value passed to the function called by <code>_traverse</code> is also copied. Depending on your needs, this could also use a <code>const T &</code>, or overloads of <code>_traverse</code> that take <code>func</code> with a reference could be provided. The downside to providing access to the data via a reference is that it can allow that data to be altered.</p>\n\n<p>If <code>_insert</code> takes <code>curr</code> as a pointer (<code>std::unique_ptr<node>* curr</code>) then you can use a loop rather than recursion. This also applies to <code>_findmin</code> and <code>_del</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T02:27:18.343",
"Id": "214885",
"ParentId": "214882",
"Score": "0"
}
},
{
"body": "<h3>Observations</h3>\n<p>You pass data by value. This is fine for small data types like <code>int</code>. But imagine that <code>T</code> is some huge object that is very expensive to copy. You should think of passing the data by reference to avoid any intermediate copies. When you get a bit more advanced think about passing by r-value reference to allow you to move the objects.</p>\n<p>For your traversal you pass a function pointer. This is a bit limiting. Normally you would templateze the function to allow you to pass any function like object (function pointer/functor/lambda/std::function) etc.</p>\n<p>Yes you need recursion when traversing trees. But you don't need it everywhere. There are a couple of places where a simple loop would be sufficient.</p>\n<p>I can see why you use <code>std::unique_ptr</code>. But in my view a tree is a container and should manage its own memory. So I would have simply used <code>Node*</code> inside data. The code is not that much harder to write in this context. <strong>BUT</strong> I don't have any real issue with <code>std::unique_ptr</code>.</p>\n<h3>Code</h3>\n<p>Insert by const reference</p>\n<pre><code>void insert(T const& data)\n{\n _insert(root, data);\n}\n_insert(std::unique_ptr<node>& curr, T const& data)\n{\n if (curr.get() == nullptr) {\n curr.reset(new node(data));\n return;\n }\n\n auto& next = (data < curr->data) ? curr->left : curr->right;\n _insert(next, data);\n}\n</code></pre>\n<p>Insert by r-Value reference</p>\n<pre><code>void insert(T&& data)\n{\n _insert(root, std::forward<T>(data));\n}\n_insert(std::unique_ptr<node>& curr, T&& data)\n{\n if (curr.get() == nullptr) {\n curr.reset(new node(data));\n return;\n }\n\n auto& next = (data < curr->data) ? curr->left : curr->right;\n _insert(next, std::forward<T>(data));\n}\n</code></pre>\n<p>Emplace into node.</p>\n<pre><code>// This calls T constructor only when you construct the node itself.\ntemplate<typename... Args>\nvoid emplace(Args const&... args)\n{\n _emplace(root, args...));\n}\ntemplate<typename... Args>\n_emplace(std::unique_ptr<node>& curr, Args const&... args)\n{\n if (curr.get() == nullptr) {\n curr.reset(new node(args...));\n return;\n }\n\n auto& next = (data < curr->data) ? curr->left : curr->right;\n _insert(next, args...);\n}\ntemplate<typename... Args>\nnode::node(Args const&... args)\n : data(args...) // Data of type T constructed in place\n , left(nullptr)\n , right(nullptr)\n{}\n</code></pre>\n<p>Using a function like object to traverse the tree:</p>\n<pre><code>template<typename F>\nvoid traverse(const & action)\n{\n _traverse(root, action);\n}\ntemplate<typename F>\nvoid _traverse(std::unique_ptr<node>& curr, F const& action);\n\n\n// outside class\n\ntemplate<typename T>\ntemplate<typename F>\nvoid Btree<T>::_traverse(std::unique_ptr<node>& curr, F const& action)\n{\n if (curr == nullptr)\n return;\n _traverse(curr->left, action);\n action(curr->data);\n _traverse(curr->right, action);\n}\n\nint main()\n{\n Btree<int> tree;\n tree.traverse([](int x){std::cout << x << " ";});\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T02:43:38.990",
"Id": "415858",
"Score": "0",
"body": "Thanks for your review comments. For traversal (passing any function like object), can you please show an example ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T18:36:44.330",
"Id": "416043",
"Score": "0",
"body": "@bornfree: OK modified traverse so you can pass a functor or a function pointer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T20:35:02.833",
"Id": "215056",
"ParentId": "214882",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "215056",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T01:59:11.897",
"Id": "214882",
"Score": "0",
"Tags": [
"c++",
"object-oriented",
"c++11",
"design-patterns",
"pointers"
],
"Title": "Binary Search Tree implementation with unique pointers"
} | 214882 |
<p>I'm learning more about <code>PHP</code>, so I've decided to create a simple login/create account system. Entering information for creating a new account sends the data to my localhost machine, using <code>MySQLi</code> and the web server <code>MySQL</code>. I'm looking for feedback about security, efficiency, and overall code. I would like to kick old habits to the curb before it's too late. Any and all help is appreciated and considered. Thank you in advance!</p>
<p><strong>create.html</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>create.html</title>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body bgcolor="pink">
<center>
<form action="create.php" method="post">
<label>Username</label>
<input type="text" name="username"><br>
<label>Password</label>
<input type="password" name="password"><br>
<label>Re-enter Password</label>
<input type="password" name="confirm_password"><br>
<button type="submit">Create Account</button>
</form>
</center>
</body>
</html>
</code></pre>
<p><strong>create.php</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>create.php</title>
</head>
<body bgcolor="pink">
<?php
$servername = "localhost";
$username = "XXXXXXXXXX"; // Not shown
$password = "XXXXXXXXXX"; // Not shown
$dbname = "Database";
//Create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
//Test connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$new_user_usr = filter_input(INPUT_POST, 'username');
$new_user_pwd = filter_input(INPUT_POST, 'password');
$new_user_pwd_conf = filter_input(INPUT_POST, 'confirm_password');
$sql = "SELECT usr, pwd FROM Users";
$result = $mysqli->query($sql);
if($result->num_rows > 0) {
/* If passwords don't match */
if($new_user_pwd !== $new_user_pwd_conf) {
die("Passwords don't match");
}
/* If password isn't between bounds */
if(strlen($new_user_pwd) <= 7 || strlen($new_user_pwd) >= 13) {
die("Password not long enough! Must be at least 8 characters long, but not greater than 12 characters");
}
/* If username is the same as password*/
if($new_user_usr === $new_user_pwd) {
die("Username cannot equal password!");
}
while($row = $result->fetch_assoc()) {
if($row['usr'] === $new_user_usr) {
die("Username already taken");
}
}
$add = "INSERT INTO Users (usr, pwd) VALUES ('$new_user_usr', '$new_user_pwd')";
echo $mysqli->query($add) ? "user created successfully" : "Error: " . $add . "<br>" . $mysqli->error;
}
?>
</body>
</html>
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>I would like to kick old habits to the curb </p>\n</blockquote>\n\n<p>That's a very good intention. Especially given that the present code, sadly, is rather a display of such old habits. </p>\n\n<p>In order to improve, consider learning the following essentials:</p>\n\n<ul>\n<li><a href=\"https://phpdelusions.net/pdo\" rel=\"nofollow noreferrer\">PDO prepared statements</a> (be advised that PDO is superior to mysqli for learners). Basically all your queries involving variables must be run not via query() but via prepare()/execute(), with all variables in the query substituted with placeholders.</li>\n<li><a href=\"https://phptherightway.com/#password_hashing\" rel=\"nofollow noreferrer\">Password hashing</a> is essential. Just follow the simple example and store in the database not the original password but the result of password_hash() function's call.\n\n<ul>\n<li>there is no reason to limit the maximum password length. Let a user have the password as big as they wish.</li>\n</ul></li>\n<li>the <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">proper error reporting</a>. first of all, always configure PHP to report errors by itself. And then never write a single line of code that intentionally outputs the error message. It's your server's configuration should be responsible for the errors' output.</li>\n<li>Use a better code structure. Consider having both the HTML form and the handler sharing the same address, making the file with the form not called directly but included by the PHP file on demand. It will let you to utilize the <a href=\"https://stackoverflow.com/a/37923476/285587\">POST/Redirect/Get pattern</a>. Among other things it will let you to show errors nicely instead of bluntly aborting the script execution to show one. Collect all errors in the array and then run your query only if it is empty. Show the form back along the errors and the entered data otherwise. \n\n<ul>\n<li>the code used for the database connection is better to be stored in a separate file and then just included into every script that will need it.</li>\n</ul></li>\n<li>avoid the code that does nothing useful. For example, running a select query to get all users from the database in order to create a user just makes no sense. You can ditch both the query and the condition that follows.</li>\n</ul>\n\n<p>Taking all the above into consideration your code could be rewritten like this</p>\n\n<p>db.php:</p>\n\n<pre><code>$host = '127.0.0.1';\n$db = 'Database';\n$user = 'XXX';\n$pass = 'XXX';\n$charset = 'utf8mb4';\n\n$options = [\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n PDO::ATTR_EMULATE_PREPARES => false,\n];\n$dsn = \"mysql:host=$host;dbname=$db;charset=$charset\";\ntry {\n $pdo = new PDO($dsn, $user, $pass, $options);\n} catch (\\PDOException $e) {\n throw new \\PDOException($e->getMessage(), (int)$e->getCode());\n}\n</code></pre>\n\n<p>create_user.php</p>\n\n<pre><code>$errors = [];\nif ($_POST)\n{\n require 'db.php';\n\n $username = filter_input(INPUT_POST, 'username');\n $password = filter_input(INPUT_POST, 'password');\n $pwd_confirm = filter_input(INPUT_POST, 'confirm_password');\n\n if ($password !== $pwd_confirm) {\n $errors[] = \"Passwords don't match\";\n }\n if (strlen($password) < 8) {\n $errors[] = \"Password not long enough! Must be at least 8 characters long\";\n }\n if ($username === $password) {\n $errors[] = \"Username cannot equal password!\";\n }\n\n $stmt = $pdo->query(\"SELECT 1 FROM Users WHERE usr = ?\");\n $stmt->execute([$username]);\n $user_found = $stmt->fetchColumn();\n if ($user_found) {\n $errors[] = \"Username already taken\";\n }\n if (!$errors)\n {\n $hashed_password = password_hash($password, PASSWORD_DEFAULT);\n $stmt = $pdo->prepare(\"INSERT INTO Users (usr, pwd) VALUES (?, ?)\");\n $stmt->execute([$username, $hashed_password]);\n header(\"Location: .\"); // consider redirecting to the user profile\n exit;\n }\n} else {\n $username = \"\";\n}\n\ninclude 'form.php';\n</code></pre>\n\n<p>form.php</p>\n\n<pre><code><!DOCTYPE html>\n<html lang=\"en-US\">\n<head>\n <meta charset=\"UTF-8\">\n <title>create.html</title>\n <script src=\"script.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n</head>\n<body bgcolor=\"pink\">\n<center>\n <?php foreach ($errors as $error): ?>\n <p><?= $error ?></p>\n <?php endforeach ?>\n <form method=\"post\">\n <label>Username</label>\n <input type=\"text\" name=\"username\" value=\"<?= htmlspecialchars($username) ?>\"><br>\n <label>Password</label>\n <input type=\"password\" name=\"password\"><br>\n <label>Re-enter Password</label>\n <input type=\"password\" name=\"confirm_password\"><br>\n <button type=\"submit\">Create Account</button>\n </form>\n</center>\n</body>\n</html>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T07:53:13.783",
"Id": "214895",
"ParentId": "214883",
"Score": "2"
}
},
{
"body": "<p><strong><code>filter_input(INPUT_POST)</code> does nothing</strong></p>\n\n<p>Although <a href=\"http://php.net/manual/en/function.filter-input.php\" rel=\"nofollow noreferrer\"><code>filter_input()</code></a> can be very useful for validating and \nsanitizing data, when you use <code>filter_var(INPUT_POST)</code> you \nare actually not sanitizing <em>anything</em>. It just passes the raw data through and any invalid content you were hoping to \nremove, like HTML, will still be there. I believe what you are looking for is to use the <code>FILTER_SANITIZE_STRING</code> flag\nwhich will strip HTML from those values:</p>\n\n<pre><code>$new_user_usr = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);\n$new_user_pwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);\n$new_user_pwd_conf = filter_input(INPUT_POST, 'confirm_password', FILTER_SANITIZE_STRING);\n</code></pre>\n\n<p><strong>Do your data validation and error handling sooner</strong></p>\n\n<p>In this code you go to the database to get users and then you do data validation that could cause your script to exit\nbefore you use that data. That's a waste of time and processing power. Don't do anything until you have to. So get your \n<em>after</em> you validate the other data.</p>\n\n<p><strong>Don't <code>die()</code></strong></p>\n\n<p>It's good that you check for errors, but you handle them poorly. Terminating the executation of your code and dumping an \nerror message out to the user is a bad user experience. You should capture those errors, probably in an array, and then\ndisplay them in a user-friendly way so they have the opportunity to correct their mistakes and try again.</p>\n\n<p><strong>Your user check is extremely inefficient</strong></p>\n\n<p>You check to see if a user exists by iterating through every row in your table! That's just very slow and won't scale at all.\nYou can easily narrow this down to a simple query that checks to see if anyone is using the same username. If you get any \nresults back, you know someone is using that username.</p>\n\n<pre><code>// This code is insecure and I will fix that next\n$sql = \"SELECT usr FROM Users WHERE usr = '{$new_user_usr}'\");\n$result = $mysqli->query($sql);\nif ($result->num_rows) {\n die(\"Username already taken\");\n}\n</code></pre>\n\n<p><strong>You are wide open to SQL injections</strong></p>\n\n<p>our code is <em>wide open</em> to [SQL Injection][1] which is the [most dangerous web vulnerability][2]. This occurs when you \nexecute SQL queries with unsanitized user data. By placing the raw <code>$_POST</code> variable directly in your query you are \nallowing an attacker to inject their own SQL into your query and execute it. They can do anything from stealing data to \ndeleting your database.</p>\n\n<p>To combat this you must use parameterized queries. <a href=\"https://stackoverflow.com/q/60174/250259\">Stack Overflow</a> covers \nthis very well but here's what your code would like if you use <code>mysqli</code> with prepared statements:</p>\n\n<pre><code>$stmt = $mysqli->prepare('SELECT usr FROM Users WHERE usr = ?');\n$stmt->bind_param('s', $new_user_usr); // 's' specifies the variable type => 'string'\n$stmt->execute();\n$result = $stmt->get_result();\nif ($result->num_rows) {\n die(\"Username already taken\");\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>$stmt = $mysqli->prepare('INSERT INTO Users (usr, pwd) VALUES (?, ?)');\n$stmt->bind_param('ss', $new_user_usr, $new_user_pwd); \n$stmt->execute();\n$result = $stmt->get_result();\nif (!$result->affected_rows) {\n die(\"Username already taken\");\n}\n</code></pre>\n\n<p><strong>Never store plain text passwords</strong></p>\n\n<p>Never, ever, store plain text passwords. It is a huge security nightmare and there is no excuse to do it. \nPlease use <strong><a href=\"//php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\">PHP's built-in functions</a></strong> to handle password security.</p>\n\n<pre><code>// Do this *before* you insert into the database\n$new_user_pwd = password_hash($new_user_pwd, PASSWORD_BCRYPT, $options);\n\n// Do this when you want to verify a password\nif (password_verify($new_user_pwd, $row['pwd'])) {\n echo 'Password is valid!';\n} else {\n echo 'Invalid password.';\n}\n</code></pre>\n\n<p>Make sure you <strong><a href=\"//stackoverflow.com/q/36628418/1011527\">don't escape passwords</a></strong> or use any other cleansing mechanism \non them before hashing. Doing so changes the password and causes unnecessary additional coding.</p>\n\n<p><strong>Put your database credentials some more secure</strong></p>\n\n<p>Your database credentials are considered sensitive information and should be treated as such. Putting it in your PHP code\npotentially leaves it open to discovery. If your web server has an issue and instead of rendering your PHP code it displays\nit as plain text, your credentials will be publicly available for all to see. You should consider moving it to its own \nconfiguration file which is placed outside of your web root so it cannot be accessed through a browser at any time.</p>\n\n<p><strong>Separate concerns</strong></p>\n\n<p>Try to separate your HTML and business logic. It's okay to have PHP in your HTML templates for dynamic content, but business\nlogic is best separated from your HTML as coupling them together makes your code less flexible and potentially more difficult \nto maintain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:13:23.097",
"Id": "214919",
"ParentId": "214883",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214919",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T02:14:09.007",
"Id": "214883",
"Score": "2",
"Tags": [
"php",
"html",
"mysqli"
],
"Title": "PHP New User Creation"
} | 214883 |
<p>Python beginner here. Building an OOP bank account program with SQLite and starting to struggle a bit with its design. From a design standpoint I have a file (bank) which calls ATM. ATM simulates an ATM, and is the file which then calls bank_account or credit_card depending on the account data passed in from bank.</p>
<p>To initially setup an account I decided to put this into a different file, for example <code>bank_account_setup</code> or for <code>credit_card</code>, <code>credit_card_setup</code>. These would <code>create_account</code>, help setup pin etc so that the account is created and ready to use. Then the actual bank_account or <code>credit_card</code> contains other functions, like, deposit, withdraw, get_balance etc. Also, send_email is in another file</p>
<p>My question is basically around my design. Is there a way to structure this better? How about my setup files to create bank or credit card accounts? Is that a good or bad idea? Also, another issue I am having is that when I run bank I pass in account type to ATM. In ATM I then had to know what class I am using in advance and instantiate that inside ATM. Could I handle that dynamically? (Also, the code does work - just concerned with bad design).</p>
<p>DB Schema (this is mostly correct but some fields may have been added by hand to sqlite):</p>
<pre><code>c.execute("""CREATE TABLE IF NOT EXISTS bank_account (
name text,
social integer,
account_number integer PRIMARY KEY,
balance integer,
pin integer
)""")
c.execute("""CREATE TABLE IF NOT EXISTS credit_card (
name text,
social integer,
account_number integer PRIMARY KEY,
balance integer,
card_no integer,
credit_score integer,
credit_limit integer
)""")
c.execute("""CREATE TABLE IF NOT EXISTS savings_account (
name text,
social integer,
account_number integer PRIMARY KEY,
balance integer,
rate real
)""")
c.execute("""CREATE TABLE IF NOT EXISTS notifications (
name text,
email_address,
account_number integer PRIMARY KEY,
account_type,
notif_bal,
notif_deposits,
notif_overdraft
)""")
c.execute("""CREATE TABLE IF NOT EXISTS auth_code (
account_number integer PRIMARY KEY,
account_type,
email,
auth_code
)""")
</code></pre>
<p>Here's my calling file bank:</p>
<pre><code>import atm
class BankAccount:
def __init__(self, name, social, account_number, balance, acctype):
self.name = name
self.social = social
self.account_number = account_number
self.balance = balance
self.acctype = acctype
if __name__ == '__main__':
obj1 = atm.ATM.main_menu( "Frank Smith", 135063522, 5544, 850, 'credit_card', 4400110022004400)
</code></pre>
<p>Here's ATM, which calls the other files:</p>
<pre><code>import sqlite3, smtplib
import bank_account
import secrets
import send_email
import credit_card
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
conn = sqlite3.connect('bank_account.db')
c = conn.cursor()
class ATM:
def get_pin(account_number, acctype, user_pin):
with conn:
db_pin = c.execute("SELECT pin from {} WHERE account_number=:account_number".format(acctype),
{'account_number':account_number})
db_pin = c.fetchone()
if db_pin is not None:
return(db_pin[0])
else:
print("db pin is None")
pass
def set_pin(account_number, acctype, input_code):
with conn:
get_code = ATM.get_user_code(account_number, acctype)
if get_code is None:
pass
print("You need to request an authorization code first before you set your pin")
else:
if get_code !=input_code:
print("Authorization code not valid")
else:
pin = input("Please set your 4 digit pin: ")
if len(pin) < 4 or len(pin) >4 or len(pin) == 4 and pin.isdigit()==False:
print("This is not a 4 digit pin")
else:
print("pin accepted")
c.execute("""UPDATE {} SET pin=:pin
WHERE account_number =:account_number""".format(acctype),
{'account_number':account_number, 'pin':pin})
print("Pin for account has been updated")
def main_menu(name, social, account_number, balance, acctype, card_no=None):
# obj1 = bank_account.BankAccount(name, social, account_number, balance, acctype)
# obj1 = credit_card.CreditCard(name, social, account_number, balance, acctype, card_no)
user_pin = int(input("\nATM Home Screen. Please enter your pin code: "))
db_pin = ATM.get_pin(account_number, acctype, user_pin)
if user_pin != db_pin and db_pin != '':
print("No pin match")
elif db_pin is '':
print("Pin has not been set")
print("First request an authorization code and use that to set the pin")
else:
user_pin == db_pin
print("\nPin accepted continue \n ")
print("""""""ATM Menu, choose an option""""""")
print("\n1 - Deposit funds")
print("2 - Withdraw funds")
print("3 - Check balance")
print("4 - Reset Pin")
print("5 - Exit")
while True:
try:
choice = int(input("Please enter a number: "))
except ValueError:
print("This is not a number")
if choice >= 1 and choice <=5:
if choice == 1:
amount = input("\nPlease enter the deposit amount: ")
if amount != '' and amount.isdigit():
int(amount)
obj1.deposit( account_number, acctype, amount)
else:
print("Please enter a valid number")
elif choice == 2:
amount = input("Please enter the withdrawl amount: ")
if amount != '' and amount.isdigit():
int(amount)
obj1.withdraw(account_number, acctype, amount)
else:
print("Please enter a valid number")
elif choice ==3:
obj1.get_balance(account_number, acctype)
elif choice ==4:
new_pin = input("Please enter a new 4 digit pin: ")
if new_pin != '' and new_pin.isdigit():
int(new_pin)
obj1.set_reset_pin(account_number, acctype, new_pin)
elif choice ==5:
break
else:
print("Not a valid number")
</code></pre>
<p>ALL of bank_account_setup:</p>
<pre><code>import sqlite3
import secrets
import getpass
import smtplib, sqlite3
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import send_email
conn = sqlite3.connect('bank_account.db')
c = conn.cursor()
class BankAccount:
def __init__(self, name, social, account_number, balance, acctype):
self.name = name
self.social = social
self.account_number = account_number
self.balance = balance
self.acctype = acctype
""" create different accounts based on account type passed in """
def create_account(self, name, social, account_number, balance, acctype, card_no=None, credit_score=None, credit_limit=None):
self.rate = None
with conn:
# account_found = BankAccount.get_account(self, account_number, acctype)
# if not account_found:
if acctype == 'bank_account':
c.execute("INSERT INTO {} VALUES (:name, :social, :account_number, :balance, :pin)".format(acctype),
{'name':name, 'social': social,'account_number': account_number, 'balance':balance, 'pin':''})
print("New account: {} has been created, acc # is: {}".format(acctype, account_number))
elif acctype == 'savings_account':
c.execute("INSERT INTO {} VALUES (:name, :social, :account_number, :balance, :rate)".format(acctype),
{'name':name, 'social': social,'account_number': account_number, 'balance':balance, 'rate':''})
print("New account: {} has been created, acc # is: {}".format(acctype, account_number))
elif acctype == 'credit_card':
c.execute("INSERT INTO credit_card VALUES (:name, :social, :account_number, :balance, :card_no,:credit_score, :credit_limit, :pin)",
{'name':name, 'social': social,'account_number': account_number, 'balance':balance, 'card_no'
:card_no, 'credit_score':credit_score, 'credit_limit':credit_limit, 'pin':'' })
print("New account: {} has been created, acc # is: {}".format(acctype, account_number))
conn.commit()
""" Show all rows in DB for the the account type passed in """
def get_account(self,account_number, acctype):
with conn:
account_find = c.execute("SELECT * from {} WHERE account_number=:account_number".format(acctype),
{'account_number':account_number})
account_found = c.fetchone()
if not account_found:
print("No {} matching that number could be found".format(acctype))
else:
print("Account type: {} exists!".format(acctype))
print(account_found)
return(account_found)
""" Generate a random string for card activation """
def set_user_code(self, account_number, acctype, email):
with conn:
# account_found = BankAccount.get_account(self, account_number, acctype)
account_found = BankAccount.get_user_code(self, account_number, acctype)
if not account_found:
auth_code = secrets.token_hex(4)
print("User code {} generated".format(auth_code))
c.execute("INSERT INTO auth_code VALUES (:account_number, :acctype, :email, :auth_code)",
{'account_number': account_number, 'acctype': acctype, 'email':email, 'auth_code':auth_code})
print("DB updated with auth code for account")
subject = 'Authorization code'
body = 'Authorization code: {}\n \
Use the authorization code when setting your pin for the first time'.format(auth_code)
email_user = 'testpython79@gmail.com'
email_send = 'testpython79@gmail.com'
email_pass = 'Liverpool27'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(email_user, email_pass)
text = msg.as_string()
server.sendmail(email_user, email_send, text)
server.quit
else:
print("Auth code {} is already set for this account {} ".format(account_found[2], account_number))
conn.commit()
def get_user_code(self,account_number, acctype):
with conn:
account_found = c.execute("SELECT auth_code from auth_code WHERE account_number=:account_number",
{'account_number':account_number})
account_found = c.fetchone()
if account_found is None:
pass
# print("You need to request an authorization code first before you set your pin")
else:
return(account_found[0])
""" Set pin for an account based on the auth code entered for validation """
def set_pin(self,account_number, acctype, input_code):
with conn:
get_code = BankAccount.get_user_code(self, account_number, acctype)
if get_code is None:
pass
print("You need to request an authorization code first before you set your pin")
else:
if get_code !=input_code:
print("Authorization code not valid")
else:
pin = input("Please set your 4 digit pin: ")
if len(pin) < 4 or len(pin) >4 or len(pin) == 4 and pin.isdigit()==False:
print("This is not a 4 digit pin")
else:
print("pin accepted")
c.execute("""UPDATE {} SET pin=:pin
WHERE account_number =:account_number""".format(acctype),
{'account_number':account_number, 'pin':pin})
print("Pin for account has been updated")
if __name__ == '__main__':
obj1 = BankAccount("Alexis Sanchez", 135063522, 5534, 100, 'bank_account')
# obj1.create_account("Alexis Sanchez", 135063522, 5534, 100, 'bank_account')
# obj1.set_user_code(5534, 'bank_account', 'asanchez@noemail.com')
obj1.set_pin(5534, 'bank_account', '1f7bd3f9')
</code></pre>
<p>ALL of bank_account:</p>
<pre><code>import sqlite3
import secrets
import getpass
import smtplib, sqlite3
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import send_email
conn = sqlite3.connect('bank_account.db')
c = conn.cursor()
class BankAccount:
def __init__(self, name, social, account_number, balance, acctype):
self.name = name
self.social = social
self.account_number = account_number
self.balance = balance
self.acctype = acctype
""" create different accounts based on account type passed in """
def create_account(self, name, social, account_number, balance, acctype, card_no=None, credit_score=None, credit_limit=None):
self.rate = None
with conn:
# account_found = BankAccount.get_account(self, account_number, acctype)
# if not account_found:
if acctype == 'bank_account':
c.execute("INSERT INTO {} VALUES (:name, :social, :account_number, :balance, :pin)".format(acctype),
{'name':name, 'social': social,'account_number': account_number, 'balance':balance, 'pin':''})
print("New account: {} has been created, acc # is: {}".format(acctype, account_number))
elif acctype == 'savings_account':
print("Savings account")
c.execute("INSERT INTO {} VALUES (:name, :social, :account_number, :balance, :rate)".format(acctype),
{'name':name, 'social': social,'account_number': account_number, 'balance':balance, 'rate':''})
print("New account: {} has been created, acc # is: {}".format(acctype, account_number))
elif acctype == 'credit_card':
c.execute("INSERT INTO credit_card VALUES (:name, :social, :account_number, :balance, :card_no,:credit_score, :credit_limit, :pin)",
{'name':name, 'social': social,'account_number': account_number, 'balance':balance, 'card_no'
:card_no, 'credit_score':credit_score, 'credit_limit':credit_limit, 'pin':'' })
print("New account: {} has been created, acc # is: {}".format(acctype, account_number))
conn.commit()
""" Generate a random string for card activation """
def set_user_code(self, account_number, acctype, email):
with conn:
# account_found = BankAccount.get_account(self, account_number, acctype)
account_found = BankAccount.get_user_code(self, account_number, acctype)
if not account_found:
auth_code = secrets.token_hex(4)
print("User code {} generated".format(auth_code))
c.execute("INSERT INTO auth_code VALUES (:account_number, :acctype, :email, :auth_code)",
{'account_number': account_number, 'acctype': acctype, 'email':email, 'auth_code':auth_code})
print("DB updated with auth code for account")
subject = 'Authorization code'
body = 'Authorization code: {}\n \
Use the authorization code when setting your pin for the first time'.format(auth_code)
email_user = 'testpython79@gmail.com'
email_send = 'testpython79@gmail.com'
email_pass = 'Liverpool27'
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(email_user, email_pass)
text = msg.as_string()
server.sendmail(email_user, email_send, text)
server.quit
else:
print("Auth code {} is already set for this account {} ".format(account_found[2], account_number))
conn.commit()
def get_user_code(self,account_number, acctype):
with conn:
account_found = c.execute("SELECT auth_code from auth_code WHERE account_number=:account_number",
{'account_number':account_number})
account_found = c.fetchone()
if account_found is None:
pass
# print("You need to request an authorization code first before you set your pin")
else:
return(account_found[0])
""" Set pin for an account based on the auth code entered for validation """
def set_pin(self,account_number, acctype, input_code):
with conn:
get_code = BankAccount.get_user_code(self, account_number, acctype)
if get_code is None:
pass
print("You need to request an authorization code first before you set your pin")
else:
if get_code !=input_code:
print("Authorization code not valid")
else:
pin = input("Please set your 4 digit pin: ")
if len(pin) < 4 or len(pin) >4 or len(pin) == 4 and pin.isdigit()==False:
print("This is not a 4 digit pin")
else:
print("pin accepted")
c.execute("""UPDATE {} SET pin=:pin
WHERE account_number =:account_number""".format(acctype),
{'account_number':account_number, 'pin':pin})
print("Pin for account has been updated")
""" Reset pin, pass in new pin """
def set_reset_pin(self, account_number, acctype, new_pin):
with conn:
c.execute("""UPDATE {} SET pin=:new_pin
WHERE account_number =:account_number""".format(acctype),
{'account_number':account_number, 'new_pin':new_pin})
print("Pin for account has been updated")
conn.commit()
def get_pin(self, account_number, acctype, user_pin):
with conn:
db_pin = c.execute("SELECT pin from {} WHERE account_number=:account_number".format(acctype),
{'account_number':account_number})
db_pin = c.fetchone()
if db_pin is not None:
return(db_pin[0])
else:
print("db pin is None")
pass
""" Set email notification preferences for users who have confirmed bank accounts """
""" Do an insert if no notifications record is found """
""" If there is a notifications record, update all notifications for that user """
def set_notifications(self, name, email_address, account_number, acctype, notif_bal, notif_deposits, notif_overdraft, notif_withdraw):
with conn:
""" check if an account is found first """
account_found = BankAccount.get_account(self, account_number, acctype)
""" Check if a notification record is found """
notif_found = BankAccount.get_notif(self, account_number, acctype)
if account_found and notif_found is None:
c.execute("""INSERT INTO notifications VALUES (:name, :email_address, :account_number, :acctype, :notif_bal, :notif_deposits, :notif_overdraft, :notif_withdraw)""".format(acctype),
{'name':name, 'email_address': email_address,'account_number': account_number, 'acctype':acctype, 'notif_bal':notif_bal,
'notif_deposits':notif_deposits, 'notif_overdraft':notif_overdraft, 'notif_withdraw':notif_withdraw})
print("Notifications for acc#{} has been created, acctype {} have been setup".format(account_number, acctype))
elif account_found and notif_found:
c.execute("""UPDATE notifications SET notif_bal=:notif_bal, notif_deposits=:notif_deposits, notif_overdraft=:notif_overdraft, notif_withdraw=:notif_withdraw""",
{'notif_bal':notif_bal, 'notif_deposits':notif_deposits, 'notif_overdraft':notif_overdraft, 'notif_withdraw': notif_withdraw})
print("Notificatons for acc# {} have been updated".format(account_number))
else:
print("Setup an account first then set notifications")
def get_notif(self,account_number, acctype):
with conn:
notif_exist = c.execute("""SELECT * from notifications WHERE account_number=:account_number and
account_type=:account_type""",
{'account_number':account_number, 'account_type':acctype})
notif_exist = c.fetchone()
return(notif_exist)
""" Show all rows in DB for the the account type passed in """
def get_account(self,account_number, acctype):
with conn:
account_find = c.execute("SELECT * from {} WHERE account_number=:account_number".format(acctype),
{'account_number':account_number})
account_found = c.fetchone()
if not account_found:
print("No {} matching that number could be found".format(acctype))
else:
print("Account type: {} exists!".format(acctype))
print(account_found)
return(account_found)
def get_balance(self, account_number, acctype):
with conn:
balance = c.execute("SELECT balance from {} WHERE account_number=:account_number".format(acctype),
{'account_number':account_number})
balance = c.fetchone()
print("The balance for account number: {} is ${}".format(account_number, balance[0]))
notif_set = BankAccount.get_notif(self, account_number, acctype)
if notif_set is None:
print("No notifications are set for this user")
else:
notif_balance = notif_set[4]
name = notif_set[0]
if notif_balance == 1:
notify = send_email.send_email(account_number, acctype, 'Balance', balance, balance, name)
return(balance[0])
""" Deposit funds into the account number + acctype for the account passed in """
def deposit(self, account_number, acctype, amount):
with conn:
""" Check acct exists before making deposit """
account_found = BankAccount.get_account(self, account_number, acctype)
if account_found:
existing_bal = account_found[3]
c.execute("""UPDATE {} SET balance=balance +:amount
WHERE account_number =:account_number""".format(acctype),
{'account_number':account_number, 'amount':amount})
new_bal = existing_bal + (int(amount))
print("${} has been deposited to account {} and the new balance is ${}".format(amount, account_number, existing_bal + (int(amount))))
# Check email configurations are turned on for deposits
notif_set = BankAccount.get_notif(self, account_number, acctype)
if notif_set is None:
print("No notifications are set for this user")
else:
notif_deposits = notif_set[5]
name = notif_set[0]
if notif_deposits == 1:
notify = send_email.send_email(account_number, acctype, 'Deposit', amount, new_bal, name)
""" withdraw funds from the bank account passed in """
def withdraw(self, account_number, acctype, amount):
with conn:
""" Check account exists """
account_found = BankAccount.get_account(self, account_number, acctype)
existing_bal = account_found[3]
if account_found:
c.execute("""UPDATE bank_account SET balance=balance -:amount
WHERE account_number =:account_number""",
{'account_number':account_number, 'amount':amount})
new_bal = existing_bal - (int(amount))
conn.commit()
print("${} has been withdrawn from account {} and the new balance is ${}".format(amount, account_number, existing_bal - (int(amount))))
notif_set = BankAccount.get_notif(self, account_number, acctype)
if notif_set is None:
print("No notifications have been set for this acct")
else:
notif_withdraw = notif_set[7]
name = notif_set[0]
if notif_withdraw == 1:
notify = send_email.send_email(account_number, acctype, 'Withdraw', amount, new_bal, name)
else:
print("Withdrawl notifications have been turned off")
if account_found and new_bal < 0 and notif_set is not None:
notify_o = send_email.send_email(account_number, acctype, 'Overdraft', amount, new_bal, name)
conn.commit()
</code></pre>
<p>ALL of credit card setup:</p>
<pre><code>from bank_account import BankAccount
import sqlite3
conn = sqlite3.connect('bank_account.db')
c = conn.cursor()
class CreditCard(BankAccount):
def __init__(self, name, social, account_number, balance, acctype, card_no, credit_score=None, credit_limit=None):
super().__init__(name, social, account_number, balance, acctype)
self.card_no = card_no
self.credit_score = credit_score
self.credit_limit = credit_limit
""" set credit limit, check if acct exists, then call get credit limit """
def set_credit_limit(self, account_number, acctype, credit_score):
with conn:
account_found = BankAccount.get_account(self, account_number, acctype)
if account_found:
credit_limit = CreditCard.set_credit_limit_helper(self, account_number, credit_score)
if credit_limit:
c.execute("""UPDATE credit_card SET credit_limit=:credit_limit
WHERE account_number =:account_number """,
{'account_number':account_number, 'credit_limit':credit_limit})
print("Account number {} credit limit is set to {}".format(account_number, credit_limit))
conn.commit()
def get_credit_limit(self, account_number):
with conn:
c.execute("""SELECT credit_limit from credit_card WHERE account_number=:account_number""",
{'account_number':account_number})
credit_limit = c.fetchone()
if credit_limit is None:
pass
else:
return(credit_limit[0])
""" get credit limit based on credit score passed in """
def set_credit_limit_helper(self, account_number, credit_score):
if credit_score > 700:
credit_limit = -2000
elif credit_score > 100 and credit_score <= 300:
credit_limit = -1500
else:
credit_limit = -1000
return credit_limit
if __name__ == '__main__':
obj1 = CreditCard("Juan Santos", 135063555, 5544, 100, 'credit_card', 2200330066007700)
# obj1.create_account("Juan Santos", 135063555, 9922, 100, 'credit_card', 2200330066007700)
obj1.set_credit_limit(5544, 'credit_card', 200)
# obj1.set_user_code(9922, 'credit_card', 'juan@noemail.com')
# obj1.set_pin(9922, 'credit_card', 'b4493a59')
</code></pre>
<p>ALL of credit_card:</p>
<pre><code>from bank_account import BankAccount
import sqlite3
conn = sqlite3.connect('bank_account.db')
c = conn.cursor()
class CreditCard(BankAccount):
def __init__(self, name, social, account_number, balance, acctype, card_no, credit_score=None, credit_limit=None):
super().__init__(name, social, account_number, balance, acctype)
self.card_no = card_no
self.credit_score = credit_score
self.credit_limit = credit_limit
""" set credit limit, check if acct exists, then call get credit limit """
def set_credit_limit(self, account_number, acctype, credit_score):
with conn:
account_found = BankAccount.get_account(self, account_number, acctype)
if account_found:
credit_limit = CreditCard.set_credit_limit_helper(self, account_number, credit_score)
if credit_limit:
c.execute("""UPDATE credit_card SET credit_limit=:credit_limit
WHERE account_number =:account_number """,
{'account_number':account_number, 'credit_limit':credit_limit})
print("Account number {} credit limit is set to {}".format(account_number, credit_limit))
conn.commit()
def withdraw(self, account_number, acctype, amount):
with conn:
account_found = BankAccount.get_account(self, account_number, acctype)
if account_found:
balance = account_found[3]
credit_limit = CreditCard.get_credit_limit(self, account_number)
amount_left = credit_limit - (int(balance))
if balance - (int(amount)) < credit_limit:
print("Your balance is: {}, and your credit limit is: {}".format(balance, credit_limit))
print("The max you can withdraw is {}".format(amount_left))
else:
existing_bal = account_found[3]
c.execute("""UPDATE credit_card SET balance=balance -:amount
WHERE account_number =:account_number""",
{'account_number':account_number, 'amount':amount})
print("${} has been withdrawn from account {} and the new balance is ${}".format(amount, account_number, existing_bal - (int(amount))))
notif_set = BankAccount.get_notif(self, account_number, acctype)
if notif_set is None:
print("No notifications have been set for this acct")
else:
notif_withdraw = notif_set[7]
if notif_withdraw == 1:
notify = BankAccount.send_email(self,account_number, acctype, 'Withdraw', amount, existing_bal - amount)
conn.commit()
def get_credit_limit(self, account_number):
with conn:
c.execute("""SELECT credit_limit from credit_card WHERE account_number=:account_number""",
{'account_number':account_number})
credit_limit = c.fetchone()
if credit_limit is None:
pass
else:
return(credit_limit[0])
""" get credit limit based on credit score passed in """
def set_credit_limit_helper(self, account_number, credit_score):
if credit_score > 700:
credit_limit = -2000
elif credit_score > 100 and credit_score <= 300:
credit_limit = -1500
else:
credit_limit = -1000
return credit_limit
</code></pre>
<p>Adding send email program also:</p>
<pre><code>import smtplib, sqlite3
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import bank_account
conn = sqlite3.connect('bank_account.db')
c = conn.cursor()
""" get email config - check if there is an existing acct first """
def get_email_config(account_number, acctype, action, amount, new_bal, name):
subject = '{} account {} notification'.format(acctype, action)
body = ''
acctype = acctype.replace('_',' ')
if action == 'Balance':
body = '{},\n \
The balance for account number: {} is : ${} '.format(name, account_number, amount[0])
elif action == 'Deposit':
body= '{},\n \
A deposit of: ${} has been made to account number: {}\n \
The new balance is now: ${}'.format(name, amount, account_number, new_bal)
elif action == 'Overdraft':
body = '{},\n \
Please note that account number: {} is now overdrawn \n \
The balance is ${}. Please add funds to avoid penalties'.format(name, account_number, new_bal)
elif action == 'Withdraw':
body = '{},\n \
Please note that a withdrawl in the amount of: ${} has been made from account number: {} \n \
The balance is ${}'.format(name, amount, account_number, new_bal)
return(subject, body)
def send_email( account_number, acctype, action, amount, new_bal, name):
""" Pull subject and body from email_config """
email_config = get_email_config(account_number, acctype, action, amount, new_bal, name)
body = email_config[1]
subject = email_config[0]
email_user = 'placeholder@noemail.com'
email_send = 'customerplaceholder@noemail.com'
email_pass = 'pass'
msg = MIMEMultipart()
msg['From'] = email_config[0]
msg['To'] = email_config[1]
msg['Subject'] = email_config[-2]
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(email_user, email_pass)
text = msg.as_string()
server.sendmail(email_user, email_send, text)
server.quit
if action == 'Deposit':
print("Deposit Notification sent")
elif action == 'Balance':
print("Balance Notification sent")
elif action == 'Overdraft':
print("Overdraft Notification sent")
elif action == 'Withdraw':
print("Withdraw Notification sent")
else:
pass
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T05:53:00.840",
"Id": "415554",
"Score": "1",
"body": "This code is not complete. For instance, the static class method `ATM.get_user_code()` is not defined anywhere. You are using an sqlite3 database, but no where have you shown the schema. Both of these things makes it impossible for us to run the code, so we are left wondering if we have a complete picture of the program structure. Lacking that, we really can't provide a good code review with any confidence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T14:45:27.033",
"Id": "415618",
"Score": "0",
"body": "Thought I might run out space which is why i didnt add all of the data in all the programs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:04:54.597",
"Id": "415623",
"Score": "0",
"body": "The limit on code review was [raised to 65535 characters](https://codereview.meta.stackexchange.com/a/7163/100620)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:06:58.880",
"Id": "415624",
"Score": "0",
"body": "Thanks. I added much more so people have a better idea of what it contains. Also I added the sql which created the DB, however I didnt keep it fully up to date when adding columns so there might be a slight difference here and there"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:12:05.400",
"Id": "415626",
"Score": "0",
"body": "@AJNeufield - added more detail. get_user_code does exist but I thought I might be over the limit so I didnt add"
}
] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Running this code through a linter such as <a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\">flake8</a> will give you some hints towards producing more idiomatic code. You can also use <a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\">Black</a> to automatically format your code to be more idiomatic.</li>\n<li>You don't need to assign <code>obj1</code> in <code>main</code> - the variable is unused.</li>\n<li><code>main_menu</code> taking a bunch of strings and numbers makes the call completely unintelligible on its own. If you were to instead create a <code>Customer</code> with an <code>Account</code>, <code>Identification</code> and <code>BankCard</code> instead, the meaning of the now single parameter would be obvious.</li>\n<li><code>fetchone</code> does not assert that there is only one record. You should make sure to check that whenever you use it outside of a loop you <code>assert</code> that there are no more rows after retrieving it. Otherwise you can very easily get into situations where business rules such as having only one code per card is broken.</li>\n<li>Optional parameters are a code smell. That doesn't mean they are always bad, but they are very often a sign that the code needs some <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a> love. In your case you never call <code>main_menu</code> without <code>card_no</code>, so it should not be optional.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:45:10.703",
"Id": "415632",
"Score": "0",
"body": "Thanks. Would Customer, Account, Identification and BankCard be classes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T19:18:23.347",
"Id": "415674",
"Score": "0",
"body": "Yes, hence the capitalization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T02:56:46.200",
"Id": "415720",
"Score": "0",
"body": "In that case is the customer basically replacing bank account, the superclass? Would the others be subclasses? And then taking pieces out of bank account and credit card etc, and putting these into Account, Identification etc where appropriate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T03:00:08.947",
"Id": "415721",
"Score": "0",
"body": "Also, are you saying main_menu would take one parameter or all the above main_menu(Customer, Account, Identification, BankCard)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T05:59:45.697",
"Id": "214892",
"ParentId": "214886",
"Score": "4"
}
},
{
"body": "<h1>Layers</h1>\n\n<p>Perhaps the biggest problem with this project is a lack of clear layers of responsibility. You’ve got files and classes for organization, but it is highly coupled — which is not a good thing.</p>\n\n<p>I would suggest reorganizing the code into layers:</p>\n\n<ol>\n<li>Presentation Layer: the UI. Presenting information to the user, and asking the user for information</li>\n<li>Business Logic. Checking if the correct pin/authorization code has been provided, verifying withdrawals don’t cause balances to go negative, ensuring deposits and withdrawals aren’t negative, etc.</li>\n<li>Data Model. Your <code>BankAccount</code>, and <code>CreditCard</code> goes here. They just store information. But these are “dumb” classes; little or no logic here.</li>\n<li>Data Access Layer: This is your connection to the database. You read/write <code>BankAccount</code> and <code>CreditCard</code> information here.</li>\n</ol>\n\n<p>Why?</p>\n\n<p>Presently, 6 of your 7 files import <code>sqlite3</code>. If you need to change your database to “MySQL” or “DB2”, you will need to touch almost all of your code. That is difficult and error prone. If the <code>sqlite3</code> was contained in just one file, and that was the only thing in that file, you could easily switch out the database by switching out that one file.</p>\n\n<p>Almost every file prints something too. What if you need to change your UI from console input/output to some kind of GUI, say based on <code>tkinter</code>. Again, you have to change almost every file. If the UI was separate from the business logic, data model and data access layer, it would be easy to do. As it presently stands, the entire application would change.</p>\n\n<p>Ideally, each layer would be in a different package, but that might be overkill. Simply, “these 3 files are the business logic, these 4 files are for the UI, these 3 are the data model, and this file is the data access layer” would go wonders for decoupling the application, and allowing an easier time adapting, upgrading it, or simply maintaining it.</p>\n\n<h1>Doc Strings</h1>\n\n<p>You’ve tried to add <code>\"\"\"doc-strings\"\"\"</code> to your code. I applaud the effort. But unfortunately you are doing it wrong.</p>\n\n<p>Docstrings are simply strings that appear as the first statement of a function, class, and/or module. While they can be triple-quoted or single-quoted strings, and they can use single or double quotes, what matters is they are the first statement.</p>\n\n<p>In a Python shell, type:</p>\n\n<pre><code>>>> def myfunc(a, b, c):\n... \"\"\"A cryptic function name for a function that returns\n... the geometric mean of 3 numbers.\"\"\"\n... return (a * b * c) ** (1 / 3)\n...\n</code></pre>\n\n<p>Then, ask for “help” on the function you just created:</p>\n\n<pre><code>>>> help(myfunc)\n</code></pre>\n\n<p>The <code>help</code> command looks for a doc-string attached to the function, if any, and displays that information. Try <code>help(abs)</code> or <code>help(map)</code> or <code>help(str.endswith)</code>. Useful information? Any guesses how it got there?</p>\n\n<p>You have 3 triple-quoted strings before <code>set_notifications</code>. The benefit of triple-quoted strings are they can contain new-lines. Moving the lines into the <code>set_notifications</code> function will result in just the first line becoming the doc-string. You need to start the string with a triple-quote and end it three lines later with a triple-quote in order for the entire 3 lines of text to become the doc-string.</p>\n\n<hr>\n\n<p>What is the point of <code>print(\"\"\"\"\"\"\"ATM Menu, choose an option\"\"\"\"\"\"\")</code>? The first <code>\"\"\"</code> is ended by the next <code>\"\"\"</code>, creating an empty string, then you have <code>\"ATM Menu, choose an option\"</code>, followed by <code>\"\"\"</code> and <code>\"\"\"</code> which again creates another empty string. These 3 string are concatenated together giving you simply <code>\"ATM Menu, choose an option\"</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T14:33:35.770",
"Id": "415789",
"Score": "0",
"body": "thanks for taking the time to comment. I will definitely take this into account"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T20:03:11.557",
"Id": "416551",
"Score": "0",
"body": "thanks for commenting. Is there any way you can share some more detail on how I can go about splitting my code into layers as you mentioned? I am having trouble visualizing how I am going to accomplish this. One thing I did start doing was to take get_pin set_pin etc out and put it into its own class Identification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T21:37:45.220",
"Id": "416558",
"Score": "0",
"body": "You've got several files, with typically only one class/file. One class/file is not pythonic; you end up with classes like `bank_account.BankAccount`, which you then work-around using `from bank_account import BankAccount`. You could restructure into several files, with several classes/file. One file, called `model.py` might contain several dumb, plain-old-data class structures for your various account types. Another file `database.py` could `import model` and provide your SQL queries for loading/saving the model data to the database. Another file `business.py` adds business logic, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-14T14:24:39.727",
"Id": "416644",
"Score": "0",
"body": "Ive put the classes into their own file (account.py) and then create_account, get_account etc in another file, but that second file, database.py wants the class definitions in it in order to run. I'm not sure how to pass those definitions between the two"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T03:51:30.297",
"Id": "214981",
"ParentId": "214886",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214892",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T03:10:11.503",
"Id": "214886",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"finance",
"sqlite"
],
"Title": "OOP bank account program in Python 3"
} | 214886 |
<p>I am learning Python and I wrote a script that counts how many coins you would need for an amount in dollars. I was wondering if I could make any improvements to it.</p>
<pre><code>def change():
amnt = float(input("Enter an amount in USD: "))
quarters = divmod(amnt, 0.25)
print("Quarters: ", quarters[0])
amnt = round(quarters[1], 2)
dimes = divmod(amnt, 0.10)
print("Dimes: ", dimes[0])
amnt = round(dimes[1], 2)
nickels = divmod(amnt, 0.
print("Nickels: ", nickels[0])
amnt = round(nickels[1], 2)
penny = divmod(amnt, 0.01)
print("Pennies", penny[0])
change()
</code></pre>
| [] | [
{
"body": "<p>Separate input from processing. If you want to test your method with a number of different values, you'll have to call <code>change()</code> multiple times, and enter in the value each time. Instead, change the function to accept the <code>amnt</code>, and you can call it many times passing in the amount of cash as an argument:</p>\n\n<pre><code>def change(amnt):\n # ...\n</code></pre>\n\n<p>Working with tuples from <code>divmod</code> is awkward. Python has deconstructing assignment, which will take a returned <code>tuple</code> an assign the members to separate variables:</p>\n\n<pre><code>def change(amnt):\n quarters, amnt = divmod(amnt, 0.25)\n print(\"Quarters: \", quarters)\n\n dimes, amnt = divmod(round(amnt, 2), 0.10)\n print(\"Dimes: \", dimes)\n</code></pre>\n\n<p>For the last operation, you don't use the remainder, so the \"throw-away\" variable <code>_</code> can be used for it:</p>\n\n<pre><code> pennies, _ = divmod(round(amnt, 2), 0.01)\n print(\"Pennies: \", pennies)\n</code></pre>\n\n<p>If you import this script into another program, you probably don't want the script to immediately run; rather you just want the <code>change(amnt)</code> function to be defined so this other program can call it. This is done by adding a \"guard\" at the end of the script, which only runs the code if the script is invoked directly:</p>\n\n<pre><code>if __name__ == '__main__':\n amnt = float(input(\"Enter an amount in USD: \"))\n change(amnt)\n</code></pre>\n\n<hr>\n\n<p>In addition to separating input from processing, you might want to separate the processing from the output:</p>\n\n<pre><code>def change(amnt):\n quarters, amnt = divmod(amnt, 0.25)\n dimes, amnt = divmod(amnt, 0.10)\n nickels, amnt = divmod(amnt, 0.05)\n pennies = round(amnt / 0.01, 0)\n\n return list(map(int, [quarters, dimes, nickels, pennies]))\n\nif __name__ == '__main__':\n amnt = float(input(\"Enter an amount in USD: \"))\n quarters, dimes, nickels, pennies = change(amnt)\n print(\"{} quarters, {} dimes, {} nickels, {} pennies\".format(\n quarters, dimes, nickels, pennies))\n</code></pre>\n\n<hr>\n\n<p>Despite attempts to fix rounding errors with things like <code>round(amnt,2)</code>, calling <code>change(0.85)</code> returns <code>[3, 0, 1, 5]</code>, showing that there wasn't quite enough change to make 2 nickels, but after removing 1 nickel, approximately 5 pennies remained. This is caused by floating point math.</p>\n\n<p>We can avoid these issues by switching to integer math, based on the number of pennies:</p>\n\n<pre><code>def change(amnt):\n pennies = round(amnt * 100) # Convert from dollars to pennies\n\n quarters, pennies = divmod(pennies, 25)\n dimes, pennies = divmod(pennies, 10)\n nickels, pennies = divmod(pennies, 5)\n\n return quarters, dimes, nickels, pennies\n\nif __name__ == '__main__':\n amnt = float(input(\"Enter an amount in USD: \"))\n quarters, dimes, nickels, pennies = change(amnt)\n print(\"{} quarters, {} dimes, {} nickels, {} pennies\".format(\n quarters, dimes, nickels, pennies))\n</code></pre>\n\n<p>As mentioned in the comments by @Ilmari, <code>round(...)</code> with only a single argument will round the value to the nearest whole number and return an <strong>integer</strong> value. When integer values are used with <code>divmod</code>, results are also integers, so switching from dollars-and-cents to integer pennies eliminates the ugly rounding issues.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T06:17:34.197",
"Id": "415558",
"Score": "0",
"body": "+1 for everything except your non-PEP8 formatting, even though it does look nice here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:33:44.197",
"Id": "415578",
"Score": "1",
"body": "It might be worth noting that the behavior of single-argument `round()` autoconverting floats to ints is specific to Python 3. In Python 2, you'd need to explicitly write `pennies = int(round(amnt * 100))` if you want the results to be ints. (Of course, using an explicit `int()` here is OK in Python 3 too, just redundant.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T04:25:53.013",
"Id": "214891",
"ParentId": "214888",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "214891",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T03:56:17.020",
"Id": "214888",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"change-making-problem"
],
"Title": "Script that counts quarters, dimes, nickels, and pennies"
} | 214888 |
<p>I am working through <a href="https://projecteuler.net/problem=14" rel="nofollow noreferrer">this</a> problem on project euler.</p>
<p>Basic purpose of the code:</p>
<pre><code>/*
if n is even n -> n/2
if n is odd n -> 3n + 1
which starting number under 1 million produces the longest sequence?
*/
</code></pre>
<p>The trouble with the code is that when I implement concurrency as I have, the program runs considerably more slowly than when I am just returning values directly from the <code>get_seq_len</code> function. Am I implementing concurrency incorrectly? Or is the program just not complex enough that there is speed to be gained from concurrency or something?</p>
<pre><code>package main
import ("fmt";"math";"time")
</code></pre>
<p>This function takes a number <code>x</code> and then using the formula described in the above comment block creates a sequence of numbers from it until the number 1 is reached. Originally I had the function simply returning the length of the sequence, but now I have it sending the length to the specified channel.</p>
<pre><code>func get_seq_len(x int, c chan int) {
var count int = 1
for {
if x == 1 {
break
} else if x%2 == 0 {
x = x / 2
} else {
x = 3 * x + 1
}
count++
}
// return count + 1
c <- count + 1
}
</code></pre>
<p>Here the main function just step through every number from 1 to whatever the <code>max</code> is and then tests the length of the sequence for that number. I use channel <code>c</code> to pass the sequenced length back to <code>main()</code>.</p>
<pre><code>func main() {
start := time.Now()
var max int = int(math.Pow(10,6))
// var max int = int(math.Pow(3,3))
var max_length int = 0
var max_num int = 0
c := make(chan int, 50)
for i:=1; i<max; i++ {
// length := get_seq_len(i, c)
go get_seq_len(i, c)
length := <-c
if length > max_length { max_length = length; max_num = i }
}
fmt.Println(max_num)
t := time.Now()
elapsed := t.Sub(start)
fmt.Println(elapsed)
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>Longest Collatz sequence</p>\n \n <p><a href=\"https://projecteuler.net/problem=14\" rel=\"nofollow noreferrer\">Problem 14</a></p>\n \n <p>The following iterative sequence is defined for the set of positive\n integers:</p>\n\n<pre><code>n → n/2 (n is even)\nn → 3n + 1 (n is odd)\n</code></pre>\n \n <p>Although it has not been proved yet (Collatz Problem), it is thought\n that all starting numbers finish at 1.</p>\n \n <p>Which starting number, under one million, produces the longest chain?</p>\n</blockquote>\n\n<hr>\n\n<p>In Go, the testing package includes a benchmark facility. Therefore, if we are concerned about performance, as we often are, we start with a simple implementation and benchmark it. Starting number 837799 produces the longest chain of 525 elements. When I ran a Go benchmark, it took 231,949,902 nanoseconds, about one-quarter of a second.</p>\n\n<pre><code>BenchmarkEuler14-8 5 231949902 ns/op 0 B/op 0 allocs/op\n</code></pre>\n\n<p><code>euler14a_test.go</code>:</p>\n\n<pre><code>package main\n\nimport \"testing\"\n\nfunc lenChain(n int) int {\n c := 1\n for ; n > 1; c++ {\n if n&1 == 0 {\n n >>= 1\n } else {\n n += n<<1 + 1\n }\n }\n return c\n}\n\nfunc euler14() (maxn, maxc int) {\n maxs := 1000000 - 1\n for n := 1; n <= maxs; n++ {\n c := lenChain(n)\n if maxc < c {\n maxn = n\n maxc = c\n }\n }\n return maxn, maxc\n}\n\nfunc BenchmarkEuler14(b *testing.B) {\n for N := 0; N < b.N; N++ {\n euler14()\n }\n}\n</code></pre>\n\n<p>If you you want it to be faster, perhaps we could remember some intermediate results. When I ran a Go benchmark, it took 16.979.849 nanoseconds, about than one-sixtieth of a second.</p>\n\n<pre><code>BenchmarkEuler14-8 100 16979849 ns/op 4005900 B/op 1 allocs/op\n</code></pre>\n\n<p><code>euler14b_test.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"testing\"\n)\n\nfunc lenChain(n int, a []int) int {\n if n < 1 {\n return 0\n }\n\n c := 1\n for m := n; m > 1; {\n if m < len(a) && a[m] > 0 {\n c += a[m] - 1\n break\n }\n\n if m&1 == 1 {\n // m is odd:\n // m = 3*m + 1\n m += m<<1 + 1\n c++\n }\n // m is even:\n // m = m/2\n m >>= 1\n c++\n }\n\n if n < len(a) && a[n] < c {\n a[n] = c\n }\n\n return c\n}\n\nfunc euler14() (maxn, maxc int) {\n maxs := 1000000 - 1\n a := make([]int, maxs/2)\n for n := 1; n <= maxs; n++ {\n c := lenChain(n, a)\n if maxc < c {\n maxn = n\n maxc = c\n }\n }\n return maxn, maxc\n}\n\nfunc BenchmarkEuler14(b *testing.B) {\n for N := 0; N < b.N; N++ {\n euler14()\n }\n}\n</code></pre>\n\n<p>When I ran your \"concurrent\" program, using eight threads, it took 639,898,032 nanoseconds, about two-thirds of a second.</p>\n\n<hr>\n\n<p>Some real-world code review questions: What is concurrency? What is parallelism? What do you expect to accomplish? What is your plan?</p>\n\n<p>In your earlier Go performance question, <a href=\"https://codereview.stackexchange.com/questions/212039\">Finding all prime numbers within a range</a>, I pointed ot the importance of benchmarking and algorithms.</p>\n\n<p>You only timed your program. You did not run Go benchmarks. You have no detail. You only used one simple algorithm. My benchmarks allowed me to peer into my code, often line by line. My code, using an optimized memoization algorithm, runs around nearly forty times faster than your concurrent code.</p>\n\n<p>Efficient solutions to the problem exhibit little concurrency and little parallelism. Using concurrency tools adds overhead without any corresponding benefit.</p>\n\n<hr>\n\n<blockquote>\n <p>Comment:\n You compute a lot of intermediate values in the sequence, yet only\n cache the first (being m). I'd imagine your solution would be a lot\n faster if you made a second pass in lenChain that filled all the\n misses into a. If you bite the bullet with function call overhead for\n a recursive implementation, this change would even be trivial. –\n <a href=\"https://codereview.stackexchange.com/users/190319/dillon-davis\">Dillon Davis</a></p>\n</blockquote>\n\n<hr>\n\n<p>When I ran benchmarks, your idea, despite using more memory, was slower: 22,234,021 versus 16.979.849 nanoseconds.</p>\n\n<pre><code>euler14c_test.go:\nBenchmarkEuler14-8 50 22234021 ns/op 8003587 B/op 1 allocs/op\n\neuler14b_test.go:\nBenchmarkEuler14-8 100 16979849 ns/op 4005900 B/op 1 allocs/op\n</code></pre>\n\n<p><code>euler14c_test.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"testing\"\n)\n\nfunc lenChain(n int, a []int) int {\n if n <= 1 {\n if n != 1 {\n return 0\n }\n\n c := 1\n if n < len(a) {\n if a[n] == 0 {\n a[n] = c\n }\n }\n return c\n }\n\n if n < len(a) {\n if a[n] > 0 {\n return a[n]\n }\n }\n\n m := n\n if m&1 == 0 {\n // m is even:\n // m = m/2\n m >>= 1\n } else {\n // m is odd:\n // m = 3*m + 1\n m += m<<1 + 1\n }\n c := 1 + lenChain(m, a)\n\n if n < len(a) {\n a[n] = c\n }\n\n return c\n}\n\nfunc euler14() (maxn, maxc int) {\n maxs := 1000000 - 1\n a := make([]int, maxs+1)\n\n for n := 1; n <= maxs; n++ {\n c := lenChain(n, a)\n if maxc < c {\n maxn = n\n maxc = c\n }\n }\n\n return maxn, maxc\n}\n\nfunc BenchmarkEuler14(b *testing.B) {\n for N := 0; N < b.N; N++ {\n euler14()\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T05:07:52.297",
"Id": "415724",
"Score": "0",
"body": "You compute a lot of intermediate values in the sequence, yet only cache the first (being `m`). I'd imagine your solution would be a lot faster if you made a second pass in `lenChain` that filled all the misses into `a`. If you bite the bullet with function call overhead for a recursive implementation, this change would even be trivial."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T01:41:19.520",
"Id": "415955",
"Score": "0",
"body": "Thanks for the followup. That's interesting that it actually took *longer*. I could understand if may it took a negligible about less time due to memory fetching bottlenecks, but to actually be slower is surprising. I guess function call overhead + writing to more memory addresses offset any gains from caching these values."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T00:00:08.180",
"Id": "214974",
"ParentId": "214889",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T03:58:34.587",
"Id": "214889",
"Score": "0",
"Tags": [
"performance",
"programming-challenge",
"go",
"concurrency",
"collatz-sequence"
],
"Title": "Finding the longest Collatz sequence using Go, concurrently"
} | 214889 |
<p>Am making a pure .net library with helper functions (<a href="https://github.com/billywatsy/Avo/blob/master/Avo/Avo/Extension_Number.cs" rel="nofollow noreferrer">GitHub</a>).</p>
<p>However I wanted to have a thousand separator for all number types and here is what I am currently doing </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Avo
{
public static class Extension_Number
{
#region ThousandSeparator
public static string ToThousandSeparator(this decimal value, int numberOfDecimalPlaces)
{
if (numberOfDecimalPlaces < 0) numberOfDecimalPlaces = 0;
return string.Format("{0:N" + numberOfDecimalPlaces + "}", value).ToString();
}
public static string ToThousandSeparator(this int value, int numberOfDecimalPlaces)
{
if (numberOfDecimalPlaces < 0) numberOfDecimalPlaces = 0;
return string.Format("{0:N" + numberOfDecimalPlaces + "}", value).ToString();
}
public static string ToThousandSeparator(this double value, int numberOfDecimalPlaces)
{
if (numberOfDecimalPlaces < 0) numberOfDecimalPlaces = 0;
return string.Format("{0:N" + numberOfDecimalPlaces + "}", value).ToString();
}
public static string ToThousandSeparator(this long value, int numberOfDecimalPlaces)
{
if (numberOfDecimalPlaces < 0) numberOfDecimalPlaces = 0;
return string.Format("{0:N" + numberOfDecimalPlaces + "}", value).ToString();
}
#endregion
}
}
</code></pre>
<p>As you can see above , </p>
<p>l have to repeat the same for
int , decimal , long </p>
<p>l can achieve the results l want but is it best</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Avo
{
class Program
{
static void Main(string[] args)
{
decimal tes = 294944.8484827M;
int iint = 34;
Console.WriteLine(tes.ToThousandSeparator(3));
Console.WriteLine(iint.ToThousandSeparator(2));
Console.ReadKey();
}
}
}
</code></pre>
<p>but is there an eloquent way of doing it , but allowing number types only.</p>
| [] | [
{
"body": "<p>There is no common base type for numeric types, unfortunately.</p>\n\n<p>You could still reduce the repetitiveness of your code though, by encapsulating the common structure in a single function:</p>\n\n<pre><code> private static string AddThousandsSeparator(Object numeric, int numberOfDecimalPlaces)\n {\n // note this would crash when passed a non-numeric object.\n // that's why it's private, and it's the class's responsibility\n // to limit the entry points to this function to numeric types only\n return String.Format(\"{0:N\" + Math.Max(0, numberOfDecimalPlaces) + \"}\", numeric);\n }\n\n public static string WithThousandsSeparator(this decimal value, int numberOfDecimalPlaces)\n {\n return AddThousandsSeparator(value, numberOfDecimalPlaces);\n }\n\n public static string WithThousandsSeparator(this int value, int numberOfDecimalPlaces)\n {\n return AddThousandsSeparator(value, numberOfDecimalPlaces);\n }\n\n public static string WithThousandsSeparator(this double value, int numberOfDecimalPlaces)\n {\n return AddThousandsSeparator(value, numberOfDecimalPlaces);\n }\n\n public static string WithThousandsSeparator(this long value, int numberOfDecimalPlaces)\n {\n return AddThousandsSeparator(value, numberOfDecimalPlaces);\n }\n</code></pre>\n\n<p>A few side remarks:</p>\n\n<ul>\n<li><p>There is no point in calling <code>ToString()</code> on the result of <code>String.Format</code>. <code>String.Format</code> already returns a <code>string</code>.</p></li>\n<li><p><code>Math.Max</code> is a more concise alternative for the conditional reassignment. (For what it's worth, Kotlin provides readable extension functions as syntax sugar for this sort of thing, eg. <code>someNumber.coerceAtLeast(0)</code> - trivially easy to reimplement them in C# for readability).</p></li>\n<li><p>I also corrected the naming slightly. It's \"thousands\" separator (plural), plus I think <code>With...</code> makes it clearer what the function does. The <code>ToSomething</code> phrase conventionally means a value is getting converted to Something, as if you were converting the number <em>to the thousands separator itself</em> - obviously nonsensical - rather than just adding it to the formatting.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T11:31:19.977",
"Id": "415591",
"Score": "1",
"body": "making AddThousandsSeparator private is nice and the other types public , thus make change to a single function applies to all , thanks for that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T11:36:26.240",
"Id": "415592",
"Score": "0",
"body": "Sure thing, happy to be of help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T11:46:52.053",
"Id": "415593",
"Score": "2",
"body": "You can slightly _optimize_ it by making the `Object` parameter an `IFormattable`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:35:42.140",
"Id": "415603",
"Score": "0",
"body": "That's a valid remark (well, it's been a while since I coded in C# day to day), although instinctively I feel that the more specific the parameter type, the more of a false sense of type security it projects. It's a tradeoff of sorts."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T10:56:08.913",
"Id": "214909",
"ParentId": "214900",
"Score": "4"
}
},
{
"body": "<p>I would definitely go with t3chb0t and replace <code>Object</code> with <code>IFormattable</code> in Konrads answer. Further you could provide default values to <code>numberOfDecimalPlaces</code> of your own choice and maybe the possibility to provide a <code>FormatProvider</code> which defaults to <code>CultureInfo.CurrentCulture</code>:</p>\n\n<pre><code> public static class Extension_Number\n {\n private static string Format(this IFormattable value, int decimalPlaces, IFormatProvider formatProvider = null) => value.ToString($\"N{Math.Max(0, decimalPlaces)}\", formatProvider ?? CultureInfo.CurrentCulture);\n\n public static string ToThousandSeparator(this decimal value, int numberOfDecimalPlaces = 2, IFormatProvider formatProvider = null)\n {\n return value.Format(numberOfDecimalPlaces, formatProvider);\n }\n public static string ToThousandSeparator(this int value, int numberOfDecimalPlaces = 0, IFormatProvider formatProvider = null)\n {\n return value.Format(numberOfDecimalPlaces, formatProvider);\n }\n public static string ToThousandSeparator(this double value, int numberOfDecimalPlaces = 6, IFormatProvider formatProvider = null)\n {\n return value.Format(numberOfDecimalPlaces, formatProvider);\n }\n public static string ToThousandSeparator(this long value, int numberOfDecimalPlaces = 0, IFormatProvider formatProvider = null)\n {\n return value.Format(numberOfDecimalPlaces, formatProvider);\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:46:37.550",
"Id": "214924",
"ParentId": "214900",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "214909",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T09:19:32.107",
"Id": "214900",
"Score": "3",
"Tags": [
"c#",
"formatting",
"integer",
"floating-point",
"fixed-point"
],
"Title": "Adding thousand separator to various number types"
} | 214900 |
<p>I'm refactoring my <a href="https://codereview.stackexchange.com/questions/192103/scheduler-built-with-observables-v2-follow-up">scheduler</a> and for one of its triggers I need an endless counter that would automatically restart. Since this is a simple and very common task I don't want to <em>ever</em> have to implement it again so I encapsulated it in such a way that it hopefully can be reused <em>everywhere</em> else.</p>
<hr>
<p>The counter is represented by an enumerable interface with a couple or properties that provide information about the counter and methods allowing to interact with it.</p>
<pre><code>public interface IInfiniteCounter : IEnumerable<(int Value, InfiniteCounterState State)>
{
int Min { get; }
int Max { get; }
int Length { get; }
int Current { get; }
(int Value, InfiniteCounterState State) Next();
void Reset();
}
</code></pre>
<p>It uses an <code>enum</code> to inform the caller about the type of the value. It returns <code>First</code> each time the counter restarted, <code>Intermediate</code> for values inbetween and <code>Last</code> for the last value.</p>
<pre><code>public enum InfiniteCounterState
{
First,
Intermediate,
Last,
}
</code></pre>
<hr>
<p>I have one implementation of the interface. The <code>InfiniteCounter</code> that is a forward running counter:</p>
<pre><code>public class InfiniteCounter : IInfiniteCounter
{
private int _current;
public InfiniteCounter(int min, int max)
{
Min = min;
Max = max;
}
public InfiniteCounter(int max) : this(0, max) { }
public int Min { get; }
public int Max { get; }
public int Length => Max - Min;
public int Current => _current + Min;
private bool IsLast => _current == Length;
public (int Value, InfiniteCounterState State) Next()
{
if (IsLast)
{
Reset();
}
return
(
Current,
_current++ == 0
? InfiniteCounterState.First
: IsLast
? InfiniteCounterState.Last
: InfiniteCounterState.Intermediate
);
}
public void Reset()
{
_current = 0;
}
public IEnumerator<(int Value, InfiniteCounterState State)> GetEnumerator()
{
while (true)
{
yield return Next();
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
</code></pre>
<p>In order to have it running backwards I created two extensions. One that is an extension for the <code>IInfiniteCounter</code></p>
<pre><code>public static class InfiniteCounterExtensions
{
public static IEnumerable<(int Value, InfiniteCounterState State)> Countdown(this IInfiniteCounter counter)
{
return counter.Select(x => (x.Value.Flip(counter.Min, counter.Max), x.State));
}
}
</code></pre>
<p>and one that is flipping the value:</p>
<pre><code>public static class IndexMath
{
public static int Flip(this int value, int min, int max)
{
return (-(value - max + 1) % (max - min)) + min;
}
}
</code></pre>
<p>Examples:</p>
<pre><code>void Main()
{
var take = 4;
new InfiniteCounter(3).Take(take).Dump("0-2");
new InfiniteCounter(3).Countdown().Take(take).Dump("2-0");
new InfiniteCounter(2, 5).Take(take).Dump("2-4");
new InfiniteCounter(2, 5).Countdown().Take(take).Dump("4-2");
0.Flip(0, 3).Dump();
1.Flip(0, 3).Dump();
}
</code></pre>
<hr>
<p>What do you think about it? It should be convenient to use and every piece of it should be testable. <em>(Argument checking will be added later)</em></p>
| [] | [
{
"body": "<blockquote>\n<pre><code>public interface IInfiniteCounter : IEnumerable<(int Value, InfiniteCounterState State)>\n</code></pre>\n</blockquote>\n\n<p>vs</p>\n\n<blockquote>\n<pre><code> int Current { get; }\n\n (int Value, InfiniteCounterState State) Next();\n\n void Reset();\n</code></pre>\n</blockquote>\n\n<p>The interface itself looks a lot more like <code>IEnumerator<></code> than <code>IEnumerable<></code>, so IMO implementing <code>IEnumerable<></code> is misleading and dangerous. The docs for <code>IEnumerable<></code> don't say either way whether or not it's possible to have two active enumerators at the same time, but I can't think of any implementations in the standard library for which it isn't possible, and I've probably written a lot of code which assumes that it is possible.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> int Min { get; }\n\n int Max { get; }\n\n int Length { get; }\n</code></pre>\n</blockquote>\n\n<p>I can safely assume that <code>Min</code> is inclusive, but I absolutely need a comment to tell me whether <code>Max</code> is or not, and it would be helpful to have a comment indicating the standard implementation of <code>Length</code>. Also, should <code>Length</code> be <code>uint</code> both because it's guaranteed to be non-negative and to avoid overflow in edge cases?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public static class IndexMath\n{\n public static int Flip(this int value, int min, int max)\n {\n return (-(value - max + 1) % (max - min)) + min;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>I don't understand why this method uses <code>%</code>. For me the obvious interpretation of the name (and the use case) is <code>max - (value - min)</code>. If there's some trickery going on to avoid or handle overflow, it needs explanatory comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:35:29.200",
"Id": "415602",
"Score": "0",
"body": "This is an interesting point with the enumerator thing... it's hard to decide which one it actually should be... I think it should be cleaner if `Next` wasn't part of the interface... oops, or not, I need this because it's not running in a loop but will be called by the scheduler on each tick... You're right, the `%` should fix the overflow of the `value`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:30:27.403",
"Id": "214913",
"ParentId": "214908",
"Score": "3"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/214913/59161\">@Peter Taylor</a> is right. It was some strange enumerable/enumerator hybrid so I have turned it into a real <code>IEnumerator<T></code> of itself because I think is makes it easier to use in various scenarios.</p>\n\n<p>If I now want to have an <code>IEnumerable</code> I can use the new <code>AsEnumerable</code> extension and if I want to have a countdown then I can flip the value with new <code>ValueAsCountdown()</code> extension. The <code>State</code> has become <code>Position</code>.</p>\n\n<p>It hasn't changed much but here's the full code (that I still need to document... later):</p>\n\n<pre><code>public interface IInfiniteCounter : IEnumerator<IInfiniteCounter>\n{\n /// <summary>\n /// Gets the min value of the counter.\n /// </summary>\n int Min { get; }\n\n /// <summary>\n /// Gets the max exclusive value of the counter.\n /// </summary>\n int Max { get; }\n\n /// <summary>\n /// Gets the total length of the counter.\n /// </summary>\n int Length { get; }\n\n /// <summary>\n /// Gets the current value of the counter.\n /// </summary>\n int Value { get; }\n\n /// <summary>\n /// Gets the relative position of the counter between min and max.\n /// </summary>\n InfiniteCounterPosition Position { get; }\n}\n\npublic class InfiniteCounter : IInfiniteCounter\n{\n private int _value;\n\n public InfiniteCounter(int min, int max)\n {\n Min = min;\n Max = max;\n Reset();\n }\n\n public InfiniteCounter(int max) : this(0, max) { }\n\n public int Min { get; }\n\n public int Max { get; }\n\n public int Length => Max - Min;\n\n public int Value => _value + Min;\n\n IInfiniteCounter IEnumerator<IInfiniteCounter>.Current => this;\n\n object IEnumerator.Current => this;\n\n public InfiniteCounterPosition Position =>\n _value == 0\n ? InfiniteCounterPosition.First\n : _value == Length - 1\n ? InfiniteCounterPosition.Last\n : InfiniteCounterPosition.Intermediate;\n\n public bool MoveNext()\n {\n if (Position == InfiniteCounterPosition.Last)\n {\n Reset();\n }\n\n _value++;\n\n return true;\n }\n\n public void Reset()\n {\n _value = -1;\n }\n\n public void Dispose()\n {\n // There is nothing to dispose.\n }\n}\n\npublic static class IndexMath\n{\n public static int Flip(this int value, int min, int max)\n {\n return (-(value - max + 1) % (max - min)) + min;\n }\n}\n\npublic static class InfiniteCounterExtensions\n{\n public static IEnumerable<IInfiniteCounter> AsEnumerable(this IEnumerator<IInfiniteCounter> counter)\n {\n while (counter.MoveNext())\n {\n yield return counter.Current;\n }\n }\n\n public static int ValueAsCountdown(this IInfiniteCounter counter)\n {\n return counter.Value.Flip(counter.Min, counter.Max);\n }\n}\n\npublic enum InfiniteCounterPosition\n{\n First,\n Intermediate,\n Last,\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T00:05:30.330",
"Id": "415848",
"Score": "0",
"body": "I have small issue with InfiniteCounterPosition. I guess you intend to have a proper range, and not have Min=Max, in which case a given position could be both the First and Last."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-09T09:11:15.647",
"Id": "415875",
"Score": "0",
"body": "@RickDavin good point, I was thinking about restricting the _length_ to at least two elements. Otherwise it doesn't make sense to use it at all ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T16:20:52.103",
"Id": "215042",
"ParentId": "214908",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214913",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T10:44:31.550",
"Id": "214908",
"Score": "3",
"Tags": [
"c#",
"iterator",
"interface"
],
"Title": "Infinite and countdown counters"
} | 214908 |
<p>I have this method rated B on Scrutinizer (direct link: <a href="https://scrutinizer-ci.com/g/sineverba/domotic-panel/inspections/76996c9f-543f-43b4-9475-c64fe810a278/code-structure/operation/App%5CHttp%5CControllers%5CApi%5CPublicIpController%3A%3Aupdate" rel="nofollow noreferrer">https://scrutinizer-ci.com/g/sineverba/domotic-panel/inspections/76996c9f-543f-43b4-9475-c64fe810a278/code-structure/operation/App%5CHttp%5CControllers%5CApi%5CPublicIpController%3A%3Aupdate</a>)</p>
<pre><code>public function update()
{
try {
$data = array();
$update = false;
$string_previous_public_ip = null;
$current_public_ip = $this->getGateway()->fetchPublicIp($this->getIp());
$previous_public_ip = $this->getGateway()->getLastRecord();
$data[ 'ip_address' ] = $current_public_ip;
if (isset($previous_public_ip->ip_address)) {
$string_previous_public_ip = $previous_public_ip->ip_address;
$data[ 'id' ] = $previous_public_ip->id;
}
if ($current_public_ip != $string_previous_public_ip) {
$update = $this->updateOrCreate($data);
}
return response()->json([
'updated' => $update
], 200);
} catch (ConnectionError $e) {
// Will return error 500
} catch (ServiceError $e) {
// Will return error 500
} catch (\Exception $e) {
// Will return error 500
}
return response()->json([
'updated' => $update
], 500);
}
</code></pre>
<p>Can I lower the cyclomatic complexity? I did move yet a <code>if/else</code> for the update (<code>updateOrCreate</code> method I think it is clear his work), but it is not sufficient.</p>
<p>Thank you!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:51:07.440",
"Id": "415606",
"Score": "0",
"body": "Can you post a screenshot of the messaging from Scrutenizer in your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:10:15.150",
"Id": "415609",
"Score": "0",
"body": "@JohnConde I did add a direct link to Scrutinizer..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:29:28.590",
"Id": "415611",
"Score": "3",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] | [
{
"body": "<p>Your three <code>catch</code> blocks and two <code>return</code>s do the same thing as each other. You only need one of each.</p>\n\n<p><code>$update</code> is referenced outside of <code>try</code>, should be defined there too.</p>\n\n<p><code>$current_public_ip</code> is just another name for <code>$data[ 'ip_address' ]</code>. It's not any shorter or clearer and doesn't resemble its other name very closely.</p>\n\n<p><code>$previous_public_ip</code> isn't an IP address, it's an object that contains an IP address and other stuff. It would be clearer to simply name it <code>$previous</code>, which lets you drop the redundant <code>string_</code> from <code>$string_previous_public_ip</code>. <code>_public</code> can go too.</p>\n\n<pre><code>public function update()\n{\n $update = false;\n $status = 500; // default\n try {\n $data = array();\n $previous_ip = null;\n $data[ 'ip_address' ] = $this->getGateway()->fetchPublicIp($this->getIp());\n $previous = $this->getGateway()->getLastRecord();\n if ( isset($previous->ip_address) ) {\n $previous_ip = $previous->ip_address;\n $data[ 'id' ] = $previous->id;\n }\n if ( $data[ 'ip_address' ] != $previous_ip ) {\n $update = $this->updateOrCreate($data);\n }\n $status = 200;\n } catch ( \\Exception $e ) {\n // return default status (500)\n }\n return response()->json([ 'updated' => $update ], $status);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T14:00:26.003",
"Id": "214925",
"ParentId": "214914",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214925",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:45:58.113",
"Id": "214914",
"Score": "0",
"Tags": [
"php",
"cyclomatic-complexity"
],
"Title": "Php: how to lower complexity of method"
} | 214914 |
<p>Kata: <a href="https://www.codewars.com/kata/find-the-unknown-digit/train/python" rel="nofollow noreferrer">https://www.codewars.com/kata/find-the-unknown-digit/train/python</a> </p>
<blockquote>
<p>To give credit where credit is due: This problem was taken from the ACMICPC-Northwest Regional Programming Contest. Thank you problem writers.</p>
<p>You are helping an archaeologist decipher some runes. He knows that this ancient society used a Base 10 system, and that they never start a number with a leading zero. He's figured out most of the digits as well as a few operators, but he needs your help to figure out the rest.</p>
<p>The professor will give you a simple math expression, of the form</p>
<pre><code>[number][op][number]=[number]
</code></pre>
<p>He has converted all of the runes he knows into digits. The only operators he knows are addition (+),subtraction(-), and multiplication (*), so those are the only ones that will appear. Each number will be in the range from -1000000 to 1000000, and will consist of only the digits 0-9, possibly a leading -, and maybe a few ?s. If there are ?s in an expression, they represent a digit rune that the professor doesn't know (never an operator, and never a leading -). All of the ?s in an expression will represent the same digit (0-9), and it won't be one of the other given digits in the expression. No number will begin with a 0 unless the number itself is 0, therefore 00 would not be a valid number.</p>
<p>Given an expression, figure out the value of the rune represented by the question mark. If more than one digit works, give the lowest one. If no digit works, well, that's bad news for the professor - it means that he's got some of his runes wrong. output -1 in that case.</p>
<p>Complete the method to solve the expression to find the value of the unknown rune. The method takes a string as a paramater repressenting the expression and will return an int value representing the unknown rune or -1 if no such rune exists. </p>
<hr>
</blockquote>
<h2>My Solution</h2>
<pre class="lang-py prettyprint-override"><code>import re, operator as op
parse_op = re.compile(r"(-?[0-9?]+)([-+*])(-?[0-9?]+)(=)(-?[0-9?]+)") #For parsing the LHS.
ops = {"*": op.mul, "+": op.add, "-": op.sub}
def solve_runes(s):
search = set("0123456789") - set(c for c in s if c.isnumeric())
n = [0]*3
n[0], op, n[1], x, n[2] = parse_op.search(s).groups()
if any(len(x) > 1 and x[0] == "?" for x in n):
search -= {"0"}
for digit in sorted(search):
v = [int(x.replace("?", digit)) for x in n]
if ops[op](v[0], v[1]) == v[2]:
return int(digit)
return -1
</code></pre>
<h2>Sample Test Case</h2>
<pre class="lang-py prettyprint-override"><code>test.assert_equals(solve_runes("1+1=?"), 2, "Answer for expression '1+1=?' ")
test.assert_equals(solve_runes("123*45?=5?088"), 6, "Answer for expression '123*45?=5?088' ")
test.assert_equals(solve_runes("-5?*-1=5?"), 0, "Answer for expression '-5?*-1=5?' ")
test.assert_equals(solve_runes("19--45=5?"), -1, "Answer for expression '19--45=5?' ")
test.assert_equals(solve_runes("??*??=302?"), 5, "Answer for expression '??*??=302?' ")
test.assert_equals(solve_runes("?*11=??"), 2, "Answer for expression '?*11=??' ")
test.assert_equals(solve_runes("??*1=??"), 2, "Answer for expression '?*11=??' ")
</code></pre>
| [] | [
{
"body": "<p>In this code, I find it misleading that <code>n</code> is first assigned zeros,\nand then its content is replaced with strings.</p>\n\n<blockquote>\n<pre><code>n = [0]*3\nn[0], op, n[1], x, n[2] = parse_op.search(s).groups()\n</code></pre>\n</blockquote>\n\n<p>I think it would be more clear this way:</p>\n\n<pre><code>num1, op, num2, _, num3 = parse_op.search(s).groups()\nnums = [num1, num2, num3]\n</code></pre>\n\n<p>Notice that I replaced <code>x</code> with <code>_</code>. It's a common convention when a variable is unused.</p>\n\n<p>Some doctests with example inputs and expected outputs would be great too,\nmaking the code easier to digest, and play with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T02:04:14.577",
"Id": "415716",
"Score": "0",
"body": "I'll add the sample tests from the provided kata."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T18:20:33.117",
"Id": "214941",
"ParentId": "214915",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214941",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T12:46:14.853",
"Id": "214915",
"Score": "2",
"Tags": [
"python",
"beginner",
"strings",
"programming-challenge",
"parsing"
],
"Title": "(Codewars): Find the Unknown Digit"
} | 214915 |
<p>I'm currently learning some javascript and I've been getting up to scratch with ES6. I have learned the basics and continued to build things that I've wanted to build in Javascript for a long time.</p>
<p>I am looking for someone to review the code, and to hopefully aid me in becoming a better developer in learning from mistakes.</p>
<p>So the image slider is working from an array which is a div with 4 hidden img elements. The is an img element which is being created within the div #image-display id. The JS then swaps the src attribute based off the number within the counter and the key from the array.</p>
<p>The working copy is on codepen: <a href="https://codepen.io/syncoed/pen/WmpEQJ" rel="nofollow noreferrer">https://codepen.io/syncoed/pen/WmpEQJ</a></p>
<p><strong>HTML</strong>
</p>
<pre><code> <div id="image-display" class="mx-auto">
<span id="left">&#10096;</span>
<span id="right">&#10097;</span>
</div>
<div id="img-container">
<img id="img-size" src="../image-slider/img/image1.jpg" hidden/>
<img id="img-size" src="../image-slider/img/image2.jpg" hidden/>
<img id="img-size" src="../image-slider/img/image3.jpg" hidden/>
<img id="img-size" src="../image-slider/img/image4.jpg" hidden/>
</div>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code> #image-display{
width:500px;
height: 100%;
border: 3px solid orange;
z-index: -1;
padding:3;
margin:0;
}
#img-size{
height:100%;
width:100%;
z-index: -1;
margin:0;
position: relative;
}
/* left arrow */
#left{
z-index: 0;
position: fixed;
left:21.5%;
top:10%;
cursor: pointer;
color:#ffffff;
padding:0;
}
/* right arrow */
#right{
z-index: 0;
position: fixed;
right:53.5%;
top: 10%;
cursor: pointer;
color:#ffffff;
padding:0;
}
/*Desktop Media Queries*/
@media(min-width: 1573px) {
#right{
right:35%;
top: 12%;
}
#left{
left:35.5%;
top:12%;
}
}
@media(min-width: 1613px) {
#right{
right:35.5%;
top: 11%;
}
#left{
left:35.5%;
top:11%;
}
}
@media(min-width: 1140px) {
#right{
right:37.5%;
top: 11%;
}
#left{
left:37.5%;
top:11%;
}
}
</code></pre>
<p><strong>Javascript</strong></p>
<pre><code> const imgDisplay = document.querySelector('#image-display');
const allImages = document.querySelector('#img-container');
//gets all images
let all = allImages.querySelectorAll('img');
var imageContainer = document.querySelector('.selector');
let counter = 0;
var newImg = document.createElement('img');
newImg.setAttribute('id', 'img-size');
newImg.setAttribute('src', all[0].src);
imgDisplay.appendChild(newImg);
let imageSelected = all[counter];
imgDisplay.addEventListener('click', (e) => {
if (counter == all.length - 1 && e.target.id == "right") {
newImg.setAttribute('src', all[0].src);
counter = 0;
} else if (counter == 0 && e.target.id == 'left') {
counter = all.length - 1;
newImg.setAttribute('src', all[counter].src);
} else {
if (e.target.tagName == 'SPAN' && e.target.id == 'right') {
counter++;
newImg.setAttribute('src', all[counter].src);
}
if (e.target.tagName == 'SPAN' && e.target.id == 'left') {
counter--;
newImg.setAttribute('src', all[counter].src);
}
}
});
</code></pre>
| [] | [
{
"body": "<h2>Explanation:</h2>\n\n<p>If you're going to take the source of an image and set it to another image, why even bother having those images as HTML? It would be <em>much</em> simpler to simply store the image urls in an array like so:</p>\n\n<pre><code>const imageUrls = [\n \"https://i.ytimg.com/vi/E6CYI3Xb1tQ/maxresdefault.jpg\",\n \"https://upload.wikimedia.org/wikipedia/commons/9/9b/Dragon_Ball_Z_Logo.png\",\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDWVk-v3DR5j0pHabogu6i3n1KLhqJWNd-Z54qevISiCoHKF88\",\n \"https://media.comicbook.com/2017/02/vegeta-dragon-ball-z-235088-1280x0.png\"\n];\n</code></pre>\n\n<p>Secondly, you're using a <code>counter</code> variable and an <code>imageSelected</code> variable... but their end goal is the same thing. Stick with the <code>counter</code>.</p>\n\n<p>You're spending a lot of time writing conditions, why not use % (modulo) to determine which is the next image.</p>\n\n<p>When the right button is clicked simply do:</p>\n\n<pre><code>counter = (counter + 1) % imageUrls.length\n</code></pre>\n\n<p>This way, once you get to the last image (counter = 3) and wish to go to the next one, then <code>(counter + 1) = (3+1) = (4)</code>. So the new position is 4 however the imageUrl length is 4.. and <code>4 % 4 = 0</code>. So, it's an easy solution to reset the counter to 0 when it gets to the end of the image url list.</p>\n\n<p>However, this doesn't work when you wish to go left. Because module doesn't work on negative numbers. To solve this do the following.</p>\n\n<pre><code>counter = (counter + -1 + imageUrls.length) % imageUrls.length\n</code></pre>\n\n<p>Now, to figure out if it's <code>1</code> or <code>-1</code> and to avoid setting a condition for it, we're going to store those values in the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*\" rel=\"nofollow noreferrer\"><code>data attributes</code></a> in the left and right HTML elements like so:</p>\n\n<pre><code><span data-direction=\"1\" id=\"left\">&#10096;</span>\n<span data-direction=\"-1\" id=\"right\">&#10097;</span>\n</code></pre>\n\n<p>Then simply to access them in the event callback:</p>\n\n<pre><code>Number(this.dataset.direction) //returns a string so reason why use Number to convert it.\n</code></pre>\n\n<p>Now, all there is left to do is to complete the formula.</p>\n\n<pre><code>counter = (counter + Number(this.dataset.direction) + imageUrls.length) % imageUrls.length;\n</code></pre>\n\n<p>Avoid setting the onclick function to a container and actually set it to the elements that need to be clicked.</p>\n\n<pre><code>imgDisplay.querySelectorAll(\"#left, #right\").forEach(element=>{\n //first time this is called element = left\n //second time this is called element = second\n //for each element add an event listener.\n});\n</code></pre>\n\n<h2>Solution:</h2>\n\n<pre><code>const imageUrls = [\n \"https://i.ytimg.com/vi/E6CYI3Xb1tQ/maxresdefault.jpg\",\n \"https://upload.wikimedia.org/wikipedia/commons/9/9b/Dragon_Ball_Z_Logo.png\",\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDWVk-v3DR5j0pHabogu6i3n1KLhqJWNd-Z54qevISiCoHKF88\",\n \"https://media.comicbook.com/2017/02/vegeta-dragon-ball-z-235088-1280x0.png\"\n];\n\nconst imgDisplay = document.getElementById('image-display');\n\n\nlet counter = 0;\nconst img = new Image();\nimg.src = imageUrls[counter];\nimgDisplay.appendChild(img);\n\nimgDisplay.querySelectorAll(\"#left, #right\").forEach(element=>{\n element.addEventListener('click', function(e){\n counter = (counter + Number(this.dataset.direction) + imageUrls.length) % imageUrls.length;\n img.src = imageUrls[counter];\n });\n});\n</code></pre>\n\n<h2>Working Example:</h2>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const imageUrls = [\n \"https://i.ytimg.com/vi/E6CYI3Xb1tQ/maxresdefault.jpg\",\n \"https://upload.wikimedia.org/wikipedia/commons/9/9b/Dragon_Ball_Z_Logo.png\",\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDWVk-v3DR5j0pHabogu6i3n1KLhqJWNd-Z54qevISiCoHKF88\",\n \"https://media.comicbook.com/2017/02/vegeta-dragon-ball-z-235088-1280x0.png\"\n];\n\nconst imgDisplay = document.getElementById('image-display');\n\n\nlet counter = 0;\nconst img = new Image();\nimg.src = imageUrls[counter];\nimgDisplay.appendChild(img);\n\nimgDisplay.querySelectorAll(\"#left, #right\").forEach(element=>{\n element.addEventListener('click', function(e){\n counter = (counter + Number(this.dataset.direction) + imageUrls.length) % imageUrls.length;\n img.src = imageUrls[counter];\n });\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#image-display {\n width: 500px;\n height: 100%;\n border: 3px solid orange;\n z-index: -1;\n padding: 3;\n margin: 0;\n}\n\n#img-size {\n height: 100%;\n width: 100%;\n z-index: -1;\n margin: 0;\n position: relative;\n}\n\n\n/* left arrow */\n\n#left {\n z-index: 0;\n position: fixed;\n left: 21.5%;\n top: 10%;\n cursor: pointer;\n color: #ffffff;\n padding: 0;\n}\n\n\n/* right arrow */\n\n#right {\n z-index: 0;\n position: fixed;\n right: 53.5%;\n top: 10%;\n cursor: pointer;\n color: #ffffff;\n padding: 0;\n}\n\n\n/*Desktop Media Queries*/\n\n@media(min-width: 1573px) {\n #right {\n right: 35%;\n top: 12%;\n }\n #left {\n left: 35.5%;\n top: 12%;\n }\n}\n\n@media(min-width: 1613px) {\n #right {\n right: 35.5%;\n top: 11%;\n }\n #left {\n left: 35.5%;\n top: 11%;\n }\n}\n\n@media(min-width: 1140px) {\n #right {\n right: 37.5%;\n top: 11%;\n }\n #left {\n left: 37.5%;\n top: 11%;\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><html>\n\n<head>\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <title></title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">\n\n</head>\n\n<body>\n <div class=\"container\">\n\n <div id=\"image-display\" class=\"mx-auto\">\n <!-- <img id=\"img-size\" class=\"selector\" /> -->\n <span data-direction=\"1\" id=\"left\">&#10096;</span>\n <span data-direction=\"-1\" id=\"right\">&#10097;</span>\n </div>\n </div>\n</body>\n\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T09:41:37.163",
"Id": "415751",
"Score": "1",
"body": "thank you for reviewing, there was a lot of room to refactor the code, but this was simply basic for what I have learned in JS at the moment and using ES6. I'm hoping to use this within a latest project of mine, where the user simply uploads pictures, which this part is built :). I will review your solution and attempt to look into the other approach. Greatly appreciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:42:42.340",
"Id": "214934",
"ParentId": "214916",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:01:54.143",
"Id": "214916",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"html",
"css"
],
"Title": "JS Simple Image Slider"
} | 214916 |
<p>In C#, 64bit Windows, .NET 4.5 (or later), and enabling <code>gcAllowVeryLargeObjects</code> in the App.config file allows for objects larger than two gigabyte. That's cool, but unfortunately, the maximum number of elements that C# allows in an array is still <a href="https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element" rel="nofollow noreferrer">limited to about 2^31 = 2.15 billion</a>. Testing confirmed this.</p>
<p>To overcome this, Microsoft <a href="https://web.archive.org/web/20181119090643/https://blogs.msdn.microsoft.com/joshwil/2005/08/10/bigarrayt-getting-around-the-2gb-array-size-limit/" rel="nofollow noreferrer">recommends in Option B</a> creating the arrays natively. Problem is we need to use unsafe code, and as far as I know, unicode won't be supported, at least not easily.</p>
<p>So I ended up creating my own BigStringBuilder function in the end. It's a list where each list element (or page) is a char array (type <code>List<char[]></code>).</p>
<p>Providing you're using 64 bit Windows, you can now easily surpass the 2 billion character element limit. I managed to test creating a giant string around 32 gigabytes large (needed to increase virtual memory in the OS first, otherwise I could only get around 7GB on my 8GB RAM PC). I'm sure it handles more than 32GB easily. In theory, it should be able to handle around 1,000,000,000 * 1,000,000,000 chars or one quintillion characters, which should be enough for anyone!</p>
<p>I also added some common functions to provide some functionality such as fileSave(), length(), substring(), replace(), etc. Like the StringBuilder, in-place character writing (mutability), and instant truncation are possible.</p>
<p>Speed-wise, some quick tests show that it's not significantly slower than a StringBuilder when appending (found it was 33% slower in one test). I got similar performance if I went for a 2D jagged char array (<code>char[][]</code>) instead of <code>List<char[]></code>, but Lists are simpler to work with, so I stuck with that.</p>
<p>I'm looking for advice to potentially speed up performance, particularly for the append function, and to access or write faster via the indexer (<code>public char this[long n] {...}</code> )</p>
<pre><code>// A simplified version specially for StackOverflow / Codereview
public class BigStringBuilder
{
List<char[]> c = new List<char[]>();
private int pagedepth;
private long pagesize;
private long mpagesize; // https://stackoverflow.com/questions/11040646/faster-modulus-in-c-c
private int currentPage = 0;
private int currentPosInPage = 0;
public BigStringBuilder(int pagedepth = 12) { // pagesize is 2^pagedepth (since must be a power of 2 for a fast indexer)
this.pagedepth = pagedepth;
pagesize = (long)Math.Pow(2, pagedepth);
mpagesize = pagesize - 1;
c.Add(new char[pagesize]);
}
// Indexer for this class, so you can use convenient square bracket indexing to address char elements within the array!!
public char this[long n] {
get { return c[(int)(n >> pagedepth)][n & mpagesize]; }
set { c[(int)(n >> pagedepth)][n & mpagesize] = value; }
}
public string[] returnPagesForTestingPurposes() {
string[] s = new string[currentPage + 1];
for (int i = 0; i < currentPage + 1; i++) s[i] = new string(c[i]);
return s;
}
public void clear() {
c = new List<char[]>();
c.Add(new char[pagesize]);
currentPage = 0;
currentPosInPage = 0;
}
// See: https://stackoverflow.com/questions/373365/how-do-i-write-out-a-text-file-in-c-sharp-with-a-code-page-other-than-utf-8/373372
public void fileSave(string path) {
StreamWriter sw = File.CreateText(path);
for (int i = 0; i < currentPage; i++) sw.Write(new string(c[i]));
sw.Write(new string(c[currentPage], 0, currentPosInPage));
sw.Close();
}
public void fileOpen(string path) {
clear();
StreamReader sw = new StreamReader(path);
int len = 0;
while ((len = sw.ReadBlock(c[currentPage], 0, (int)pagesize)) != 0){
if (!sw.EndOfStream) {
currentPage++;
if (currentPage == c.Count) c.Add(new char[pagesize]);
}
else {
currentPosInPage = len;
break;
}
}
sw.Close();
}
public long length() {
return (long)currentPage * (long)pagesize + (long)currentPosInPage;
}
public string ToString(long max = 2000000000) {
if (length() < max) return substring(0, length());
else return substring(0, max);
}
public string substring(long x, long y) {
StringBuilder sb = new StringBuilder();
for (long n = x; n < y; n++) sb.Append(c[(int)(n >> pagedepth)][n & mpagesize]); //8s
return sb.ToString();
}
public bool match(string find, long start = 0) {
//if (s.Length > length()) return false;
for (int i = 0; i < find.Length; i++) if (i + start == find.Length || this[start + i] != find[i]) return false;
return true;
}
public void replace(string s, long pos) {
for (int i = 0; i < s.Length; i++) {
c[(int)(pos >> pagedepth)][pos & mpagesize] = s[i];
pos++;
}
}
// Simple implementation of an append() function. Testing shows this to be about
// as fast or faster than the more sophisticated Append2() function further below
// despite its simplicity:
public void Append(string s)
{
for (int i = 0; i < s.Length; i++)
{
c[currentPage][currentPosInPage] = s[i];
currentPosInPage++;
if (currentPosInPage == pagesize)
{
currentPosInPage = 0;
currentPage++;
if (currentPage == c.Count) c.Add(new char[pagesize]);
}
}
}
// This method is a more sophisticated version of the Append() function above.
// Surprisingly, in real-world testing, it doesn't seem to be any faster.
public void Append2(string s)
{
if (currentPosInPage + s.Length <= pagesize)
{
// append s entirely to current page
for (int i = 0; i < s.Length; i++)
{
c[currentPage][currentPosInPage] = s[i];
currentPosInPage++;
}
}
else
{
int stringpos;
int topup = (int)pagesize - currentPosInPage;
// Finish off current page with substring of s
for (int i = 0; i < topup; i++)
{
c[currentPage][currentPosInPage] = s[i];
currentPosInPage++;
}
currentPage++;
currentPosInPage = 0;
stringpos = topup;
int remainingPagesToFill = (s.Length - topup) >> pagedepth; // We want the floor here
// fill up complete pages if necessary:
if (remainingPagesToFill > 0)
{
for (int i = 0; i < remainingPagesToFill; i++)
{
if (currentPage == c.Count) c.Add(new char[pagesize]);
for (int j = 0; j < pagesize; j++)
{
c[currentPage][j] = s[stringpos];
stringpos++;
}
currentPage++;
}
}
// finish off remainder of string s on new page:
if (currentPage == c.Count) c.Add(new char[pagesize]);
for (int i = stringpos; i < s.Length; i++)
{
c[currentPage][currentPosInPage] = s[i];
currentPosInPage++;
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:22:48.837",
"Id": "415629",
"Score": "7",
"body": "So what kind of crazy stuff one needs this large data-types for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:59:34.987",
"Id": "415636",
"Score": "0",
"body": "@t3chb0t: Converting giant CSV files for users of my software. Ask my users :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:02:33.413",
"Id": "415637",
"Score": "4",
"body": "ok... but isn't streaming it easier and faster than loading the entire file into memory? It screams: the [XY Problem](https://en.wikipedia.org/wiki/XY_problem). Your users are not responsible for you wasting RAM :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:08:52.977",
"Id": "415639",
"Score": "2",
"body": "The question you should be asking is how you can convert _this giant_ CSV more efficiently rather than brute-forcing it into your RAM."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:18:55.737",
"Id": "415641",
"Score": "0",
"body": "@t3chb0t: In my dreams. The giant string will be analysed and manipulated more than once (e.g: checked for number of pairs of open/close braces, followed by special text replacements, then removing empty lines/whitespace, and other possible filtering, followed by consistency checks for column counts for every row). And that's just for one of the simpler conversions. These tasks will be slower if manipulation is performed repeatedly via HDD (or even SSD) instead of RAM."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:21:09.840",
"Id": "415642",
"Score": "1",
"body": "oh boy... this sounds like you're pushing json over csv... this is even more scarry then I thought. This entire concept seems to be pretty odd :-| Why don't you do the filtering on the fly? Read, filter, write...? Anyway, have fun with this monster solution ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:22:37.137",
"Id": "415643",
"Score": "0",
"body": "@t3chb0t: Funnily enough, one of the possible conversions is from CSV to JSON, or vice versa :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:32:23.100",
"Id": "415645",
"Score": "1",
"body": "@DanW: it still sounds like treating the input as one giant string is not the most efficient approach. If you really can't process it in a streaming fashion, then did you look into specialized data structures such as ropes, gap buffers, piece tables, that sort of stuff?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:57:16.427",
"Id": "415648",
"Score": "0",
"body": "@t3chb0t: There are many parts where the whole text needs to be loaded before it can even consider writing (consistency checks is one example, and so is obtaining all possible parameters to present to the user). Regardless, the giant 2D string array I also have (elegant mediator between input and output for many different file types) is about 3x larger in terms of memory. On the small off-chance loading/filtering line by line works, it'd be a complete rewrite of the code, which started off as a small project, but has grown beyond my initial expectations (to put it mildly)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:59:35.217",
"Id": "415649",
"Score": "0",
"body": "@PieterWitvoet: See my comment above for more info. In answer to your question, no, though because the code is already very complex, I'd rather minimize further complexity in any way I can, especially if speed will end up being affected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T18:32:40.120",
"Id": "415669",
"Score": "0",
"body": "Is it not possible to parse the string in chunks and then deal with a >2GB list of objects than with a >2GB string? I think all you want to do (consistency checks, parameters, etc) will be easier to handle if you have your data in a data structure and not as text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T18:33:22.880",
"Id": "415670",
"Score": "0",
"body": "Regarding the solution itself, I would suggest you research `Span<T>` and friends. Since I don't know them well enough, I can't give a full answer with these."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T19:05:22.253",
"Id": "415673",
"Score": "1",
"body": "You're talking about replacing and removing text. How do you plan to support those operations in an efficient manner? But you're also talking about a 2D string array. Why do you need to work with the input as a giant string(builder) if you already have a more appropriate data structure?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T20:08:03.267",
"Id": "415681",
"Score": "0",
"body": "[This question is being discussed on meta](https://codereview.meta.stackexchange.com/q/9112/31562). In the mean-time I have rolled-back your edit where you replied to the answer below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T10:56:19.460",
"Id": "415763",
"Score": "0",
"body": "@PieterWitvoet: Just as one example, in case of a malformed CSV, some rows may have less/more columns than others, and I need to find the maximum number of columns for any row before creating the appropriately sized 2D array. Another thing which springs to mind is that I feel operating on millions of individual strings in a 2D string array would perform slower than in-place character replacements on a single giant BigStringBuilder. I could be mistaken though. Also to reiterate, there's no chance I'm rewriting the code at this stage - it'd be a lot of work."
}
] | [
{
"body": "<blockquote>\n<pre><code> List<char[]> c = new List<char[]>();\n private int pagedepth;\n private long pagesize;\n private long mpagesize; // https://stackoverflow.com/questions/11040646/faster-modulus-in-c-c\n private int currentPage = 0;\n private int currentPosInPage = 0;\n</code></pre>\n</blockquote>\n\n<p>Some of these names are rather cryptic. I'm not sure why <code>c</code> isn't private. And surely some of the fields should be <code>readonly</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> pagesize = (long)Math.Pow(2, pagedepth);\n</code></pre>\n</blockquote>\n\n<p>IMO it's better style to use <code>1L << pagedepth</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public char this[long n] {\n get { return c[(int)(n >> pagedepth)][n & mpagesize]; }\n set { c[(int)(n >> pagedepth)][n & mpagesize] = value; }\n }\n</code></pre>\n</blockquote>\n\n<p>Shouldn't this have bounds checks?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public string[] returnPagesForTestingPurposes() {\n string[] s = new string[currentPage + 1];\n for (int i = 0; i < currentPage + 1; i++) s[i] = new string(c[i]);\n return s;\n }\n</code></pre>\n</blockquote>\n\n<p>There's no need for this to be public: you can make it <code>internal</code> and give your unit test project access with <code>[assembly:InternalsVisibleTo]</code>. Also, since it's for testing purposes, it could probably be marked <code>[System.Diagnostics.Conditional(\"DEBUG\")]</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void clear() {\n c = new List<char[]>();\n c.Add(new char[pagesize]);\n</code></pre>\n</blockquote>\n\n<p>In C# it's conventional for method names to start with an upper case letter.</p>\n\n<p>There's no need to throw quite as much to the garbage collector. Consider as an alternative:</p>\n\n<pre><code>var page0 = c[0];\nc.Clear();\nc.Add(page0);\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> // See: https://stackoverflow.com/questions/373365/how-do-i-write-out-a-text-file-in-c-sharp-with-a-code-page-other-than-utf-8/373372\n</code></pre>\n</blockquote>\n\n<p>Why? I don't think it sheds any light on the following method.</p>\n\n<blockquote>\n<pre><code> public void fileSave(string path) {\n StreamWriter sw = File.CreateText(path);\n for (int i = 0; i < currentPage; i++) sw.Write(new string(c[i]));\n sw.Write(new string(c[currentPage], 0, currentPosInPage));\n sw.Close();\n }\n</code></pre>\n</blockquote>\n\n<p>Missing some <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.idisposable.dispose?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">disposal</a>: I'd use a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement\" rel=\"nofollow noreferrer\"><code>using</code> statement</a>.</p>\n\n<p><code>new string(char[])</code> copies the entire array to ensure that the string is immutable. That's completely unnecessary here: <code>StreamWriter</code> has a method <code>Write(char[], int, int)</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void fileOpen(string path) {\n clear();\n</code></pre>\n</blockquote>\n\n<p>Yikes! That should be mentioned in the method documentation.</p>\n\n<blockquote>\n<pre><code> StreamReader sw = new StreamReader(path);\n int len = 0;\n while ((len = sw.ReadBlock(c[currentPage], 0, (int)pagesize)) != 0){\n if (!sw.EndOfStream) {\n currentPage++;\n if (currentPage == c.Count) c.Add(new char[pagesize]);\n }\n else {\n currentPosInPage = len;\n break;\n</code></pre>\n</blockquote>\n\n<p>I think this can give rise to inconsistencies. Other methods seem to assume that if the length of the <code>BigStringBuilder</code> is an exact multiple of <code>pagesize</code> then <code>currentPosInPage == 0</code> and <code>c[currentPage]</code> is empty, but this can give you <code>currentPosInPage == pagesize</code> and <code>c[currentPage]</code> is full.</p>\n\n<p>This method is also missing disposal.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public long length() {\n return (long)currentPage * (long)pagesize + (long)currentPosInPage;\n }\n</code></pre>\n</blockquote>\n\n<p>Why is this a method rather than a property? Why use multiplication rather than <code><<</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public string substring(long x, long y) {\n StringBuilder sb = new StringBuilder();\n for (long n = x; n < y; n++) sb.Append(c[(int)(n >> pagedepth)][n & mpagesize]); //8s\n</code></pre>\n</blockquote>\n\n<p>What is <code>8s</code>? Why append one character at a time? <code>StringBuilder</code> also has a method which takes <code>(char[], int, int)</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public bool match(string find, long start = 0) {\n //if (s.Length > length()) return false;\n for (int i = 0; i < find.Length; i++) if (i + start == find.Length || this[start + i] != find[i]) return false;\n return true;\n }\n</code></pre>\n</blockquote>\n\n<p>What does this method do? The name implies something regexy, but there's no regex in sight. The implementation looks like <code>StartsWith</code> (by default - the offset complicates it).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public void replace(string s, long pos) {\n for (int i = 0; i < s.Length; i++) {\n c[(int)(pos >> pagedepth)][pos & mpagesize] = s[i];\n pos++;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Bounds checks?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // This method is a more sophisticated version of the Append() function above.\n // Surprisingly, in real-world testing, it doesn't seem to be any faster. \n</code></pre>\n</blockquote>\n\n<p>I'm not surprised. It's still copying character by character. It's almost certainly faster to use <code>string.CopyTo</code> (thanks to <a href=\"https://codereview.stackexchange.com/users/51173/pieter-witvoet\">Pieter Witvoet</a> for mentioning this method) or <code>ReadOnlySpan.CopyTo</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:26:54.093",
"Id": "415644",
"Score": "0",
"body": "Thanks! Added responses to my main post if you want to look."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:34:02.560",
"Id": "415646",
"Score": "2",
"body": "Regarding the last point, there's also `string.CopyTo`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T19:23:30.953",
"Id": "415675",
"Score": "0",
"body": "c# class instance members are private by default, so `c` is private. But you're right that it is inconsistent to not explicitly declare it private like the other fields are. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/accessibility-levels"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T05:32:25.453",
"Id": "415725",
"Score": "0",
"body": "Thanks. I gave a more [detailed response](https://codereview.stackexchange.com/revisions/214917/6) to my Q, but it was rolled back, so I'll keep things terse here: \"Shouldn't this have bounds checks?\": Not if we want maximum speed? Re: StreamWriter, doesn't `Close()` dispose the StreamWriter when the method ends, like other normal class objects outside of scope would be? If not, I could use `sw=null;`? \"I'm not surprised. It's still copying character by character.\": I expected faster because there isn't the If condition (`if (currentPosInPage == pagesize)`) for every character that's appended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T09:15:22.090",
"Id": "415747",
"Score": "0",
"body": "@DanW, that's not what I meant by disposal. I've added a couple of links which should make it clearer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T09:44:33.953",
"Id": "415752",
"Score": "0",
"body": "Apparently, `StreamWriter.Close()` just calls `StreamWriter.Dispose()` [under the bonnet](https://stackoverflow.com/a/1187727/848344), so maybe my `Close()` statement is sufficient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T10:21:52.700",
"Id": "415759",
"Score": "3",
"body": "@DanW: `using` translates to a `try/finally` statement that ensures disposal even when an exception is thrown, so it's almost always the better approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T13:33:59.857",
"Id": "415778",
"Score": "1",
"body": "By the way, for your info, appending using `string.CopyTo` is around 3.2x as fast as my original code! Code is: `s.CopyTo(0, c[currentPage], currentPosInPage, s.Length); currentPosInPage += s.Length;`. Just for fun, I also tried: `Array.Copy(s.ToCharArray(), 0, c[currentPage], currentPosInPage, s.Length); currentPosInPage += s.Length;`, and that was not quite as good (2.1x faster), but still better than my original code."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T15:12:00.433",
"Id": "214931",
"ParentId": "214917",
"Score": "9"
}
},
{
"body": "<h3>Design considerations</h3>\n\n<p>In the comments you mentioned that you're going to analyze and manipulate this string? If so, that could be a problem, because replacing, inserting and removing text requires moving all subsequent characters to make room or to fill the gap. With this much data, you can expect that to have a major impact on performance. That is why I mentioned data structures like ropes, gap buffers and piece tables: those are often used in text editors to efficiently support these kind of operations.</p>\n\n<p>But I think that would be solving the wrong problem. From what I understand so far, the rest of your code is built around a 2D array of strings - a table, essentially - that can be converted to a variety of formats. Because it's an array, you need to know the number of columns and rows up-front, so you need to parse the input before you can allocate the array, and then parse it again to fill the array. This <code>BigStringBuilder</code> class allows you to read the whole file into memory, so you don't have to read it from disk twice.</p>\n\n<p>Why not use dynamically resizable arrays (<code>List<T></code>) instead? That would allow you to read the data directly into your final data structure with only a single parsing pass. If that requires a lot of work, then you're probably suffering from a lack of abstraction. Instead of passing a raw <code>string[,]</code> around, wrap it in a class. That allows you to swap the internal 2D array for a more suitable data structure without having to modify all the code that uses this table.</p>\n\n<p>For example, a <code>List<List<string>></code> as internal data structure lets you add variable-length rows on-the-fly, so you only need a single parsing pass. That also allows you to read the input file in a streaming fashion instead of having to read it fully into memory first.</p>\n\n<p>If modifying existing code that relies in a 2D string array sounds like a lot of work, consider emulating the 'interface' of a 2D array. With a class that provides a <code>string this[int row, int column]</code> indexer and a <code>GetLength(int dimension)</code> method, chances are that you only need to change the type of a bunch of parameters and variables.</p>\n\n<hr>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>Putting <code>if</code> and <code>for</code> bodies on the same line makes control flow difficult to follow.</li>\n<li><code>fileSave</code> and <code>fileOpen</code> are not very flexible. Letting the caller pass in a <code>Stream</code> or <code>TextReader</code>/<code>TextWriter</code> would make them more reusable. That also gives callers control over things like encoding and buffer size. Additionally, overloads like <code>CopyToStream(Stream toStream, long offset, long count)</code> and <code>CopyFromStream(Stream fromStream, long count)</code> are probably also a good idea.</li>\n<li><code>c[(int)(n >> pagedepth)][n & mpagesize]</code> is duplicated several times in the code. Use <code>this[n]</code> instead.</li>\n<li>There's very little documentation, especially for infrastructure-level code like this. I don't know about you, but I tend to forget things about code I wrote a while ago, so documentation that explains why something works the way it does, or how something is intended to be used, is quite useful.</li>\n<li>I'd recommend using more self-descriptive names, and aiming for consistency with the standard types you're 'emulating':\n\n<ul>\n<li><code>this[n]</code> -> <code>this[index]</code></li>\n<li><code>substring(x, y)</code> -> <code>Substring(startIndex, length)</code></li>\n<li><code>replace(s, pos)</code> -> <code>Overwrite(value, startIndex)</code> (I find <code>replace</code> confusing because it's so different from what <code>string.Replace</code> does)</li>\n</ul></li>\n<li>Regarding camelCase vs PascalCase, I don't see why it's important to distinguish between standard library code and your own, but to each their own I guess. But why the inconsistency in <code>ToString</code> and <code>Append</code>?</li>\n<li>I'd argue that correctness is more important than performance. Leaving out bounds checks should be a last resort, and only when profiling shows that they're actually a bottleneck. Chances are that it's possible to improve the API so you don't need to access individual characters so often.</li>\n<li>I agree with Peter that <code>fileOpen</code> clearing the string-builder is unexpected behavior, in a negative way.\nCertainly the caller can call <code>clear</code> before <code>fileOpen</code> if that's the behavior they want? Otherwise, I would clearly document this.</li>\n<li><code>length</code> being a method is inconsistent with <code>StringBuilder</code> and other collection types. A little bit of calculation in a property should be fine.</li>\n<li>If you're using <code>returnPagesForTestingPurposes</code> for automated testing then you're testing implementation details, which is a bad idea. If you're using it for debugging, then why not inspect the data with a debugger instead, or use tracepoints?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T07:50:06.027",
"Id": "415980",
"Score": "0",
"body": "I manipulate the string so that in-place replacements are either equal in length, or shorter, so that reading can continue whilst the same BigStringBuilder is being operated on. Your idea of using List<T> is interesting regardless. Honestly, a part of me would love to experiment and refactor the program like you say to compare speed, but time is limited. FYI, `string[,]` is poor only allowing for 2^28 elements in total. `string[][]` allows essentially around 2^56 elements, far better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T07:51:14.857",
"Id": "415981",
"Score": "0",
"body": "Quote: \"c[(int)(n >> pagedepth)][n & mpagesize] is duplicated several times in the code\": Sadly, I found function calling slower than writing the code direct, possibly due to the compiler not inlining it. Quote: \"But why the inconsistency in ToString and Append?\": I have less excuse with Append(), but ToString was due to overriding the default ToString method. Quote: \"Leaving out bounds checks should be a last resort\": Either way, it'll crash and I can easily solve the bug. Besides, the program has already been heavily tested, so safety is less of a concern now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-11T08:48:42.777",
"Id": "416087",
"Score": "0",
"body": "So you're using a jagged array then? In that case you could parse the input directly into a `List<string[]>` and convert it to a `string[][]` afterwards, so you don't need to modify any of the other code at all. About inlining, you could try marking the indexer's getter and setter with `MethodImplOptions.AggressiveInlining`. Note that `replace` can be optimized by using `string.CopyTo`. About bounds checks, if 'it'll crash' means that you're expecting it to throw an exception anyway, then that's not the case when accessing unused characters in the last page."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-11T11:18:15.237",
"Id": "416112",
"Score": "0",
"body": "One other factor to consider is when the user changes settings after the results are displayed. Reading it all out from HDD into a 2D array, would next a second HDD read after the user adjusts a single setting afterwards as it would need to be reparsed. Regarding `AggressiveInlining`, it seems to do the trick, but requires .NET 4.5, and I fear many of my users are still using .NET 3.5/4. Pretty astonishing that the C# team haven't fixed the issue until .NET4.5+."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T19:29:01.833",
"Id": "215054",
"ParentId": "214917",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "214931",
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:05:26.653",
"Id": "214917",
"Score": "7",
"Tags": [
"c#",
"performance",
"strings",
"pagination"
],
"Title": "Version of C# StringBuilder to allow for strings larger than 2 billion characters"
} | 214917 |
<p>I have a struct which nests other structs like following:</p>
<pre><code>#[derive(Debug)]
pub struct Rankings {
conferences: Vec<Conference>,
}
#[derive(Debug)]
pub struct Conference {
divisions: Vec<Division>,
}
#[derive(Debug)]
pub struct Division {
teams: Vec<Team>,
}
#[derive(Debug, Clone)]
pub struct Team {
name: String,
market: String,
}
</code></pre>
<p>What I want to do is converting a <code>Rankings</code> instance to <code>Vec<Team></code>. Here's my solution:</p>
<pre><code>fn main() {
let mut rankings = Rankings {
conferences: vec![
Conference {
divisions: vec![
Division {
teams: vec![
Team {
name: String::from("Raptors"),
market: String::from("Toronto"),
},
Team {
name: String::from("Knicks"),
market: String::from("New York"),
}
]
},
Division {
teams: vec![
Team {
name: String::from("Bucks"),
market: String::from("Milwaukee"),
},
Team {
name: String::from("Cavaliers"),
market: String::from("Cleveland"),
}
]
},
]
},
]
};
println!("- rankings:\n{:#?}\n", rankings);
let mut raw_teams: Vec<Vec<Vec<Team>>> = rankings
.conferences
.iter_mut()
.map(|c| c.divisions.iter_mut().map(|d| d.teams.clone()).collect())
.collect();
println!("- raw_teams:\n{:#?}\n", raw_teams);
let flattened_teams = raw_teams
.iter_mut()
.fold(Vec::new(), |mut acc, val| {
acc.append(val);
acc
})
.iter_mut()
.fold(Vec::new(), |mut acc, val| {
acc.append(val);
acc
});
println!("- flattened_teams:\n{:#?}\n", flattened_teams);
}
</code></pre>
<p><a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=58307f8e83dcea162f49f8e483b47c49" rel="nofollow noreferrer">Playground link</a></p>
<p>First, I converted <code>Rankings</code> to <code>Vec<Vec<Vec<Team>>></code> using <code>iter_mut()</code> and <code>map()</code>, then flattened <code>Vec<Vec<Vec<Team>>></code> to <code>Vec<Team></code> using <code>iter_mut()</code> and <code>fold()</code>.</p>
<p>But I just wrote that code avoiding compile errors, which mean the code could be refactored better using idiomatic patterns. I think I might overuse mutability, and two conversion process can be simplified using appropriate iterator functions. Thanks for any advices.</p>
| [] | [
{
"body": "<p>First of all, there is no need to use <code>iter_mut()</code> on <code>conferences</code>, as you never change the original <code>rankings</code>. As we <code>clone</code> the teams later, we can simply use</p>\n\n<pre><code>let mut raw_teams: Vec<Vec<Vec<Team>>> = rankings\n .conferences\n .iter()\n .map(|c| c.divisions.iter().map(|d| d.teams.clone()).collect())\n .collect();\n</code></pre>\n\n<p>Now that we have a <code>Vec<Vec<Vec<Team>></code>, we can call <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flatten\" rel=\"nofollow noreferrer\"><code>flatten</code></a>:</p>\n\n<pre><code>let flattened_teams: Vec<Team> = raw_teams.into_iter().flatten().flatten().collect();\n</code></pre>\n\n<p>I used <code>into_iter()</code> as your original code left <code>raw_teams</code> empty.</p>\n\n<p>However, we can skip <code>raw_teams</code> entirely if we use <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flat_map\" rel=\"nofollow noreferrer\"><code>flat_map</code></a> instead of <code>map(…).flatten()</code>:</p>\n\n<pre><code>let flattened_teams: Vec<Team> = rankings\n .conferences\n .iter()\n .flat_map(|c| &c.divisions) // need to borrow due to iter()\n .flat_map(|d| &d.teams) // need to borrow due to iter()\n .cloned() // clone the elements\n .collect();\n</code></pre>\n\n<p>If we don't want to borrow, we can of course just move everything into <code>flattened_teams</code> by simply removing <code>cloned()</code> and <code>&</code>:</p>\n\n<pre><code>let flattened_teams : Vec<Team> = rankings\n .conferences\n .into_iter()\n .flat_map(|c| c.divisions)\n .flat_map(|d| d.teams)\n .collect()\n</code></pre>\n\n<p>None of these functions use <code>mut</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T19:36:17.027",
"Id": "415679",
"Score": "0",
"body": "Note you can move the `cloned()` outside, right before the `collect()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T07:00:41.777",
"Id": "415732",
"Score": "0",
"body": "Edited, @JayDepp, as it makes both variants symmetric."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T14:01:15.493",
"Id": "214926",
"ParentId": "214918",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214926",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:09:48.410",
"Id": "214918",
"Score": "3",
"Tags": [
"functional-programming",
"rust",
"immutability"
],
"Title": "Rust: Flattening nested struct to Vec<T>"
} | 214918 |
<p>This is an updated version of my previously posted "<em><a href="https://codereview.stackexchange.com/questions/214592/blackjack-game-made-in-python-3">Blackjack game made in Python 3</a></em>". I think I did almost everything @Austin Hastings recommend me to do and I hope you like it.</p>
<pre><code>from random import shuffle
import os
def shuffled_shoe():
shoe = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'A', 'J', 'Q', 'K']*4
shuffle(shoe)
return shoe
def deal_card(shoe, person, number):
for _ in range(number):
person.append(shoe.pop())
def deal_hand(shoe, player, dealer):
deal_card(shoe, player, 2)
deal_card(shoe, dealer, 2)
def score(person):
non_aces = [c for c in person if c != 'A']
aces = [c for c in person if c == 'A']
total = 0
for card in non_aces:
if card in 'JQK':
total += 10
else:
total += int(card)
for card in aces:
if total <= 10:
total += 11
else:
total += 1
return total
def display_info(player, dealer, player_stands):
os.system('cls' if os.name == 'nt' else 'clear')
print("Your cards: [{}] ({})".format("][".join(player), score(player)))
if player_stands:
print("Dealer cards: [{}] ({})".format("][".join(dealer), score(dealer)))
else:
print(f"Dealer cards: [{dealer[0]}][?]")
def hit_or_stand():
while True:
print("What do you choose?")
print("[1] Hit")
print("[2] Stand")
ans = input("> ")
if ans in '12':
return ans
def player_play(shoe, player, dealer, player_plays, dealer_plays, player_stands):
while not player_stands:
if hit_or_stand() == '2':
player_plays = False
dealer_plays = True
player_stands = True
display_info(player, dealer, True)
elif not player_stands:
deal_card(shoe, player, 1)
display_info(player, dealer, False)
if score(player) >= 21:
player_plays = False
break
return (player_plays, dealer_plays, player_stands)
def dealer_play(shoe, dealer, DEALER_MINIMUM_SCORE, player):
while score(dealer) <= DEALER_MINIMUM_SCORE:
deal_card(shoe, dealer, 1)
display_info(player, dealer, True)
return False
def results(player, dealer, player_stands, first_hand, still_playing):
if score(player) == 21:
print("Blackjack! You won")
still_playing = False
elif first_hand and score(dealer) == 21:
print("Dealer got a blackjack. You lost!")
still_playing = False
elif score(player) > 21:
print("Busted! You lost!")
still_playing = False
if player_stands:
if score(dealer) > 21:
print("Dealer busted! You won")
elif score(player) > score(dealer):
print("You beat the dealer! You won!")
elif score(player) < score(dealer):
print("Dealer has beaten you. You lost!")
else:
print("Push. Nobody wins or losses.")
still_playing = False
return still_playing
def main():
shoe = shuffled_shoe()
player = []
dealer = []
player_plays = True
still_playing = True
dealer_plays = False
player_stands = False
deal_hand(shoe, player, dealer)
display_info(player, dealer, player_stands)
still_playing = results(player, dealer, player_stands, True, still_playing)
while still_playing:
while player_plays:
(player_plays, dealer_plays, player_stands) = player_play(shoe, player, dealer, player_plays, dealer_plays, player_stands)
while dealer_plays:
dealer_plays = dealer_play(shoe, dealer, 17, player)
still_playing = results(player, dealer, player_stands, False, still_playing)
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>First; I agree with the points made by @Austin. I like it that your code is written such that it is easy to read (which I find important).\nHowever, I find the structure of the program a bit hard to follow. For example; there are two display functions (display_info and result). I would merge these or at the least group them together.</p>\n\n<p>In Python there seem to be two schools: 1) put everything in a function (as a means of documentation), 2) create functions to aid \"separation of concerns\" and add comments for documentation. My guess is that @Austin is more a type-1 person and I am more a type-2 person. I would suggest to add comments (especially to document functions and function arguments).</p>\n\n<p>These are some observations from my side:</p>\n\n<ul>\n<li>a lot of functions take both the player as the dealer as argument, while their actions are similar. It could be benificial to create a more generic function for an action (stand/hit) and call that function separately. For example: create a function which asks the action of the dealer and a function asking the action of the player.</li>\n<li>the dealer_play function always returns False. So I guess you can get rid of the return argument, as well as the 'while dealer_plays:' loop.</li>\n<li>the results function seems overly complex to me. I would not call the function at all as long as the dealer or the player are still playing. This would remove the need to keep track of who is still playing. Print the intermediate scores separately and evaluate the winner after the game.</li>\n<li>there is no need to provide a boolean for first_hand. Each player and dealer always start with two cards. So len(cards)==2 gives the same information. For readability it could be good to perform this action at the start of the function (first_hand = len(dealer) == 2), as this way there is no need to change the code too much and you remove the burden of keeping track of this variable from the function-caller.</li>\n</ul>\n\n<p>There is one other point that caught my eye: you are mixing different string formatting methods (''.format() vs f-strings). I would choose one of the methods and stick with that.</p>\n\n<p>All these comments might seem like I do not like your code. This is not the case, my aim is to point out some possible improvements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T10:52:42.457",
"Id": "215015",
"ParentId": "214921",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "215015",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T13:28:38.373",
"Id": "214921",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"playing-cards"
],
"Title": "Blackjack game - follow-up"
} | 214921 |
<p>I have implemented a thread safe vector, based on std::thread and std::vector. I am new to many of the patterns used in threading and was wondering if there's a more efficient way the locking can be implemented? Also I'm not sure what the best name is to give variables that just get stored right away (i.e. <code>in</code>).</p>
<p>Here is SafeVector.hpp</p>
<pre><code>#ifndef SAFEVECTOR_HPP
#define SAFEVECTOR_HPP
#include <vector>
#include <mutex>
#include <condition_variable>
#include <string>
class SafeVector {
public:
SafeVector() : vec(), mut(), cond() {}
SafeVector(const SafeVector& orig) : vec(orig.vec), mut(), cond() {}
~SafeVector() {}
void insert(std::string in, const int index);
void push_back(std::string in);
std::string& operator[](const int index);
std::vector<std::string>::iterator begin();
std::vector<std::string>::iterator end();
std::vector<std::string> toVector();
private:
std::vector<std::string> vec;
std::mutex mut;
std::condition_variable cond;
};
#endif /* SAFEVECTOR_HPP */
</code></pre>
<p>Here is SafeVector.cpp</p>
<pre><code>#include <string>
#include <utility>
#include "SafeVector.hpp"
void SafeVector::insert(std::string in, const int index)
{
std::lock_guard<std::mutex> lock(mut);
vec[index] = std::move(in);
cond.notify_one();
}
void SafeVector::push_back(std::string in)
{
std::lock_guard<std::mutex> lock(mut);
vec.push_back(std::move(in));
cond.notify_one();
}
std::string& SafeVector::operator[](const int index)
{
return vec[index];
}
std::vector<std::string>::iterator SafeVector::begin()
{
return vec.begin();
}
std::vector<std::string>::iterator SafeVector::end()
{
return vec.end();
}
std::vector<std::string> SafeVector::toVector()
{
return vec;
}
</code></pre>
<p>Currently, these are the only functions I need to use on vectors but if I decide to implement more, I'm assuming the rest would be done in the same way. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T04:53:38.230",
"Id": "487359",
"Score": "0",
"body": "What is the purpose of condition variable here?"
}
] | [
{
"body": "<p>We probably want to be able to move-construct, so as well as this constructor:</p>\n\n<blockquote>\n<pre><code>SafeVector(const SafeVector& orig) : vec(orig.vec), mut(), cond() {}\n</code></pre>\n</blockquote>\n\n<p>We probably want also:</p>\n\n<pre><code>SafeVector(SafeVector&& orig)\n : vec{std::move(orig.vec)},\n mut{},\n cond{}\n{}\n</code></pre>\n\n<p>I'd recommend being able to construct from a standard vector:</p>\n\n<pre><code>SafeVector(std::vector vec)\n : vec{std::move(vec)},\n mut{},\n cond{}\n{}\n</code></pre>\n\n<p>Since we always default-initialize <code>mut</code> and <code>cond</code>, we could declare their initializers in the class definition, removing the need to have them in the constructors' initializer lists.</p>\n\n<p>There's no need to specify an empty destructor - just let the compiler generate it.</p>\n\n<p>I think we probably want one or more assignment operators.</p>\n\n<p>Big question: how can we safely use iterators we get from <code>begin()</code> and <code>end()</code>? There's no way for client code to lock the mutex until it's finished using the iterators.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T14:44:02.577",
"Id": "214930",
"ParentId": "214927",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T14:17:33.113",
"Id": "214927",
"Score": "7",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"vectors"
],
"Title": "Implementation of thread-safe vector"
} | 214927 |
<p>I need to search a large repository of files for a specific resource, and return it only if it is used or not. </p>
<p>It is working as expected, but it is very time consuming. To search for 50 resource names takes around 200 seconds. I have many more than 50. </p>
<p>I found <a href="https://codereview.stackexchange.com/questions/78294/powershell-search-millions-of-files-as-fast-as-possible">this</a> question that helped a bit, but I was wondering if there is anything else I can do to speed it up. </p>
<pre><code>$searchList = Get-ChildItem -r *.cs -OutBuffer 1000000
$usedIcons = @()
foreach ($name in $testNames) {
$pattern = "Resources."+$name
$found = $searchList | Select-String -Pattern $pattern -SimpleMatch -Quiet
if($found -eq $true){
Write-Host $name
$usedIcons += $name
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:40:44.067",
"Id": "415660",
"Score": "1",
"body": "I would try a parallel tool such as [the silver searcher](https://github.com/k-takata/the_silver_searcher-win32/releases). To find a servies of names preceded by \"Resources.\", the command will be `ag --csharp \"Resources\\.(name1|name2|name3|...)\"`"
}
] | [
{
"body": "<p>I also suggest to use a better RegEx but stay with PowerShell.</p>\n\n<p>Without exactly knowing your <code>$testnames</code> you can manually or automatically build a RegEx with a <a href=\"https://www.regular-expressions.info/lookaround.html\" rel=\"nofollow noreferrer\">lookbehind</a> and <a href=\"https://www.regular-expressions.info/alternation.html\" rel=\"nofollow noreferrer\">alternations</a> and read the <code>*.cs</code> files only once.</p>\n\n<pre><code>## build some sample files \n'foo','bar','baz'|ForEach-Object{\"Resources.$_\" > \"$_.cs\"}\n\n$testnames = [RegEx]\"(?<=Resources\\.)(foo|bar|baz)\"\n# (zero length look behind assertion)(alternation)\n\n$Result = Get-ChildItem *.cs -Recurse -File | \n Select-String -Pattern $testnames|\n Select-Object @{n='UsedIcons';e={$_.Matches.Groups[0].Value}} -Unique\n\n$Result\n</code></pre>\n\n<p>Sample output:</p>\n\n<pre><code>UsedIcons\n---------\nbar\nbaz\nfoo\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T23:59:34.627",
"Id": "415847",
"Score": "0",
"body": "I didn't need regex, actually. it was a simple string match. Thanks for the answer :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T19:59:27.590",
"Id": "214951",
"ParentId": "214933",
"Score": "1"
}
},
{
"body": "<p>Thanks for the suggestions, I found the most increase in performance came from loading the text of each file into a variable and then doing <code>-match</code> of all needed names in that file. That gave me over 10x improvement in runtime! </p>\n\n<p>Here is final code:</p>\n\n<pre><code>$usedIcons = @()\n$searchList = Get-ChildItem -r *.cs\n\n$searchList | ForEach-Object{\n $file = Get-Content $_ -raw\n foreach ($name in $uniqueNames){\n $pattern = \"Resources.\"+$name\n #$pattern = $name\n $found = $file -match $pattern \n if($found -eq $true){\n Write-Host $name - $_.Name\n $usedIcons += $name\n $uniqueNames = $uniqueNames | Where-Object { $_ -ne $name}\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T23:57:51.363",
"Id": "215065",
"ParentId": "214933",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "215065",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:09:12.103",
"Id": "214933",
"Score": "0",
"Tags": [
"performance",
"strings",
"file-system",
"powershell"
],
"Title": "Search files content fast in powershell"
} | 214933 |
<pre><code># Standard multi choice question template
def multiChoiceQuestion(options: list):
while True:
print("\nEnter the number of your choice - ")
for x in range(len(options)):
print(str((x + 1)) + ". " + options[x])
print("\n")
try:
answer = int(input())
except ValueError:
print("Doesn't seem like a number! Try again!")
continue
if answer < 1 or answer > len(options):
print("That option does not exist! Try again!")
continue
return answer
</code></pre>
<p>I created a template to ask a multi choice question in python. The loop will never reach it's end, since there is always a continue or a return statement. Is the <code>while True</code> condition appropriate for it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:29:25.023",
"Id": "415657",
"Score": "0",
"body": "\"The loop will never reach it's end ... Is the `while True` condition appropriate for it?\" That depends on whether that is the intended behaviour. Is it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T19:32:39.823",
"Id": "415678",
"Score": "1",
"body": "Side note: `for x in len(options):` will produce an error as Python doesn't allow iteration over an integer. 200_success's approach is the way to go here, but for future reference, use `for x in range(len(options)):` if you really need to loop a certain number of times. This takes the `len(options)` integer and creates an interable out of it."
}
] | [
{
"body": "<p>The <code>while True</code> is fine, and is probably the best way to do it. However, the rest of the flow control is a bit clumsy. By rearranging a few statements, you can eliminate the <code>continue</code>s.</p>\n\n<p>PEP 8, the official Python style guide, recommends <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\"><code>lowercase_with_underscores</code> for function names</a> unless you have a good reason to deviate.</p>\n\n<p>The loop to print the numbered menu would be better written using <code>enumerate()</code>. Also, Python supports double-ended comparisons for validating that the answer is in range.</p>\n\n<pre><code>def multi_choice_question(options: list):\n while True:\n print(\"\\nEnter the number of your choice - \")\n for i, option in enumerate(options, 1):\n print(f'{i}. {option}')\n print(\"\\n\")\n try:\n answer = int(input())\n if 1 <= answer <= len(options):\n return answer\n print(\"That option does not exist! Try again!\")\n except ValueError:\n print(\"Doesn't seem like a number! Try again!\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:13:32.520",
"Id": "214936",
"ParentId": "214935",
"Score": "11"
}
},
{
"body": "<p>I think that <code>200_success</code> already covered most points. I would however like to add an alternative idea for the printing part:</p>\n\n<pre><code>print(\"Enter the number of your choice -\",\n *(f'{i}. {opt}' for i, opt in enumerate(options, 1)),\n sep='\\n', end='\\n\\n')\n</code></pre>\n\n<p>Explanation:\nfrom the <a href=\"https://docs.python.org/3/library/functions.html#print\" rel=\"noreferrer\">docs</a> we see that following signature for the print function:</p>\n\n<pre><code> print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False)\n</code></pre>\n\n<p>we can therefore print everything with a single print call instead of three individual ones. I leave it up to you which one you perceive easier to use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T22:52:45.533",
"Id": "214965",
"ParentId": "214935",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "214936",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T16:49:59.417",
"Id": "214935",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"validation"
],
"Title": "Python 3.6+ function to ask for a multiple-choice answer"
} | 214935 |
<p>I have a csv parsing method in my Windows App that reads headers and information from the subsequent lines. I am not sure if I am doing in an efficient way. Please comment.</p>
<pre><code>public List<(string IPN, string FPTech)> GetIPNFPTechFromCSV(string filePath)
{
List<(string, string)> IPNFPTechPairs = new List<(string, string)>();
using (StreamReader csvfileReader = new StreamReader(filePath))
{
List<string> headings = new List<string>();
if (HasHeaderRow)
{
headings = LoadFieldNamesFromHeaderRow(csvfileReader.ReadLine());
if (headings.Count != 2)
return null;
else
{
int IPNPos = headings.IndexOf("PartNumber");
int FPPos = headings.IndexOf("FPTech");
if (IPNPos != -1 && FPPos != -1)
{
string line;
while ((line = csvfileReader.ReadLine()) != null)
{
var IPNFPTechPair = (IPN: line.Split(Delimiter)[IPNPos], FPTech: line.Split(Delimiter)[FPPos]);
IPNFPTechPairs.Add(IPNFPTechPair);
}
}
else
return null;
}
}
else
return null;
}
return IPNFPTechPairs;
}
</code></pre>
<p>In the caller I am doing</p>
<pre><code>var InputPairs = inputcsvfile.GetIPNFPTechFromCSV(txt_filePath.Text);
if (InputPairs == null)
{
MessageBox.Show("Please make sure input file is in valid format with PartNumber,FPTech Headers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
</code></pre>
<p>To me, it looks like I am returning nulls from too many paths in my csv parsing method. Please let me know how can I improve this code. I am also not sure how do we efficiently log or report eceptions though out the Windows App. Any ideas are welcome please.</p>
<p>Sample Input CSV File</p>
<pre><code>FPTech,PartNumber
TK0,H19873-001
TK1,H19873-001
TK2,H19872-001
TK1,H19874-001
TK0,H19872-001
</code></pre>
<p>The input .csv should be in this format and the FPTech and PartNumber Headers can interchange and sometime smissing. When missing, any of these I want to report to user.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T18:50:03.930",
"Id": "415671",
"Score": "0",
"body": "In order to fully examine the effectiveness of your code, a sample of the data that includes any variations that you expect, would be helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T18:57:12.767",
"Id": "415672",
"Score": "0",
"body": "updated it with sample input with 6 lines"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T20:35:59.087",
"Id": "415684",
"Score": "0",
"body": "Does the return type have to be a list?"
}
] | [
{
"body": "<blockquote>\n<pre><code> if (HasHeaderRow)\n {\n</code></pre>\n</blockquote>\n\n<p>It seems strange, that you know in advance, if the file has headers or not? If that is right, why then call the method in the first place if <code>HasHeaderRow</code> is <code>false</code> - when you do nothing in that case?</p>\n\n<hr>\n\n<blockquote>\n <p><code>public List<(string IPN, string FPTech)> GetIPNFPTechFromCSV(string filePath)</code></p>\n</blockquote>\n\n<ol>\n<li>I would return <code>IEnumerable<..></code> instead and then use <code>yield return</code> to return each data pair (see below).</li>\n<li>I would define a <code>struct</code> or <code>class</code> instead of using a <code>named tuple</code>. IMO <code>named tuples</code> are only useful very locally, because they can be harder to maintain, if their definition changes and you distribute them across the application (see below).</li>\n</ol>\n\n<hr>\n\n<blockquote>\n<pre><code> var IPNFPTechPair = (IPN: line.Split(Delimiter)[IPNPos], FPTech: line.Split(Delimiter)[FPPos]);\n</code></pre>\n</blockquote>\n\n<p>Here you split the same string twice. It would be better to do:</p>\n\n<pre><code>string[] cells = line.Split(Delimiter);\nvar IPNFPTechPair = (IPN: cells[IPNPos], FPTech: cells[FPPos]);\n</code></pre>\n\n<hr>\n\n<p>You should handle all the heading stuff in a separate method in order to make the design and responsibility more clear.</p>\n\n<hr>\n\n<p>All in all I would do something like:</p>\n\n<pre><code>public IEnumerable<IpnItem> Read(string filePath)\n{\n using (StreamReader reader = new StreamReader(filePath))\n {\n (int ipnColumn, int fptechColumn) = ReadHeaders(reader);\n\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n string[] cells = line.Split(Delimiter);\n yield return new IpnItem(cells[ipnColumn], cells[fptechColumn]);\n }\n }\n}\n\nprivate (int ipnColumn, int fptechColumn) ReadHeaders(StreamReader reader)\n{\n string[] headers = reader.ReadLine().Split(Delimiter);\n if (headers.Length != 2) throw new Exception(\"Number of column headers should be 2\");\n (int ipnColumn, int fptechColumn) columnIndices = (Array.IndexOf(headers, \"PartNumber\"), Array.IndexOf(headers, \"FPTech\"));\n if (columnIndices.ipnColumn == -1 || columnIndices.fptechColumn == -1) throw new Exception(\"Invalid or missing column names\");\n return columnIndices;\n}\n</code></pre>\n\n<p>Where <code>IpnItem</code> is declared as:</p>\n\n<pre><code> public class IpnItem\n {\n public IpnItem(string ipn, string fpTech)\n {\n IPN = ipn;\n FPTech = fpTech;\n }\n\n public string IPN { get; private set; }\n public string FPTech { get; private set; }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T23:01:47.193",
"Id": "415711",
"Score": "0",
"body": "I'd also re-use the `ReadHeaders` function to read the data rows (and rename accordingly) - the function presumably already contains the required logic to split a line, as there's no difference in the syntax."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T20:33:17.083",
"Id": "214954",
"ParentId": "214942",
"Score": "2"
}
},
{
"body": "<p>Another option you have is to read the data into a <code>DataTable</code>. This represents the data basically the same as a list of a custom type without having to create that type. </p>\n\n<p>Once the data is read, it can be searched for null values and the return set accordingly, or if it might be desired it is relatively simple to return a set of rows that contain the incomplete data.</p>\n\n<p>Simple function for this could look like this:</p>\n\n<pre><code>public DataTable GetIPNFPTechFromCSV(string fileName)\n{\n const string BOM = \"\";\n string directory = System.IO.Path.GetDirectoryName(fileName);\n if( directory == \"\")\n {\n directory = @\".\\\";\n }\n string file = System.IO.Path.GetFileName(fileName);\n OdbcConnection conn = new OdbcConnection($@\"Driver={{Microsoft Text Driver (*.txt; *.csv)}};Dbq={directory};FMT=Delimited','\");\n using (OdbcDataAdapter da = new OdbcDataAdapter($@\"Select * from [{file}]\", conn))\n DataTable dt = new DataTable();\n using (OdbcDataAdapter da = new OdbcDataAdapter(com))\n {\n da.Fill(dt);\n }\n if(dt.Columns[0].ColumnName.StartsWith(BOM))\n {\n dt.Columns[0].ColumnName = dt.Columns[0].ColumnName.Trim(BOM.ToArray());\n }\n bool goodData = dt.Select().All(x => !x.ItemArray.Contains(DBNull.Value));\n if(goodData)\n {\n return dt;\n }\n else\n {\n return null;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T08:13:43.697",
"Id": "415739",
"Score": "0",
"body": "You can use `Encoding.UTF8.GetPreamble()` instead of hardcoding the `BOM` :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T23:22:59.743",
"Id": "214970",
"ParentId": "214942",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T18:38:50.647",
"Id": "214942",
"Score": "3",
"Tags": [
"c#",
"winforms"
],
"Title": "CSV reader in Windows Forms"
} | 214942 |
<p>I've been making this pet project of mine which is an implementation of a HashTable for a very specific purpose: storing huge amounts of objects in-memory (think Redis). I ended up with this implementation in C++ which is in my opinion a very basic and generic Java-inspired HashTable using buckets. I'd like to hear advice on what to do next to make those narrow optimizations and what approaches are the best to try out. Also I've strived to make my code in the spirit of STL, and I don't think I managed to do that properly (C++ isn't my main language, I actually come from Python).</p>
<p>You can clone the code with tests <a href="https://github.com/Korbiwe/hash_table" rel="nofollow noreferrer">here</a> (github link, cmake 3.13 or higher required)</p>
<pre><code>#pragma once
//
// Created by korbiwe on 2019-02-05.
//
#include <functional>
#include <vector>
#include <list>
#include <string>
#include "util.h"
namespace lib {
namespace {
using index_t = unsigned;
};
template<class Key, class T, class Hash = std::hash<T>>
class HashTable {
public:
using key_t = Key;
using mapped_t = T;
using pair_t = std::pair<const Key, T>;
using bucket_t = std::list<pair_t>;
using table_t = std::vector<bucket_t>;
using reference = pair_t&;
using const_reference = const pair_t&;
explicit HashTable(size_t capacity = 8, double load_factor = 0.75);
T& at(const Key& key);
T& operator[](const Key& key);
void erase(const Key& key);
void insert(const pair_t& pair);
size_t size() const;
bool empty() const;
private:
void _expand_and_rehash();
const bucket_t& _resolve_key(const Key& key) const;
bucket_t& _resolve_key(const Key& key);
size_t _capacity;
size_t _size = 0;
double _load_factor;
table_t _table;
Hash _hash_f;
};
template<class Key, class T, class Hash>
HashTable<Key, T, Hash>::HashTable(size_t capacity, double load_factor) :
_capacity(round_up_to_power_of_two(capacity)),
_load_factor(load_factor),
_table(table_t(_capacity)) {
}
template<class Key, class T, class Hash>
void HashTable<Key, T, Hash>::insert(const HashTable::pair_t& pair) {
Key key = pair.first;
T value = pair.second;
bucket_t& bucket = _resolve_key(key);
bucket.push_back(pair);
_size++;
if (_size > _capacity * _load_factor)
_expand_and_rehash();
}
template<class Key, class T, class Hash>
T& HashTable<Key, T, Hash>::at(const Key& key) {
bucket_t& bucket = _resolve_key(key);
#ifdef DEBUG
std::cout << "Lookup in a bucket with " << std::to_string(bucket.size()) << " elements.";
#endif
auto found = std::find_if(bucket.begin(), bucket.end(), [&key](pair_t pair) { return pair.first == key; });
if (bucket.empty() || found == bucket.end()) {
throw std::out_of_range("HashTable::at");
}
return found->second;
}
template<class Key, class T, class Hash>
void HashTable<Key, T, Hash>::_expand_and_rehash() {
#ifdef DEBUG
std::cout << "Rehashing at capacity "
<< std::to_string(_capacity)
<< " and size "
<< std::to_string(_size)
<< "."
<< std::endl;
std::cout << "Load factor at "
<< std::to_string(static_cast<double>(_size) / _capacity)
<< " before rehashing"
<< std::endl;
#endif
table_t temporary = _table;
_capacity *= 2;
_table = table_t(_capacity);
for (bucket_t bucket : temporary) {
if (bucket.empty()) continue;
for (pair_t entry : bucket) {
bucket_t& new_bucket = _resolve_key(entry.first);
new_bucket.push_back(entry);
}
}
#ifdef DEBUG
std::cout
<< "... and "
<< std::to_string(static_cast<double>(_size) / _capacity)
<< " after rehashing."
<< std::endl;
#endif
}
template<class Key, class T, class Hash>
T& HashTable<Key, T, Hash>::operator[](const Key& key) {
bucket_t& bucket = _resolve_key(key);
#ifdef DEBUG
std::cout << "Lookup in a bucket with " << std::to_string(bucket.size()) << " elements.";
#endif
auto found = std::find_if(bucket.begin(), bucket.end(), [&key](const pair_t& pair) { return pair.first == key; });
if (bucket.empty() || found == bucket.end()) {
pair_t& default_ = bucket.emplace_back(key, T());
return default_.second;
}
return found->second;
}
template<class Key, class T, class Hash>
bool HashTable<Key, T, Hash>::empty() const {
return _size == 0;
}
template<class Key, class T, class Hash>
size_t HashTable<Key, T, Hash>::size() const {
return _size;
}
template<class Key, class T, class Hash>
void HashTable<Key, T, Hash>::erase(const Key& key) {
bucket_t& bucket = _resolve_key(key);
auto found = std::find_if(bucket.begin(), bucket.end(), [&key](const pair_t& pair) { return pair.first == key; });
if (bucket.empty() || found == bucket.end()) {
throw std::out_of_range("HashTable::erase");
}
bucket.erase(found);
}
template<class Key, class T, class Hash>
const typename HashTable<Key, T, Hash>::bucket_t& HashTable<Key, T, Hash>::_resolve_key(const Key& key) const {
return _table[_hash_f(key) % _capacity];
}
template<class Key, class T, class Hash>
typename HashTable<Key, T, Hash>::bucket_t& HashTable<Key, T, Hash>::_resolve_key(const Key& key) {
return _table[_hash_f(key) % _capacity];
}
}; // end namespace lib
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T20:23:07.010",
"Id": "415683",
"Score": "0",
"body": "What's in `\"util.h\"`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T21:41:37.930",
"Id": "415701",
"Score": "0",
"body": "Just the round_up_to_power_of_two() function, nothing else. It's pretty trivial, thought it would be redundant to include the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T22:42:50.930",
"Id": "415709",
"Score": "0",
"body": "Even if you don't want that part reviewed, it can be helpful to reviewers if you provide it and the unit tests - we can make better suggestions when we can compile and run the code. It's not a requirement, but can get you better reviews!"
}
] | [
{
"body": "<p>In your constructor, you can construct <code>_table</code> with just <code>_table(capacity)</code>.</p>\n\n<p>In <code>_expand_and_rehash</code>, you're making copies of vectors you don't need to make. First, you can move <code>table</code> to <code>temporary</code> using <code>table_t temporary = std::move(table);</code>. When copying the data to the new table, you're creating copies of the lists. Use a rerefences in those loop: <code>for (const bucket_t &bucket : temporary)</code> and <code>for (const pair_t &entry : bucket)</code>. Then replace <code>new_bucket.push_back</code> with <code>new_bucket.emplace_back</code>, which will avoid another potential copy.</p>\n\n<p>You might be able to defer the check for a rehash which is made in <code>insert</code> to the next insert. (i.e., check for if a rehash is necessary at the start of <code>insert</code>, rather than at the end.) The downside is that you wouldn't be able to insert an object already in the HashTable. Which brings up an important point: you currently allow duplicates. If you insert the same thing twice, you'll get two copies of that key in the HashTable. Is that what you want? (<code>erase</code> will delete the first one it finds if there is more than one.)</p>\n\n<p>There's no need to check <code>bucket.empty()</code> after your various calls to <code>find_if</code>, since if the bucket is empty the <code>find_if</code> won't find what you're looking for and will return <code>bucket.end()</code> (which you're already checking for).</p>\n\n<p>In <code>insert</code>, you can remove the local <code>value</code> variable, which is unused. There's no real reason to have <code>key</code> in there, either, since it is only used once.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T04:54:55.517",
"Id": "214984",
"ParentId": "214943",
"Score": "2"
}
},
{
"body": "<p>Missing includes:</p>\n\n<pre><code>#include <cstddef>\n#include <stdexcept>\n#include <utility>\n\n#ifdef DEBUG\n#include <iostream>\n#endif\n</code></pre>\n\n<p>Also, <code>std::size_t</code> is misspelt throughout.</p>\n\n<hr>\n\n<p>We seem to be missing <code>const</code> overloads for <code>at()</code> and <code>operator[]</code>. They are certainly worth having.</p>\n\n<hr>\n\n<p>There's a few instances of the code to find a particular key within a bucket:</p>\n\n<pre><code>auto found = std::find_if(bucket.begin(), bucket.end(),\n [&key](const pair_t& pair) { return pair.first == key; });\n</code></pre>\n\n<p>(my linebreak added for legibility).</p>\n\n<p>It's probably worth refactoring that into a small function of its own (remember that it's almost certainly going to be inlined, making no change to the object code).</p>\n\n<p>That's frequently followed by</p>\n\n<pre><code> if (bucket.empty() || found == bucket.end()) {\n</code></pre>\n\n<p>There's no value in the <code>bucket.empty()</code> test - if the bucket was empty, then <code>found</code> will inevitable be <code>bucket.end()</code>. (There's no benefit to moving the <code>bucket.empty()</code> test before the <code>std::find_f()</code>; just remove it).</p>\n\n<hr>\n\n<p>We could make the member function signatures much easier to read by including the definitions within the class body. For example, compare this:</p>\n\n<blockquote>\n<pre><code>template<class Key, class T, class Hash>\nconst typename HashTable<Key, T, Hash>::bucket_t& HashTable<Key, T, Hash>::_resolve_key(const Key& key) const {\n return _table[_hash_f(key) % _capacity];\n}\n\ntemplate<class Key, class T, class Hash>\ntypename HashTable<Key, T, Hash>::bucket_t& HashTable<Key, T, Hash>::_resolve_key(const Key& key) {\n return _table[_hash_f(key) % _capacity];\n}\n</code></pre>\n</blockquote>\n\n<p>with:</p>\n\n<pre><code>private:\n\n const bucket_t& _resolve_key(const Key& key) const\n {\n return _table[_hash_f(key) % _capacity];\n }\n\n bucket_t& _resolve_key(const Key& key)\n {\n return _table[_hash_f(key) % _capacity];\n }\n</code></pre>\n\n<hr>\n\n<p>To reduce copying, I think <code>insert()</code> should take its argument by value, and then <code>std::move()</code> it:</p>\n\n<pre><code>void HashTable<Key, T, Hash>::insert(HashTable::pair_t pair)\n{\n bucket_t& bucket = _resolve_key(pair.first);\n bucket.push_back(std::move(pair));\n</code></pre>\n\n<p>In passing, should <code>insert()</code> allow us to add elements with keys that are already in the bucket? That's not what <code>std::unordered_map::insert()</code> does.</p>\n\n<p><code>_expand_and_rehash()</code> is another function where we could usefully move instead of copying. We should be able to get the whole class working with move-only types; it's worth adding tests that instantiate and use the class with <code>T</code> as (say) <code>std::unique_ptr</code> and dealing with copies until that works.</p>\n\n<hr>\n\n<p>Since this is intended to hold \"huge amounts\" of entries, we really need a <code>reserve()</code> member, for those cases where we construct before knowing how many elements we'll add (e.g. when a <code>HashTable</code> is a member of some other object).</p>\n\n<p>Consider the usage pattern (mainly the mix of insert, lookup, and erase) to decide whether <code>std::list</code> is the appropriate type for <code>bucket_t</code>. We might want to implement our own (perhaps a \"chunked list\", for example, to reduce the number of individual allocations).</p>\n\n<hr>\n\n<p>It's just style, but I'm not a big fan of prefixing the private members with <code>_</code>. It makes the code look like Python rather than C++, and hurts readability.</p>\n\n<p>I have a simple theory that if we need a mnemonic to keep track of which identifiers are which, then there's probably too much in the class and we need to think about splitting its responsibilities.</p>\n\n<hr>\n\n<p>Final thought: I'm not sure what I'm missing, but I don't see anything here that makes this class any more suitable than <code>std::unordered_map</code> for \"huge numbers of objects\". That suggests we need to add some comments to point out the adaptations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T18:35:46.933",
"Id": "415832",
"Score": "0",
"body": "Thanks a lot for your review! I agree with all of your points, but have a thing to point out: it doesn't have specific adaptations for big numbers of stored objects because I didn't yet add them. That was the point of the question -- to get advice on what to do next to make those adaptations, what are the possible ways to make them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T18:40:53.057",
"Id": "415833",
"Score": "0",
"body": "Also, what would be your advice about private class members? Is it a bad sign if I tend to have public data members (I tend not to, but that was the point of underscoring the private ones, to distinguish them from the public ones)? If it is, then I agree with you fully, since I've been thinking about that for a while and underscoring private members is just really a bad habit of mine."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T08:57:17.813",
"Id": "215004",
"ParentId": "214943",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215004",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T18:44:05.413",
"Id": "214943",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"hash-map"
],
"Title": "A HashTable optimised for a large in-memory storage"
} | 214943 |
<p>This website has been created for a student organization that is focused on engineering solutions for people with disabilities. With that in mind, I would like this code to be as accessible as possible, so reviews focusing on that will be appreciated. Besides that, optimizations/simplifications to the CSS or HTML that don't change behavior of the page would also be appreciated.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body, html {
font-size: 16px;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
background: #fff;
line-height: 170%;
height: 100%;
}
strong,
b {
font-weight: 600
}
hr {
border: 0;
clear:both;
display:block;
width: 96%;
background-color:#333;
height: 1px;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-weight: 300;
line-height: 150%;
}
i.fa {
color: #333;
margin-left: 6pt;
}
*,
*:before,
*:after {
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
/*clearfixes*/
.cf:before,
.cf:after {
content: " ";
display: table;
}
.cf:after {
clear: both;
}
.main-container {
background: #fefefe;
max-width: 1000px;
margin: 25px auto 25px auto;
position: relative;
width: 100%;
}
.container {
position: relative;
padding: 0px 25px 0px 25px;
}
/*animation slide left styled for profile*/
.profile {
float: left;
width: 100%;
margin: 0% 0% 3% 0%;
background: #F5F5F5;
padding: 15px;
box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.2);
border: solid 1px #EAEAEA;
}
.profile .header{
float: left;
width: 100%;
margin-bottom: 10px;
}
.profile .left{
float: left;
margin-right: 15px;
}
.profile .right{
float: left;
}
.profile img {
height: 65px;
border-radius: 10%;
box-shadow: 0px 1px 3px rgba(51, 51, 51, 0.5);
}
.profile h3 {
margin: 0px 0px 5px 0px;
}
.profile h4 {
margin: 0px 0px 5px 0px;
}
.profile .content {
float: left;
width:100%;
margin-bottom: 10px;
}
.profile .rating{}
.profile i {
color: #aaa;
margin-right: 5px;
}
/*media queries for small devices*/
@media screen and (max-width: 678px){
/*profile*/
.profile,
.profile:nth-of-type(odd),
.profile:nth-of-type(even){
width: 100%;
margin: 0px 0px 20px 0px;
}
.profile .right,
.profile .left,
.profile .content,
.profile .rating{
text-align: center;
float: none;
}
.profile img{
width: 85px;
height: 85px;
margin-bottom: 5px;
}
}
/*animation slide left styled for profile*/
.project {
float: left;
width: 100%;
margin: 0% 0% 3% 0%;
background: #F5F5F5;
padding: 15px;
box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.2);
border: solid 1px #EAEAEA;
}
.project .header{
float: left;
width: 100%;
margin-bottom: 10px;
}
.project .left{
float: left;
margin-right: 15px;
}
.project .right{
float: left;
}
.project-image-container {
display: flex;
align-items: center;
flex: 1;
margin-right: 15px;
max-height: max-content;
}
.project-image {
width: 100%;
border-radius: 10%;
box-shadow: 0px 1px 3px rgba(51, 51, 51, 0.5);
}
.project h3 {
margin: 0px 0px 5px 0px;
}
.project h4 {
margin: 0px 0px 5px 0px;
}
.project .content {
display: flex;
flex-direction: row;
width:100%;
margin-bottom: 10px;
}
.project .inner-content {
flex: 1;
}
.project .rating{}
.project i {
color: #aaa;
margin-right: 5px;
}
/*media queries for small devices*/
@media screen and (max-width: 678px){
/*profile*/
.project {
width: 100%;
height: auto;
margin: 0px 0px 20px 0px;
}
.project .right,
.project .left,
.project .content,
.project .rating{
display: flex;
flex-direction: column;
text-align: center;
justify-content: center;
}
.project-image-container {
flex: 1;
flex-basis: auto;
}
.project-image {
max-width: max-content;
max-height: max-content;
margin-bottom: 5px;
}
.project-image-container {
align-items: center;
justify-content: center;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
<head>
<title>Organization Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr"
crossorigin="anonymous">
<link href="main.css" type='text/css' rel='stylesheet'>
</head>
<body>
<div class="main-container">
<div class="container">
<h1>Organization Name</h1>
</div>
<div class="container">
<h2>About Us<i class="fa fa-question"></i></h2>
<div class="content">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ultricies, mauris id vestibulum
pulvinar, turpis magna dapibus arcu, sit amet porta est neque id mi. Morbi ut semper libero. Praesent
ac tortor nisl. Sed arcu nisl, finibus finibus turpis et, aliquet fringilla lectus. Phasellus in nisl
nibh. Morbi iaculis ipsum ut purus porttitor congue. Fusce semper tristique justo a efficitur. Donec
venenatis blandit ante, eu cursus quam finibus eget. In congue convallis dui sed rutrum. Suspendisse in
metus a magna rutrum suscipit eget vehicula quam.
</p>
<p>
Vivamus enim augue, varius et fringilla id, iaculis quis eros. Quisque tincidunt lobortis sem, in
posuere metus feugiat sed. Aenean ullamcorper eros nibh, vel pellentesque mi blandit in. Ut semper
interdum nibh, sit amet egestas lorem. Aliquam augue enim, congue tincidunt varius vel, elementum eget
velit. Aliquam interdum nunc lectus, eu aliquam massa sagittis a. Sed molestie fermentum metus, nec
viverra dui fringilla quis. Maecenas sit amet nulla tincidunt, maximus est quis, vestibulum risus.
Aenean lacinia lectus nec lectus eleifend, et congue est tincidunt.
</p>
<p>
Aliquam feugiat nec lectus eget imperdiet. Ut consectetur in ex sed faucibus. Morbi gravida urna non
enim consequat tempus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce efficitur, quam
rhoncus interdum feugiat, ipsum ante venenatis ligula, vitae vestibulum enim est in mauris. Vestibulum
vehicula sit amet ante sit amet hendrerit. Maecenas et eros elit. Vestibulum tempor ac leo ut tempus.
Nulla vitae turpis mauris.
</p>
</div>
</div>
<hr>
<div class="container">
<h2>Our Executives<i class="fa fa-users"></i></h2>
<div class="profile">
<div class="header">
<div class="left">
<img src="https://via.placeholder.com/150" alt=""/>
</div>
<div class="right">
<h3>Executive One</h3>
<h4>Faculty Sponsor</h4>
</div>
</div>
<div class="content"><i class="fa fa-quote-left"></i> Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Pellentesque et porttitor mi. Sed egestas nunc dui, a convallis tellus blandit
eget. Nulla sed elementum nibh. Sed aliquam tellus eu vestibulum aliquam. Ut laoreet libero eget
nisi facilisis varius. Nam cursus arcu velit, quis tempor metus scelerisque at. Nulla sed enim
Proin feugiat elit ut augue luctus, id interdum ex laoreet. Nunc tempor egestas aliquet.<i class="fa fa-quote-right"></i>
</div>
</div>
<div class="profile">
<div class="header">
<div class="left">
<img src="https://via.placeholder.com/150" alt=""/>
</div>
<div class="right">
<h3>Executive Two</h3>
<h4>Faculty Sponsor</h4>
</div>
</div>
<div class="content"><i class="fa fa-quote-left"></i> Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Pellentesque et porttitor mi. Sed egestas nunc dui, a convallis tellus blandit
eget. Nulla sed elementum nibh. Sed aliquam tellus eu vestibulum aliquam. Ut laoreet libero eget
nisi facilisis varius. Nam cursus arcu velit, quis tempor metus scelerisque at. Nulla sed enim
Proin feugiat elit ut augue luctus, id interdum ex laoreet. Nunc tempor egestas aliquet.<i class="fa fa-quote-right"></i>
</div>
</div>
<div class="profile">
<div class="header">
<div class="left">
<img src="https://via.placeholder.com/150" alt=""/>
</div>
<div class="right">
<h3>Executive Three</h3>
<h4>Student Lead</h4>
</div>
</div>
<div class="content"><i class="fa fa-quote-left"></i> Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Pellentesque et porttitor mi. Sed egestas nunc dui, a convallis tellus blandit
eget. Nulla sed elementum nibh. Sed aliquam tellus eu vestibulum aliquam. Ut laoreet libero eget
nisi facilisis varius. Nam cursus arcu velit, quis tempor metus scelerisque at. Nulla sed enim
Proin feugiat elit ut augue luctus, id interdum ex laoreet. Nunc tempor egestas aliquet.<i class="fa fa-quote-right"></i>
</div>
</div>
</div>
<hr>
<div class="container">
<h2>
Our Projects <i class="fa fa-project-diagram"></i></h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tristique, felis sed blandit
consequat, odio velit volutpat ligula, eu semper ligula est ac ex. In hac habitasse platea dictumst.
Curabitur sagittis aliquet elit, ac dictum lacus faucibus sagittis. Vestibulum hendrerit ligula ut ante
auctor gravida et eget augue. Aenean posuere, dui sit amet finibus tristique, mauris tellus sagittis
ex, et tempus orci ante vel magna. Vestibulum mollis sollicitudin ex, et scelerisque sapien suscipit
et. Nullam auctor, diam ac aliquam efficitur, ex nunc viverra odio, sit amet congue lorem lacus eget
dui. Quisque tellus urna, luctus vitae tincidunt a, eleifend in justo. Nam eget dolor id lacus varius
facilisis sed sed ex. Ut mattis tortor quis justo egestas, rutrum vehicula augue dictum.
</p>
<p>
Suspendisse a tellus a quam egestas lacinia eu ac lorem. Nam vel tellus urna.
Etiam ac orci venenatis, posuere libero a, volutpat turpis. Aenean lobortis nec libero in sagittis.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque in risus velit. Aliquam dapibus
imperdiet vehicula. Morbi urna leo, maximus ac viverra nec, dapibus nec mi. Integer quis quam commodo,
lobortis augue sit amet, molestie est. Integer malesuada tellus commodo, rutrum nunc et, feugiat
libero. Vestibulum eu sem sed nibh tempus dignissim eget at ligula. Cras et lacus mauris.
</p>
</div>
<div class="container cf">
<!--
Project One
-->
<div class="project">
<div class="content">
<div class="project-image-container">
<img class="project-image" src="https://via.placeholder.com/150" alt=""/>
</div>
<div class="inner-content">
<h2><b>A Project</b></h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque euismod ullamcorper
mauris
eget scelerisque. Suspendisse leo orci, aliquet at felis sed, tincidunt elementum ligula.
Curabitur
viverra felis ante, sed posuere mauris consectetur a. Integer interdum odio eleifend
interdum
rhoncus. Curabitur nec leo ultrices, cursus augue et, rutrum risus. Suspendisse vulputate
justo nec
sodales tristique. Curabitur sit amet orci lacinia, tincidunt dolor vel, consequat tortor.
Sed in
lectus vitae tellus pellentesque varius. Quisque a vehicula tellus, eu molestie purus.
</p>
<p>
Phasellus fringilla feugiat augue quis ultrices. Aliquam libero diam, viverra ut varius
eget,
scelerisque at massa. Etiam sodales sit amet quam eu egestas. Suspendisse sit amet mauris
dui.
Curabitur a nibh in velit imperdiet dignissim. Sed pulvinar aliquet erat, porta blandit
eros
rhoncus quis. Phasellus et fermentum odio. Vestibulum condimentum convallis nisl et
pellentesque.
Praesent vel nibh non leo pulvinar fringilla vel eget dui. Maecenas aliquam magna nec justo
pulvinar, fringilla porta augue viverra. Proin ac convallis nisl. Cras eu pharetra lacus,
eu
convallis mauris. Donec facilisis nisi eget lorem euismod, eget tincidunt purus sodales.
Quisque
mattis enim ut mauris pretium, id viverra arcu luctus. Duis velit massa, commodo nec
lacinia a,
malesuada tincidunt lectus. Proin felis nibh, luctus quis volutpat eget, porta a lorem.
</p>
</div>
</div>
</div>
<!--
Project Two
-->
<div class="project">
<div class="content">
<div class="project-image-container">
<img class="project-image" src="https://via.placeholder.com/150" alt=""/>
</div>
<div class="inner-content">
<h2><b>Another Project</b></h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque euismod ullamcorper
mauris
eget scelerisque. Suspendisse leo orci, aliquet at felis sed, tincidunt elementum ligula.
Curabitur
viverra felis ante, sed posuere mauris consectetur a. Integer interdum odio eleifend
interdum
rhoncus. Curabitur nec leo ultrices, cursus augue et, rutrum risus. Suspendisse vulputate
justo nec
sodales tristique. Curabitur sit amet orci lacinia, tincidunt dolor vel, consequat tortor.
Sed in
lectus vitae tellus pellentesque varius. Quisque a vehicula tellus, eu molestie purus.
</p>
<p>
Phasellus fringilla feugiat augue quis ultrices. Aliquam libero diam, viverra ut varius
eget,
scelerisque at massa. Etiam sodales sit amet quam eu egestas. Suspendisse sit amet mauris
dui.
Curabitur a nibh in velit imperdiet dignissim. Sed pulvinar aliquet erat, porta blandit
eros
rhoncus quis. Phasellus et fermentum odio. Vestibulum condimentum convallis nisl et
pellentesque.
Praesent vel nibh non leo pulvinar fringilla vel eget dui. Maecenas aliquam magna nec justo
pulvinar, fringilla porta augue viverra. Proin ac convallis nisl. Cras eu pharetra lacus,
eu
convallis mauris. Donec facilisis nisi eget lorem euismod, eget tincidunt purus sodales.
Quisque
mattis enim ut mauris pretium, id viverra arcu luctus. Duis velit massa, commodo nec
lacinia a,
malesuada tincidunt lectus. Proin felis nibh, luctus quis volutpat eget, porta a lorem.
</p>
</div>
</div>
</div>
</div>
<hr>
<div class="container">
<h2>Contact Us<i class="fa fa-broadcast-tower"></i></h2>
<div class="content">
<b>Email: </b>email@domain.com<br>
<b>Phone: </b>(123) 456-7890
</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T05:53:31.030",
"Id": "415728",
"Score": "1",
"body": "Run both your HTML and CSS through the W3C validator."
}
] | [
{
"body": "<p><code>alt</code> tags should be filled, and the contact email should be a clickable link. You might also want to add a table of contents and link to <code>a</code> tags for the different sections. Which also means you should use semantically loaded HTML5 tags (e.g. section) instead of just <code>div</code>s</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T04:00:36.173",
"Id": "415961",
"Score": "0",
"body": "I didn't fill the alt tags because each of the images will have text next to them that will function as the alt text. If I add it in, screen readers would read it twice. I did take your advice to change over to semantic HTML5 tags and will consider adding a table of contents."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-13T13:39:47.143",
"Id": "416492",
"Score": "0",
"body": "You should still put empty alt attributes, at least, so screen readers don't read the (probably pointless) filename instead."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T07:28:35.050",
"Id": "214999",
"ParentId": "214944",
"Score": "1"
}
},
{
"body": "<pre><code>h1,\nh2,\nh3,\nh4,\nh5,\nh6 {\n font-weight: 300;\n line-height: 150%;\n}\n</code></pre>\n\n<p>having all levels of headers be the same size kind of defeats the purpose of having different levels of headers</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-10T03:58:44.817",
"Id": "415960",
"Score": "0",
"body": "I agree. Changed it and it looks better and is easier to read!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-08T08:39:14.553",
"Id": "215002",
"ParentId": "214944",
"Score": "2"
}
},
{
"body": "<h3>About the HTML</h3>\n\n<ul>\n<li><p>(1) You are missing the DOCTYPE (first line of the document):</p>\n\n<pre><code><!DOCTYPE html>\n</code></pre></li>\n<li><p>(2) It’s typically a good idea to set the character encoding (first element in the <code>head</code>):</p>\n\n<pre><code><meta charset=\"utf-8\"> <!-- assuming UTF-8 -->\n</code></pre></li>\n<li><p>(3) The <code>i</code> element <a href=\"https://stackoverflow.com/a/22501699/1591669\">should not</a> be used for adding images via CSS. Use a meaningless <code>span</code> element instead:</p>\n\n<pre><code><span class=\"fa fa-question\"></span>\n</code></pre></li>\n<li><p>(4) The <code>hr</code> should not be used between sections (heading elements open implicit sections). Use CSS instead.</p></li>\n<li><p>(5) Don’t use a heading element (<code>h4</code>) for a sub-heading; use <code>p</code> instead:</p>\n\n<pre><code><h3>Executive One</h3>\n<p>Faculty Sponsor</p>\n</code></pre></li>\n<li><p>(6) The heading for an individual project should be <code>h3</code> instead of <code>h2</code>.</p></li>\n<li><p>(7) There is typically no need to use <code>b</code> in a heading (unless you only mark up a part of the heading). Use CSS instead.</p></li>\n<li><p>(8) You can link the email address and telephone number (see below).</p></li>\n<li><p>(9) For a list with name-value pairs, you can use the <code>dl</code> element:</p>\n\n<pre><code><dl>\n <dt>Email:</dt> <dd><a href=\"mailto:email@domain.com\">email@domain.com</a></dd>\n <dt>Phone:</dt> <dd><a href=\"tel:123-456-7890\">(123) 456-7890</a></dd>\n</dl>\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-11T02:38:01.060",
"Id": "215163",
"ParentId": "214944",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215163",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T18:47:51.613",
"Id": "214944",
"Score": "3",
"Tags": [
"css",
"html5"
],
"Title": "Website for student organization"
} | 214944 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.